Python Forum

Full Version: Instantiating class from the string variable
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
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.
(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.
(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?
(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.
Thanks a lot! I managed to load class from the dict using inspect module.