Computer >> Computer tutorials >  >> Programming >> Python

How to dynamically load a Python class?


There's no available function that takes a fully qualified class name and returns the class. However we can define a function that has this functionality.

Example

The following code is of such a function.

def get_class( s ):
    parts = s.split('.')
    module = ".".join(parts[:-1])
    n = __import__( module )
    for comp in parts[1:]:
        n = getattr(m, comp)          
    return n

One usage example of that function

import datetime
def get_class( cls ):
    parts = cls.split('.')
    module = ".".join(parts[:-1])
    m = __import__( module )
    for comp in parts[1:]:
        m = getattr(m, comp)
    return m
print get_class('datetime.datetime').now()

Output

This gives the output

2018-01-23 14:04:09.843000