Dynamic importing

Roy S. Rapoport googlenews at ols.inorganic.org
Sun Jun 22 03:52:31 EDT 2003


This isn't the first time I've needed to resort to __import__, but I'm
having a problem figuring out how to make it jump through my hoops,
because I'm not quite very comfortable this low in the language.

Scenario:
package demo contains:
  class master
  class one
  class two

All in their own file ('master.py', 'one.py', 'two.py').  

All three classes contain a method called 'dosomething'.  In the case
of class one and two, dosomething takes no args (other than self, of
course) and simply prints "dosomething called from module (one|two)"
as appropriate.

I want to make it so master's dosomething method takes one argument,
which should be the name of a class to import, and then call that
classe's dosomething method.

In other words, I want master to look something like:
class master:
  def dosomething(self, what):
     mod = __import__(what)
     mod.what.do_something()

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). 
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




More information about the Python-list mailing list