Instantiating an object when the type is only known at runtime

Rob Williscroft rtw at freenet.co.uk
Tue Oct 3 11:03:25 EDT 2006


Samuel wrote in news:1159883162.906612.292870 at c28g2000cwb.googlegroups.com 
in comp.lang.python:

> 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])
> 

>>> m = __import__( "StringIO" )
>>> x = getattr( m, "StringIO" )()
>>> x
<StringIO.StringIO instance at 0x00A47710>
>>> 

Rob.



More information about the Python-list mailing list