Python converts strings to class names

Introduction: Recently I encountered a problem when doing a project —->’ according to different pass values, get different module classes and serialization classes’.

Problems arise

At first, I implemented the code through multiple if statements, but since there were so many if statements, it seemed inelegant, so I wanted to put different values in a dictionary and store them as key-value pairs, but the problem was that the value type in the dictionary was a string and needed to be converted to a class.

    class A:
        print('i am A')

    class As:
        print('i am As')

    class B:
        pass

    class Bs:
        pass

    dic = {'a': 'A_As'.'b': 'B_Bs'}
Copy the code

To find the information

Python’s globals()[string] turns a string into a class. (The conversion refers to converting A string that is the same as the class name to A class, such as ‘A’ to type A.) (This is to get the corresponding class from the class name as A string.) So I took A look at globals() in usage

def globals(*args, **kwargs) : # real signature unknown
    """ Return the dictionary containing the current scope's global variables. NOTE: Updates to this dictionary *will* affect name lookups in the current global scope and vice-versa. """
    pass
Copy the code

The meaning of this comment is to return all the current objects in the form of a dictionary.

Test and fix problems

Next let’s print globals() and see what value is returned.

    print(globals())
Copy the code
{'__name__': '__main__'.'__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x0000020B614BEC48>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': 'D:/python_projects/test.py', '__cached__': None, 'Decimal': <class 'decimal.Decimal'>, 'A': <class '__main__.A'>, 'As': <class '__main__.As'>, 'B': <class '__main__.B'>, 'Bs': <class '__main__.Bs'>, 'dic': {'a': 'A_As', 'b': 'B_Bs'}}
Copy the code

We can see that all objects are included in the dictionary, and then we can use globals()[string] to get the class we want.

a = globals()[dic['a'].split('_') [0]]
# i am A
Copy the code

Full test code:

if __name__ == '__main__':
    class A:
        print('i am A')

    class As:
        print('i am As')

    class B:
        pass

    class Bs:
        pass

    dic = {'a': 'A_As'.'b': 'B_Bs'}
    print(globals())
    a = globals()[dic['a'].split('_') [0]]
Copy the code