Dyanmic import of a class

Facundo Batista facundo at taniquetil.com.ar
Thu Mar 22 20:18:33 CET 2007


rh0dium wrote:

> foo.py
>
> class foo:
>    def __init__(self):
>       print "Hi I am %s" % self.__class__.__name__

I wrote this in a file here...


> Now I have a bunch of these files.  I want to be able to dynamically
> import each one and run it.  I am having a problem actually doing the
> work.   I thought __import__ would work but I can't seem to get it to
> work.

>>> name = "foo"
>>> mod = __import__(name)
>>> theclass = getattr(mod, name)
>>> instance = theclass()
Hi I am foo


Regards,

-- 
.   Facundo
.
Blog: http://www.taniquetil.com.ar/plog/
PyAr: http://www.python.org/ar/





More information about the Python-list mailing list