views:

81

answers:

3

Hello guys, I've a name of a class stored in var, which I need to create an object from. However I do not know in which module it is defined (if I did, I would just call getattr(module,var), but I do know it's imported.

Should I go over every module and test if the class is defined there ? How do I do it in python ?

What if I have the module + class in the same var, how can I create an object from it ? (ie var = 'module.class') Cheers, Ze

A: 

Classes are not added to a global registry in Python by default. You'll need to iterate over all imported modules and look for it.

Ignacio Vazquez-Abrams
When I run `globals()` I see a little more than nothing. Am I special?
Oli
@Oli: You *do* know that `globals()` only shows you the names in the *current* module... right?
Ignacio Vazquez-Abrams
+1  A: 

globals()[classname] should do it.

More code: http://code.activestate.com/recipes/285262/

Oli
A: 

Rather than storing the classname as a string, why don't you store the class object in the var, so you can instantiate it directly.

>>> class A(object):
...     def __init__(self):
...         print 'A new object created'
... 
>>> class_object = A
>>> object = class_object()
A new object created
>>> 
Lakshman Prasad