How to Converting Strings to Class Objects in Python
Sometimes you need to access a class object by its name as a string.
This guide explores various methods to convert a string to a class object in Python, including using getattr()
, globals()
, and importlib.import_module()
, while discussing the potential risks associated with eval()
. We'll emphasize the safest and most reliable approaches.
Converting Strings to Class Objects with getattr()
The getattr()
function is a safe and direct way to get a class object when you have a string representing its name. This is the best method to use if the class is defined in the same module or a different one.
import sys
class Employee():
pass
def get_class(class_name):
return getattr(sys.modules[__name__], class_name)
cls = get_class('Employee')
print(cls) # Output: <class '__main__.Employee'>
sys.modules[__name__]
retrieves the current module.- Then we use
getattr()
to access the class object based on its string name.
If the class is in another module, you should import that module using importlib.import_module()
:
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')) # Output: <class 'another.Employee'>
importlib.import_module()
is used to dynamically import another module.- The
getattr()
function is used to access the object in the imported module using theclass_name
variable, just like we did in the previous example, where the class was defined in the same module.
Converting Strings to Class Objects with globals()
If your class is defined in the same module, you can also use the globals()
function to get the class object using a string:
class Employee():
pass
def get_class(class_name):
return globals()[class_name]
print(get_class('Employee')) # Output: <class '__main__.Employee'>
- The
globals()
function returns a dictionary with the current module's global symbols. - You can use the string representing the class name to access the class object from that dictionary.
The globals()
dictionary only contains the global variables, i.e. the variables, classes and functions declared on the module's level. If you use globals()
inside a function, you will not be able to access a class declared within another function.
Converting Strings to Class Objects with importlib.import_module()
If your class is defined in a different module, you can use importlib.import_module()
to import the module and then getattr()
to retrieve 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')) # Output: <class 'another.Employee'>
- The
importlib.import_module()
function dynamically imports a module. - Then, you use
getattr()
to get the class from the imported module. - This approach is very useful if you are not sure if the module is actually already imported.
Dangers of Using eval()
The eval()
function can be used, but its use is highly discouraged due to security risks. eval()
should only be used with trusted data.
class Employee():
pass
def get_class(class_name):
return eval(class_name)
print(get_class('Employee')) # Output: <class '__main__.Employee'>
eval()
executes a string as Python code, which presents a very significant security risk and should not be used with untrusted input. Avoid using eval()
where possible.