Home > OS >  Create an object from a text which represents the class name
Create an object from a text which represents the class name

Time:03-14

I do not know if this is possible but I am storing the output of type(...) in a string. The output is a class created by me:

type(...) -> <class 'apps.X.Y.Z.Listings'>

I am storing this as a text but later I want to use this to create an object. How can it be done? I used exec and did not worked and also callable says that is False.

In which format should I store to be able to convert the string into the class name and instantiate an object?

CodePudding user response:

If class is imported you can use globals()

globals()["Listings"]

CodePudding user response:

try this:

eval(<string_class>)()
  • Related