0

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
3
  • You're going to have to be a bit more specific. Some more coded examples, perhaps? Commented Jul 13, 2012 at 21:21
  • What have you tried so far? In Python you can pass classes around like any other object. Commented Jul 13, 2012 at 21:21
  • 1
    Python is weakly typed. There is nothing to restrict you from just passing an object of either type to any function Commented Jul 13, 2012 at 21:21

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

2 Comments

I think this example would be a little more constructive if you explicitly created the dictionary that is being returned by locals().
Agreed. (+1) for your efforts (and nice example)
2

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

2 Comments

I've never seen vars(module)[classname](). Is there a reason to prefer this over getattr? (Or is this another Tomato, tomato thing?)
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.

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.