Correct to use instance = module.__dict__[class_name]() ?

Andy Gimblett gimbo at ftech.net
Mon Mar 18 12:51:54 EST 2002


I need to be able to take a string containing the name of a python
module (without the .py) and a string containing the name of a class
defined in that module, import the module, and create an instance of
the class.

I did have the following code, which works:

def foo(module_name, class_name):
    import_statement = "import %s" % (module_name)
    exec import_statement
    handler = eval("%s.%s()" % (module_name, class_name))
    return handler

Given recent "exec/eval considered harmful" threads, I resolved to
change it to something less controversial, and now have:

def bar(module_name, class_name):
    module = __import__(module_name, globals(), locals(), [])
    handler = module.__dict__[class_name]()
    return handler

Is this correct?  In particular I'm worried that __dict__ is not the
thing to use to get at the class object, but only really because I
don't recall seeing it used like this before.  Again, it seems to work
fine - I just want to make sure I'm doing The Right Thing.  :-) All
input appreciated.

Thanks,

Andy

-- 
Andy Gimblett - Programmer - Frontier Internet Services Limited
Tel: 029 20 820 044 Fax: 029 20 820 035 http://www.frontier.net.uk/
Statements made are at all times subject to Frontier's Terms and
Conditions of Business, which are available upon request.




More information about the Python-list mailing list