Instantiating an object when the type is only known at runtime

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

"Samuel" <knipknap at> wrote in message 
news:1159883162.906612.292870 at
> 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[], 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[], 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