'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?
Solution 1:[1]
If class is imported you can use globals()
globals()["Listings"]
Solution 2:[2]
try this:
eval(<string_class>)()
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Patryk Laszuk |
Solution 2 | Ashkan Hadadi |