fetching class by name

Martin von Loewis loewis at informatik.hu-berlin.de
Fri Feb 2 17:31:10 EST 2001


Geoffrey Gerrietts <geoff at homegain.com> writes:

> Is there an easier way to retrieve a class object by name than
> doing a manual lookup through the __dict__ of every module in
> sys.modules?

Depends on what you know about the class. If you *only* know the name,
there is probably no other way. Hint: if all you need is a class with
that name, how about

>>> import new
>>> new.classobj("thename",(),{})
<class __main__.thename at 0x811dbcc>

> I think maybe I'm just spoiled by the way objective c gives you a
> cute little utility function to do this for you. Still, looking
> it up manually seems extraordinarily costly.

More explicitly: there might be more than one class with that name,
the class might be known under a different name, or it might not be
bound to a variable altogether:

>>> class Foo:pass
...
>>> foo=Foo()
>>> del Foo
>>> foo.__class__
<class __main__.Foo at 0x811c72c>

Classes are objects like any other: some are referred-to by global
variables, others are not.

Regards,
Martin





More information about the Python-list mailing list