doubt with importing module, given module name

Carsten Haese carsten at uniqsys.com
Mon Apr 9 13:36:20 EDT 2007


On Mon, 2007-04-09 at 22:52 +0530, Pradnyesh Sawant wrote:
> Hello,
> I have a string which in reality is the name of a module to be
> imported. The name of the class contained in the module also has the
> same (although with different capitalization). My requirement is to
> import the module, and also create an instance of the class. eg:
> 
> str = "module"             #name of module is "module.py"
> cls = str.capitalize()      #name of class is "Module"
> inst = cls()                   #create an instance of class "Module"
> 
> how do i do this?

1) Don't use the name 'str', you're shadowing a built-in name.

2) Use __import__ to import a module with a variable name.

3) Use getattr to look up an attribute with a variable name.

Putting 1-3 together, you get code something like this:

module_name = "module"
mod = __import__(module_name)
class_name = module_name.capitalize()
cls = getattr(mod, class_name)
inst = cls()

Hope this helps,

Carsten.





More information about the Python-list mailing list