Instantiating an object when the type is only known at runtime

Carsten Haese carsten at uniqsys.com
Wed Oct 4 09:03:26 EDT 2006


On Tue, 2006-10-03 at 18:19, Samuel wrote:
> 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)

You seem to be under the impression that importing an already imported
module is a hideously expensive operation that must be avoided at all
costs. It's not. If you import an already imported module, python simply
returns the module object from sys.modules without executing any of the
module's code.

Your code will be much easier to read if you eliminate the
"my_type_is_not_yet_loaded" check, whatever that may be under the hood,
and always perform the __import__. It's also likely to be at least as
fast, but I couldn't run a timing comparison even if I wanted to because
you didn't post working code.

-Carsten





More information about the Python-list mailing list