Last updated: Apr 10, 2024
Reading timeยท4 min
To convert a string to a class object:
sys.modules
dictionary to get the current module.getattr()
function to get the class object.import sys class Employee(): pass def get_class(class_name): return getattr(sys.modules[__name__], class_name) cls = get_class('Employee') print(cls) # ๐๏ธ <class '__main__.Employee'>
importlib.import_module()
method.Sys.modules is a dictionary that maps module names to modules that have already been loaded.
The __name__
global variable stores the module's name.
import sys # ๐๏ธ <module '__main__' from '/home/borislav/Desktop/bobbyhadz_python/main.py'> print(sys.modules[__name__])
Once you have the module object, use the getattr()
method to convert the
string to a class object.
import sys class Employee(): pass def get_class(class_name): return getattr(sys.modules[__name__], class_name) cls = get_class('Employee') print(cls) # ๐๏ธ <class '__main__.Employee'>
The getattr() function returns the value of the provided attribute of the object.
The function takes the following parameters:
Name | Description |
---|---|
object | the object whose attribute should be retrieved |
name | the name of the attribute |
default | a default value for when the attribute doesn't exist on the object |
If a class with the specified name doesn't exist, you'd get an AttributeError
.
You can pass a third argument to the getattr()
method if you need to specify a
default value.
import sys def get_class(class_name): # ๐๏ธ returns None if class with given name doesn't exist return getattr(sys.modules[__name__], class_name, None) cls = get_class('ABC123') print(cls) # ๐๏ธ None
Alternatively, you can use the eval()
function.
The eval()
function will take the string and will evaluate it as a Python
expression returning the class.
class Employee(): pass def get_class(class_name): return eval(class_name) print(get_class('Employee')) # ๐๏ธ <class '__main__.Employee'>
The eval() function
takes an expression, parses it and evaluates it as a Python expression using the
globals
and locals
dictionaries as the global and local namespace.
eval()
function should only be used with trusted code. Don't use eval()
with user-generated data.The eval()
function basically tries to run the given expression, so it should
never be used with untrusted code.
If you get linting errors when using eval()
, use the globals()
dictionary
instead.
This is a two-step process:
globals()
function to get a dictionary containing the current
scope's global variables.# โ if the class is in the same module class Employee(): pass def get_class(class_name): return globals()[class_name] print(get_class('Employee')) # ๐๏ธ <class '__main__.Employee'>
The globals function returns a dictionary that implements the current module namespace.
class Employee(): pass # {'__name__': '__main__', '__doc__': None, '__package__': None, '__loader__': <_frozen_importlib_external.SourceFileLoader object at 0x7f851caa1de0>, '__spec__': None, '__annotations__': {}, '__builtins__': <module 'builtins' (built-in)>, '__file__': '/home/borislav/Desktop/bobbyhadz_python/main.py', '__cached__': None, 'Employee': <class '__main__.Employee'>} print(globals())
The last step is to use the string to access the dictionary's key.
There is a key with the class's name that points to the class object.
If a class with the given name doesn't exist in the module, you'd get a
KeyError
exception.
The previous 3 approaches only work if the class is defined in the same module.
If the class is defined in a different module, use the importlib
module.
To convert a string to a class object when the class is defined in a different module:
importlib.import_module()
method to import the module.getattr()
function to get the class object.import importlib def get_class(module_name, class_name): module = importlib.import_module(module_name) return getattr(module, class_name) print(get_class('another', 'Employee')) # ๐๏ธ <class 'another.Employee'>
The example assumes that there is a module named another.py
located in the
same directory that contains an Employee
class.
class Employee(): pass
The importlib.import_module method takes the name of a module and imports it.
The name
argument can be absolute or relative, e.g. pkg.module
or
..module
.
If you use a relative package name, e.g. ..module
, you have to pass a second
argument to the import_module()
method, e.g.
import_module('..module', pkg.subpkg')
imports pkg.module
.
Once we have the module imported, we can use the getattr()
function to get the
class object from the given string.
The getattr()
function takes an optional third argument that serves as a
default value for when the attribute doesn't exist on the object.
You can learn more about the related topics by checking out the following tutorials: