Dynamic importing

Roy S. Rapoport googlenews at ols.inorganic.org
Mon Jun 23 02:47:39 EDT 2003


p-abel at t-online.de (Peter Abel) wrote in message news:<13a533e8.0306220640.29d8a09b at posting.google.com>...
> 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()

I've done some more work on this, and I'm pretty sure at this point
that the problems I'm running into are based on the fact that this is
a package, rather than a set of modules.  Check this out:
module approach:

class master:
        def dosomething(self, what):
                
                x = __import__(what)
                y = eval("x.%s()" % what)
                eval("y.dosomething()")

class onec:
        def dosomething(self):
                print "class one called to do something"


class twoc:
        def dosomething(self):
                print "class two called to do something"

(the extra eval there is because we're dealing with a method of a
class inside a module, whereas in the case of of your my_os there,
getcwd() is just a function).

So the above works perfectly.  Given:
import master
F = master.master()

F.dosomething('onec')
F.dosomething('twoc')

I get:
class one called to do something
class two called to do something

However, lets look at the package approach:
onec.py and twoc.py remain the same.  master.py looks slightly
different:
class master:
        def dosomething(self, what):
                
                x = __import__("demo."+what)
                y = eval("x.%s()" % what)
                eval("y.dosomething()")


(so the only difference is in that import statement).

Running the test code:
import demo.master
F = demo.master.master()
F.dosomething('one')

Gets me 
---
Traceback (most recent call last):
  File "./f2", line 6, in ?
    F.dosomething('one')
  File "./demo/master.py", line 5, in dosomething
    y = eval("x.%s()" % what)
  File "<string>", line 0, in ?
TypeError: 'module' object is not callable
---

So there's some intricacy in dealing with packages I'm not getting;
unfortunately, the only place I've seen packages documented is the
tutorial which is, understandably, a little sparse.

-roy




More information about the Python-list mailing list