How to call a function inside a (code of a) module dynamically?
For example:
class Class1(object):
pass
class Class2(object):
pass
# here I want to either instantiate object dynamically or dynamically pass
# a Class1 or Class2 object to some other method/class inside this module code
asked Jul 13, 2012 at 21:19
Memke
7441 gold badge8 silver badges26 bronze badges
-
You're going to have to be a bit more specific. Some more coded examples, perhaps?Joel Cornett– Joel Cornett2012年07月13日 21:21:06 +00:00Commented Jul 13, 2012 at 21:21
-
What have you tried so far? In Python you can pass classes around like any other object.Philipp– Philipp2012年07月13日 21:21:22 +00:00Commented Jul 13, 2012 at 21:21
-
1Python is weakly typed. There is nothing to restrict you from just passing an object of either type to any functionWug– Wug2012年07月13日 21:21:48 +00:00Commented Jul 13, 2012 at 21:21
2 Answers 2
You mean something like this?
>>> class Class1(object):
... pass
...
>>> class Class2(object):
... pass
...
>>> def foo(cls):
... print cls
...
>>> import random
>>> classes = {'Class1': Class1, 'Class2': Class2}
>>> dynamic_class = classes['Class%d' % random.randint(1, 2)]
>>> foo(dynamic_class())
<__main__.Class1 object at 0x10b44ab50>
answered Jul 13, 2012 at 21:24
sberry
133k20 gold badges145 silver badges171 bronze badges
I'm assuming that you mean you want to access the classes by name.
If the class you want is in the same module, try globals()[classname]() to instantiate the class. If it's in another module, try vars(module)[classname]() or getattr(module, classname)().
(classname is a string containing the name of the class; module is a reference to the module, not a string.)
answered Jul 13, 2012 at 21:22
kindall
185k36 gold badges291 silver badges321 bronze badges
2 Comments
mgilson
I've never seen
vars(module)[classname](). Is there a reason to prefer this over getattr? (Or is this another Tomato, tomato thing?)kindall
I kind of like
vars(modules) because it's analogous with globals()—you get back a dictionary with either so the rest is the same. Otherwise, matter of taste, I guess.lang-py