Python Forum
Instantiating class from the string variable - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Instantiating class from the string variable (/thread-7924.html)



Instantiating class from the string variable - voltron - Jan-30-2018

Is it possible to import and instantiate class from the string variable, containing full class code? I only can think about saving code into temp file and importing this file using importlib.


RE: Instantiating class from the string variable - Gribouillis - Jan-30-2018

(Jan-30-2018, 06:46 AM)voltron Wrote: Is it possible to import and instantiate class from the string variable, containing full class code?
You can exec() the code in a dict and get the class as a value in the dict.


RE: Instantiating class from the string variable - voltron - Jan-30-2018

(Jan-30-2018, 06:57 AM)Gribouillis Wrote: You can exec() the code in a dict and get the class as a value in the dict.

Thanks! Looks like what I need.

May I ask for more help? I'm trying to use following approach now
class_def = "class definition here"
globs = {}
exec(class_def, globs)
c = globs["ClassName"]()
# do something with c
To get class by name I parse class_def variable to extract class name. Is it possible to find class without knowing its name?


RE: Instantiating class from the string variable - Gribouillis - Jan-30-2018

(Jan-30-2018, 09:07 AM)voltron Wrote: Is it possible to find class without knowing its name?
If there is only a class definition in the string, the dict will contain only the keys '__builtins__' and 'YourClassName'.
If there are more objects in the dict, you can examine them with the inspect module to find the class.


RE: Instantiating class from the string variable - voltron - Feb-05-2018

Thanks a lot! I managed to load class from the dict using inspect module.