Generate a class from a string in Python

When I let a script do some processing, I usually go out of the config file, aggregate the setting values there, and when I execute it, I load that config and execute the processing. Among the setting values, there were times when I wanted to execute a certain process in a specific class. What should I do in such a case? Would you like to write parameters such as numerical values and generate classes by dividing them by if in the code, for example, ClassA for 1 and ClassB for 2? If you need a new Class C pattern, you have to add the if part of the code. In python, you can use globals () to create a class object from a string, which is convenient in such cases.

(update) As mentioned in the comment, the eval function can also create a class object from a string.

globals() This can be achieved using the globals () function. globals () returns a dictionary of currently loaded modules. You can use this to generate a class from a string.

Sample code

This is a sample code.

parent_child.py


#Parent class
class Parent(object):
  def __init__(self):
    pass

  def call(self):
    print("I am parent.")

#Child class 1
class ChildAsBrother(Parent):
  def __init__(self):
    super().__init__()

  def call(self):
    print("I am child as brother.")

#Child class 2
class ChildAsSister(Parent):
  def __init__(self):
    super().__init__()

  def call(self):
    print("I am child as sister.")

#Normal object creation and calling
obj = Parent()
obj.call()

obj = ChildAsBrother()
obj.call()

# globals()Object generation using
obj = globals()["ChildAsSister"]()     # <---Objects can be created from strings
obj.call()

#add to
#Method using eval
obj = eval("ChildAsSister")()
obj.call()

obj = eval("ChildAsSister()")
obj.call()

The execution result will be like this.

I am parent.
I am child as brother.
I am child as sister.
I am child as sister.
I am child as sister.

This way you can specify the class name you want to use in the config file and use it directly in your code. It's convenient

In the first place, globals () ...

What exactly does globals () return in the first place? I checked it for a moment. I will introduce it here for your reference.

print(globals())

#Actually, it is displayed on one line, but it is hard to see, so it is broken.
{'__name__': '__main__', 
'__doc__': None, 
'__package__': None, 
'__loader__': <_frozen_importlib_external.SourceFileLoader object at 0xffdc5c90>, 
'__spec__': None, 
'__annotations__': {}, 
'__builtins__': <module 'builtins' (built-in)>, 
'__file__': 'parent_child.py', 
'__cached__': None, 
'Parent': <class '__main__.Parent'>, 
'ChildAsBrother': <class '__main__.ChildAsBrother'>, 
'ChildAsSister': <class '__main__.ChildAsSister'>, 
'obj': <__main__.ChildAsSister object at 0xffd18b90>}

I don't know the details, but it seems that metadata and classes and objects in the execution environment are managed. It seems that the class in it is running.

Recommended Posts

Generate a class from a string in Python
Generate a first class collection in Python
Create an instance of a predefined class from a string in Python
Create a datetime object from a string in Python (Python 3.3)
Django: Import a class from a string
Create a random string in Python
Generate C language from S-expressions in Python
How to get a string from a command line argument in python
case class in python
String manipulation in python
Class notation in Python
How to embed a variable in a python string
I wrote a class in Python3 and Java
How to generate a Python object from JSON
Call a Python script from Embedded Python in C ++ / C ++
Put out a shortened URL string in Python
Insert an object inside a string in Python
Check if the string is a number in python
Take a screenshot in Python
Parse a JSON string written to a file in Python
How to convert / restore a string with [] in python
I want to embed a variable in a Python string
Generate rounded thumbnails in Python
Create a function in Python
Create a dictionary in Python
Convert date timezone (time difference) in Python (from string)
Receive dictionary data from a Python program in AppleScript
[Python] Use a string sequence
OCR from PDF in Python
[Python] How to expand variables in a character string
Generate U distribution in Python
Make a bookmarklet in Python
Generate QR code in Python
String date manipulation in Python
Draw a heart in Python
Generate 8 * 8 (64) cubes in Blender Python
Generate Word Cloud from case law data in python3
How to slice a block multiple array from a multiple array in Python
How to use the __call__ method in a Python class
[MQTT / Python] Implemented a class that does MQTT Pub / Sub in Python
I created a class in Python and tried duck typing
Python> Read from a multi-line string instead of a file> io.StringIO ()
Maybe in a python (original title: Maybe in Python)
Write a binary search in Python
Call a Python function from p5.js.
How to write a Python class
[python] Manage functions in a list
Touch a Python object from Elixir
Hit a command in Python (Windows)
[Python] Generate QR code in memory
Get data from Quandl in Python
Create a DI Container in Python
Create a pandas Dataframe from a string.
Draw a scatterplot matrix in python
ABC166 in Python A ~ C problem
Generate Jupyter notebook ".ipynb" in Python
Write A * (A-star) algorithm in Python
Read PNG chunks in Python (class)
Create a binary file in Python
python / Make a dict from a list.
A memo to generate a dynamic variable of class from dictionary data (dict) that has only standard type data in Python3