How to dynamically load a Python class?

PythonServer Side ProgrammingProgramming

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.


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()


This gives the output

2018-01-23 14:04:09.843000

Published on 23-Jan-2018 09:41:29