Dynamic importing

Peter Abel p-abel at t-online.de
Sun Jun 22 10:40:38 EDT 2003


googlenews at ols.inorganic.org (Roy S. Rapoport) wrote in message news:<533b36b0.0306212352.7c5849cb at posting.google.com>...
...
...
[snip]
> In other words, I want master to look something like:
> class master:
>   def dosomething(self, what):
>      mod = __import__(what)

I think you're quite near:

>      mod.what.do_something()

Try:   mod.do_something()
For example the following works:
>>> my_os=__import__('os')
>>> my_os.getcwd()
'C:\\PROGRA~1\\Python22\\lib\\site-packages'
>>> 
> 

> Obviously, the syntax is incorrect here, but I'm having a problem
> figuring out what the syntax should be.  My current 'best guess' is
> something like this:
> class master:
>         def dosomething(self, what):
>                 x = __import__("demo."+what)
>                 print x
> 
> What I find interesting here is that, if I understand 6.4.2 of the
> tutorial correctly, I shouldn't even need to say "demo."+what -- since
> master is in the same package as whatever what is, it should just work
> -- which means it's possible I don't quite understand everything I
> need to put in demo/__init__.py (which is currently an empty file). 

I didn't try it, but it seems to be as you said.

> Either way, the above actually gives me "<module 'demo' from
> './demo/__init__.pyc'>", so it seems that for some reason it's not
> even importing the module in question, but rather the package itself.
> 
> Allow me to helpfully summarize:  I'm clueless when it comes to the
> usage of packages and dynamic importing and function referencing. 
> What document should I read that will help me understand these
> concepts better as they work in Python?
> 
> -roy

Regards
Peter




More information about the Python-list mailing list