Python Forum
Instantiating class from the string variable
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
Instantiating class from the string variable
#1
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.
Reply
#2
(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.
Reply
#3
(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?
Reply
#4
(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.
Reply
#5
Thanks a lot! I managed to load class from the dict using inspect module.
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  Replacing String Variable with a new String Name kevv11 2 774 Jul-29-2023, 12:03 PM
Last Post: snippsat
  Need help on how to include single quotes on data of variable string hani_hms 5 2,014 Jan-10-2023, 11:26 AM
Last Post: codinglearner
  python r string for variable mg24 3 2,800 Oct-28-2022, 04:19 AM
Last Post: deanhystad
  Variable Types in a class nafshar 9 2,452 Oct-07-2022, 07:13 PM
Last Post: deanhystad
  USE string data as a variable NAME rokorps 1 959 Sep-30-2022, 01:08 PM
Last Post: deanhystad
  Removing Space between variable and string in Python coder_sw99 6 6,279 Aug-23-2022, 01:15 PM
Last Post: louries
  Remove a space between a string and variable in print sie 5 1,780 Jul-27-2022, 02:36 PM
Last Post: deanhystad
  Split string using variable found in a list japo85 2 1,296 Jul-11-2022, 08:52 AM
Last Post: japo85
  can Inner Class reference the Outer Class's static variable? raykuan 6 5,888 Jul-01-2022, 06:34 AM
Last Post: SharonDutton
  Can you print a string variable to printer hammer 2 1,944 Apr-30-2022, 11:48 PM
Last Post: hammer

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020