Dynamic class loading in python
Code :
def create(class_name):
#check for module name
module_name,class_name = class_name.rsplit(".",1)
#check if the module already loaded
if module_name not in sys.modules:
#import module
__import__(module_name)
module = sys.modules[module_name]
# fetch class
cls =getattr(module,class_name)
#create an instance of the class
return cls()
#returns an instance of html.parser.HTMLParse
obj = create('html.parser.HTMLParser')
How it works
- Get class and module name.'HMTLParser' is the class and 'html.parser' is the module.
- Check if the module already loaded.'sys.module' object contains all loaded module list.
- If no module exist manually load the module using __import__() function.
- Get the module object from the 'sys.modules' using getattr() function.
- Get class object form the module object again using getattr() function
- Create instance for the object.
Labels: class loading, dynamic invocation, module loading, python

0 Comments:
Post a Comment
Subscribe to Post Comments [Atom]
<< Home