Dyanmic import of a class

rh0dium steven.klass at gmail.com
Thu Mar 8 16:09:01 EST 2007


Hi all,

I have a directory with a bunch of python classes each uniquely named
such that the file name (dropping .py) is also the class name of the
file in question.  So for example

foo.py

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


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.

for mod in listdir():
   __import__(mod)
   a=mod()
   a.dosomething()  # This is a function which each class shares.

Can anyone help?




More information about the Python-list mailing list