Jan-30-2018, 06:46 AM
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.
Instantiating class from the string variable
|
Jan-30-2018, 06:46 AM
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:57 AM
(This post was last modified: Jan-30-2018, 06:57 AM by Gribouillis.)
(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, 09:07 AM
(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 cTo 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:20 AM
(This post was last modified: Jan-30-2018, 09:20 AM by Gribouillis.)
(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.
Feb-05-2018, 01:18 PM
Thanks a lot! I managed to load class from the dict using inspect module.
|
|