Dynamic importing

Peter Abel p-abel at t-online.de
Mon Jun 23 23:08:39 CEST 2003


googlenews at ols.inorganic.org (Roy S. Rapoport) wrote in message news:<533b36b0.0306222247.2a630d07 at posting.google.com>...
Ok it took me a while, and I'm not quite sure, but I think I got it:
...
...
...

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

When what='onec' then after the above statement x will become the **demo** 
- package with the possibility to access demo.onec.

>                 y = eval("x.%s()" % what)

So the above eval-statement tries to call demo.onec(), which results in
your error below.
Instead of this you should try:
 **y = eval("x.%s.%s()" % (what,what) )**

>                 eval("y.dosomething()")

BTW at my opinion there's no need for the eval-statement.
 **y.dosomething()**  works too.

> 
> 
> (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

I added some prints in your master-class to clearify a little bit
the situation.
class master:
  def dosomething(self, what):
    x = __import__("demo."+what)
    print "="*30
    print "x         : %s"%x
    print "x.__name__: %s"%x.__name__
    print "dir(x)    :"
    print "\n".join(dir(x))
    mod="x.%s.%s()" % (what,what)
    print "mod       : %s"%mod
    y = eval(mod)
    y.dosomething()
    print "="*30
    print

Gives me the following:
==============================
x         : <module 'demo' from 'C:\Dokumen ...[snip]
x.__name__: demo
dir(x)    :
__all__
__builtins__
__doc__
__file__
__name__
__path__
master
onec
mod       : x.onec.onec()
class one called to do something
==============================

==============================
x         : <module 'demo' from 'C:\Dokumen ...[snip]
x.__name__: demo
dir(x)    :
__all__
__builtins__
__doc__
__file__
__name__
__path__
master
onec
twoc
mod       : x.twoc.twoc()
class two called to do something
==============================

Reading http://www.python.org/doc/essays/packages.html could
help a bit.

Regards
Peter




More information about the Python-list mailing list