Loading classes dynamically

Steven Bethard steven.bethard at gmail.com
Mon Aug 15 05:25:38 CEST 2005


Ramza Brown wrote:
> try:
>      load = eval('%s(props)' % (props['plugin.generate']))
> except:
> 
> It works, doesnt seem very safe.  Where props['plugin.generate'] is a 
> class name string.  And 'props' is the first arg in the constructor.

Where is the class defined?  The right answer to this is usually 
somethign like:

     load = getattr(some_module, props['plugin.generate'])(props)

If the class is defined in the current module, another possibility is:

     load = globals()[props['plugin.generate']](props)

HTH,

STeVe



More information about the Python-list mailing list