Convert a string to a Class object in Python

avatar
Borislav Hadzhiev

Last updated: Apr 10, 2024
4 min

banner

# Table of Contents

  1. Convert a string to a Class object in Python
  2. Convert a string to a Class object using eval()
  3. Convert a string to a Class object using globals()
  4. Convert a string to a Class object using importlib.import_module()

# Convert a string to a Class object in Python

To convert a string to a class object:

  1. Use the sys.modules dictionary to get the current module.
  2. The class will be accessible in the module's attributes.
  3. Pass the string to the getattr() function to get the class object.
main.py
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'>

convert string to class object

The code for this article is available on GitHub
The example assumes that the class is defined in the same module. If the class is defined in a different module, scroll down to the last subheading and use the 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.

main.py
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.

main.py
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 code for this article is available on GitHub

The getattr() function returns the value of the provided attribute of the object.

The function takes the following parameters:

NameDescription
objectthe object whose attribute should be retrieved
namethe name of the attribute
defaulta 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.

main.py
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

specify default value when calling getattr

# Convert a string to a Class object using eval()

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.

main.py
class Employee(): pass def get_class(class_name): return eval(class_name) print(get_class('Employee')) # ๐Ÿ‘‰๏ธ <class '__main__.Employee'>

convert string to class using eval

The code for this article is available on GitHub

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.

The 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.

# Convert a string to a Class object using globals()

This is a two-step process:

  1. Use the globals() function to get a dictionary containing the current scope's global variables.
  2. Use the string as a dictionary key to get access to the class object.
main.py
# โœ… 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'>

convert string to class object using globals

The code for this article is available on GitHub

The globals function returns a dictionary that implements the current module namespace.

main.py
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.

# Convert a string to a Class object using importlib.import_module()

To convert a string to a class object when the class is defined in a different module:

  1. Use the importlib.import_module() method to import the module.
  2. The class will be accessible in the module's attributes.
  3. Pass the string to the getattr() function to get the class object.
main.py
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 code for this article is available on GitHub

The example assumes that there is a module named another.py located in the same directory that contains an Employee class.

another.py
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.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev