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

Just van Rossum just at xs4all.nl
Mon Mar 18 13:48:42 EST 2002


In article <mailman.1016473950.9924.python-list at python.org>,
 Andy Gimblett <gimbo at ftech.net> wrote:

> 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.

This would be better:

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

Just



More information about the Python-list mailing list