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:


moduleName = 'myApp.models'
className = 'Blog'

#import the module by saying 'from myApp.models import Blog'
module = __import__(moduleName, {}, {}, className)

#now you can instantiate the class
obj = getattr(module, className )()

#set a property of the object using a string
setattr('Title','my first entry')

#call an existing method you already know
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.