Dynamically Importing and Instantiating Modules in Python

Tue, Oct 13, 2009

Tech Tips

Also called reflection, here is one method to import modules and instantiate objects using strings:

  1. moduleName = 'myApp.models'  
  2. className = 'Blog'  
  3.   
  4. #import the module by saying 'from myApp.models import Blog'  
  5. module = __import__(moduleName, {}, {}, className)  
  6.   
  7. #now you can instantiate the class  
  8. obj = getattr(module, className )()  
  9.   
  10. #set a property of the object using a string  
  11. setattr('Title','my first entry')  
  12.   
  13. #call an existing method you already know  
  14. obj.save()  

I was using Python 2.5, so it is probably safe to say the code above is at least Python 2.5+ compatible.

Some additional references:
Dive Into Python – The Power of Introspection
Python Manual – Built In Functions

Bookmark and Share
,

Comments are closed.