dpv
dpv

Reputation: 157

Create an object from a text which represents the class name

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?

Upvotes: 0

Views: 255

Answers (2)

Patryk Laszuk
Patryk Laszuk

Reputation: 1440

If class is imported you can use globals()

globals()["Listings"]

Upvotes: 1

Ashkan Hadadi
Ashkan Hadadi

Reputation: 33

try this:

eval(<string_class>)()

Upvotes: 0

Related Questions