More elegant to get a name: o.__class__.__name__

George Sakkis george.sakkis at gmail.com
Fri Dec 1 10:07:06 EST 2006


Carl Banks wrote:

> alf wrote:
> > Hi,
> > is there a more elegant way to get o.__class__.__name__. For instance I
> > would imagine name(o).
>
> def name_of_type(o):
>     return o.__class__.__name__
>
> name_of_type(o)
>
>
> Carl Banks
>
> P.S. name(o) suggests it's the name of the object, not the type
> P.P.S. you could use type(o).__name__ but it doesn't work for old-style
> classes

You mean it doesn't work for old-style instances; OTOH __class__
doesn't work for old style classes:
>>> class X: pass
...
>>> X.__class__
AttributeError: class X has no attribute '__class__'

So to handle all cases, you'd have to go with:

def typename(o):
    try: cls = o.__class__
    except AttributeError: cls = type(o)
    return cls.__name__
    # or for fully qualified names
    # return '%s.%s' % (cls.__module__, cls.__name__)

George




More information about the Python-list mailing list