0

Is it possible to create an instance of a class by giving its name, e.g.:

instance = "TestXYZ"() 

Assuming that TestXYZ is imported by a class that imports the code above and TestXYZ is defined as:

class TestXYZ(object): ... 
3
  • 1
    It is possible using globals()["TestXYZ"](), but why do you want to do this? Commented Feb 6, 2014 at 15:55
  • Because I don't like to pass the exact class object, but I know the name. Commented Feb 6, 2014 at 16:00
  • Is there a reason why you don't want to pass the class itself? Commented Feb 6, 2014 at 16:53

3 Answers 3

1

Yes, it is possible. The mechanics depend on how you import the class:

>>> globals()["TestXYZ"]() <__main__.TestXYZ object at 0x10f491090> 

or

>>> getattr(sys.modules["test_module"], "TestXYZ")() <test_module.TestXYZ object at 0x10cf22090> 
Sign up to request clarification or add additional context in comments.

Comments

1

You can get a reference to an object from current namespace using:

klass = globals()['TestXYZ'] 

Then you can create an instance of the class:

instance = klass() 

Comments

1

I am not sure why do you want to do this, but instead of using globals() I'd suggest you to create a dictionary here:

class Foo: pass d = {'Foo':Foo} ins = d['Foo']() 

Or move the class to some other module:

import some_module ins = getattr(some_module, 'Foo')() 

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.