is it possible to create an object by its name in the run time

Christopher T King squirrel at WPI.EDU
Tue Aug 17 21:06:12 CEST 2004

On Tue, 17 Aug 2004, Yang Zhang wrote:

> I want to know if it is a build-in func(where can I look up?). If so,
> ignore it otherwise I want to find out which module is it defined in.

All functions and classes have a __module__ attribute which is set to the 
name of the module in which they were defined.

> All I know is the name (which is a string), and all the modules that
> this program have imported.

If you first "import __main__", you can use getattr(__main__,"foo") to get 
the object named "foo" in the global namespace.

> In the same way, I also need to process the class and methods call. I
> wonder if it is possible? I will appreciate your help very much!!

Here is a small snippet demonstrating the above:

 import __main__
 from types import FunctionType, ClassType

 def which_module(name, where = __main__):
         obj = getattr(where, name)
     except AttributeError:
         obj = getattr(__builtins__, name)
         return obj.__module__
     except AttributeError:
         if not isinstance(obj, (FunctionType, ClassType)):
             raise TypeError, "%s doesn't reference a function or class" % name
         return None

 print which_module('list')  # --> '__builtin__'
 from math import sin
 print which_module('sin')   # --> 'math'
 a = 6
 print which_module('a')     # --> TypeError

Hope this helps.

More information about the Python-list mailing list