30 April, 2010

Python: Import a Module and Get a given Class

Python offers different ways to import a module. The most flexible one is to use __import__ function. This allows script to load a module dynamically. So we can load a particular module based on user input.

Since everything in python is an object even the python module has some useful properties. One of them is __dict__ property. This is how you can use it.
className = 'MyClass'
modObj = __import__('moduleName')
# This gives us the class reference
MyClass = modObj.__dict__[className]
# So we can create class instance like this
inst = MyClass(params)

This logic works if you are using just modules. For packaging this may need to be modified.

No comments:

Post a Comment