Loading classes dynamically

Collapse
This topic is closed.
X
X
 
  • Time
  • Show
Clear All
new posts
  • Ramza Brown

    #1

    Loading classes dynamically

    What is the most pythonic way to load a class and instaniate an object
    dynamically. Right now, I am using eval:

    try:
    load = eval('%s(props) ' % (props['plugin.generat e']))
    except:

    It works, doesnt seem very safe. Where props['plugin.generat e'] is a
    class name string. And 'props' is the first arg in the constructor.

    What do you think?

    --
    Ramza from Atlanta

  • Steven Bethard

    #2
    Re: Loading classes dynamically

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

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

    load = getattr(some_mo dule, props['plugin.generat e'])(props)

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

    load = globals()[props['plugin.generat e']](props)

    HTH,

    STeVe

    Comment

    Working...