Dyanmic import of a class

Scott David Daniels scott.daniels at acm.org
Fri Mar 9 07:07:15 CET 2007


   Arnaud Delobelle wrote:
> On Mar 8, 9:09 pm, "rh0dium" <steven.kl... at gmail.com> wrote:
> [snip]
>> for mod in listdir():
>>    __import__(mod)
>>    a=mod()
>>    a.dosomething()  # This is a function which each class shares.
>>
>> Can anyone help?
> 
> 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()

-- 
--Scott David Daniels
scott.daniels at acm.org



More information about the Python-list mailing list