Instantiating an object when the type is only known at runtime

Terry Reedy tjreedy at udel.edu
Tue Oct 3 20:14:21 CEST 2006


"Samuel" <knipknap at gmail.com> wrote in message 
news:1159883162.906612.292870 at c28g2000cwb.googlegroups.com...
> Hi,
>
> I am trying to replace the eval() in the following code:
>
> def myfunc(type, table):
>    module   = __import__(type)
>    type     = 'module' + '.' + type
>    obj      = eval(type)
>    return obj(row[table.c.name], row[table.c.handle])
>
> I am out of ideas. Any hints?

Perhaps what you need is a dict 'types' mapping strings to types/classes.
Then the last two lines might become

  return types[type](row[table.c.name], row[table.c.handle])

The trick of mapping names to callables for runtime choice of what to call 
has several uses.

Terry Jan Reedy






More information about the Python-list mailing list