How do I call anonymous classes from imported modules?
James Stroud
jstroud at mbi.ucla.edu
Sun Aug 19 23:17:08 EDT 2007
JoeSox wrote:
> I am importing 3rd party modules via a plugin script. I wish to
> iterate thru the modules and call a common method like .do_foobar() or
> something with all the imports.
> But I can't figure out how to do something like below without knowing
> the class name before hand. Is there a builtin that helps call
> classes anonymously?
>
>
> (Calling example.do_foobar() works because I manually enter the classes' name)
>
>>>>a=MyApp()
>>>>sensorsList = []
>>>>for snames in a.pluginsDict["sensorsplugins"]:
>
> sensorsList.append(__import__(snames))
>
>>>>sensorsList[0].example.do_foobar()
>
>
> but I need something like
>
>>>>sensorsList[0][0].do_foobar()
>
> because I will not know the plugin class names.
>
Quick and dirty (you could also use a try: except:):
f = __import__(module_name)
for anobj in f.__dict__.values():
if hasattr(anobj, 'do_foobar'):
anobj.do_foobar()
Note that this does not test whether anobj is a class as this would
entail a type-check, which hints to poor design.
James
--
James Stroud
UCLA-DOE Institute for Genomics and Proteomics
Box 951570
Los Angeles, CA 90095
http://www.jamesstroud.com/
More information about the Python-list
mailing list