How to dynamically load a Python class?


A class is a group of items. It is a logical entity with a few unique attributes and methods. For instance, if you have a class for Cricket, it should have an attribute and method like players, tournaments, toss, runs, wickets, matches, etc. Use the keyword ‘class’ to create a class.

Example: Following is a simple example of a class −

Create the class named ‘Python’ and give it the property a −

class Python: 
a = 36

This article demonstrates the following different ways to dynamically load a Python class.

Using getattr() function

The named attribute of an object's getattr() method returns its value. If nothing is detected, it returns the function's default value.

Example

To load the module named module_name, execute the command Call_import_(module_name). To load a method named method_name from a module, call get_attr(module, method_name).

# importing the module numpy numpy = __import__("numpy") # importing an array from numpy array = getattr(numpy, "array") the_array = array([[34, 28], [38, 37]]) print(the_array)

Output

Following is an output of the above code −

[[34 28]
[38 37]]

Example

No function that accepts a fully qualified class name and returns the class is currently available. But we can develop a function that does this functionality. The following example defines such a function −

def my_class(x): groups = x.split('.') module = ".".join(groups[:-1]) a = __import__( module ) for comp in groups[1:]: a = getattr(b, comp) return a

One example of the usage of that function is as follows −

import datetime def my_class(x): groups = x.split('.') module = ".".join(groups[:-1]) b = __import__( module ) for comp in groups[1:]: b = getattr(b, comp) return b print (my_class('datetime.datetime').now())

Output

Following is an output of the above code −

2022-11-16 06:53:13.513141

Using the __import__( ) Method

Python's "dunder" or "magic" methods are those with two underscores as the method's prefix and suffix. Here, the term "Dunder" refers to "Double Under (Underscores)". These are frequently utilised to handle operator overload. Examples of magic methods are "__init__," "__add__," "__len__," and "__repr__," among many others.

Using the "magic" method, __import__, is the simplest way to accomplish this kind of task. In fact, if you search for this issue on Google, that's probably the first approach you'll come up. The basic approach is as follows −

module = __import__(module_name) 
given_class = getattr(module, Class_Name) 
instance = given_class()

In the code above, class_name and module_name must both be strings. You must include that logic if the class you are importing needs any parameters to be provided to it.

Example

For you to understand better how this operates, here is a more detailed illustration −

class DynamicImporter: def __init__(self, module_name, class_name): # The Constructor module = __import__(module_name) the_class = getattr(module, class_name) instance = the_class() print (instance) if __name__ == "__main__": DynamicImporter("decimal", "Context")

Output

Following is an output of the above code −

Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999, capitals=1, clamp=0, flags=[], traps=[InvalidOperation, DivisionByZero, Overflow])

This shows that the code operates as expected because it imports the decimal and returns a Context class instance.

Updated on: 23-Nov-2022

3K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements