By using this site, you agree to our updated Privacy Policy and our Terms of Use. Manage your Cookies Settings.
455,548 Members | 1,454 Online
Bytes IT Community
+ Ask a Question
Need help? Post your question and get tips & solutions from a community of 455,548 IT Pros & Developers. It's quick & easy.

question about import

P: n/a
I'm a little unclear about import / __import__

I'm exploring dynamically importing modules for a project, and ran
into this behavior

works as expected:
app = __import__( myapp )
appModel = __import__( myapp.model )

but...
appname= 'myapp'
app = __import__( "%s" % appname )
appModel = __import__( "%s.model" % appname )

In the latter example, app and appModel will always seem to be
imported as 'myapp' , and I've yet to find a way to address the .model
namespace

I know 'dynamically importing modules' is cursed upon -- and I'm
likely rewriting hundreds of line of codes so I can work around this
with a registration system -- however I'd like to understand why this
occurs and know if what i'm trying is even possible.
Jun 27 '08 #1
Share this Question
Share on Google+
2 Replies


P: n/a
Jonathan Vanasco schrieb:
I'm a little unclear about import / __import__

I'm exploring dynamically importing modules for a project, and ran
into this behavior

works as expected:
app = __import__( myapp )
appModel = __import__( myapp.model )

but...
appname= 'myapp'
app = __import__( "%s" % appname )
appModel = __import__( "%s.model" % appname )

In the latter example, app and appModel will always seem to be
imported as 'myapp' , and I've yet to find a way to address the .model
namespace

I know 'dynamically importing modules' is cursed upon -- and I'm
likely rewriting hundreds of line of codes so I can work around this
with a registration system -- however I'd like to understand why this
occurs and know if what i'm trying is even possible.
Is it cursed upon? Didn't know that.

However, __import__ only gives you the topmost module - in your case myapp.

So you need to do it like this (untested):

name = "a.b.c.d"
mod = __import__(name)
for part in name.split(".")[1:]:
mod = getattr(mod, part)
print mod

Diez
Jun 27 '08 #2

P: n/a
On Jun 11, 1:45*pm, "Diez B. Roggisch" <de...@nospam.web.dewrote:
Is it cursed upon? Didn't know that.
I didn't either. Until I asked some people how to do it, and was
admonished for even suggesting the concept.

However, __import__ only gives you the topmost module - in your case myapp..
ah, i didn't know that! thanks!

So you need to do it like this (untested):

name = "a.b.c.d"
mod = __import__(name)
for part in name.split(".")[1:]:
* * *mod = getattr(mod, part)
print mod
interesting approach. unfortunately, it raises AttributeError: 'a'
object has no attribute 'b'

i think i'm going to table this approach. sigh.

Jun 27 '08 #3

This discussion thread is closed

Replies have been disabled for this discussion.