Instantiating an object when the type is only known at runtime

Samuel knipknap at gmail.com
Wed Oct 4 00:19:31 CEST 2006


Thanks, that's what I was looking for.

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

For the records: If the module is already loaded, this also works:

if my_type_is_not_yet_loaded:
    module = __import__(type)
    obj    = getattr(module, type)
else:
    obj    = globals().get(type)
resource = obj(my_arg1, my_arg2)

Thanks again,
-Samuel




More information about the Python-list mailing list