Dyanmic import of a class

R

rh0dium

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?
 
S

Scott David Daniels

Arnaud said:
You are not using __import__ correctly. Perhaps reading the doc would
be a good start:
http://docs.python.org/lib/built-in-funcs.html

For example to import the module defined in 'foo.py' you would do
foo = __import__('foo')
Then your class foo would be accessible as foo.foo

To get even more explicit:
import glob, os.path
for filename in glob.glob('*.py*'):
modname, ext = os.path.splitext(filename)
try:
class_ = getattr(__import__(modname), modname)
except (ImportError, AttributeError, SyntaxError), err:
print filename, modname, err
else:
class_().dosomething()
 
F

Facundo Batista

rh0dium said:
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.
Hi I am foo


Regards,
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,755
Messages
2,569,536
Members
45,013
Latest member
KatriceSwa

Latest Threads

Top