Instantiating an object when the type is only known at runtime

Samuel knipknap at gmail.com
Tue Oct 3 18:19:31 EDT 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