Name of type of object

George Sakkis gsakkis at rutgers.edu
Wed Feb 9 10:21:07 EST 2005


"Steven Bethard" <steven.bethard at gmail.com> wrote in message
news:J8adnUGW461nV5TfRVn-rA at comcast.com...
> Randall Smith wrote:
> > Jive Dadson wrote:
> >
> >> The traceback routine prints out stuff like,
> >>
> >>     NameError: global name 'foo' is not defined
> >>
> >> NameError is a standard exception type.
> >>
> >> What if I want to print out something like that?
> >> I've determined that "global name 'foo' is not defined" comes from the
> >> __str__ member of the exception object.
> >> Where does it find the string "NameError"?  In general, if I have an
> >> object, is there a way to obtain the name of the type of the object?
> >>
> >> Thankee.
> >
> > type(object) ?
>
> Doesn't work for old-style classes like exceptions:
>
> py> e = NameError("global name 'foo' is not defined")
> py> type(e)
> <type 'instance'>
> py> type(e).__name__
> 'instance'
>
> For old-style classes, you'll need to go through __class__
>
> py> e.__class__
> <class exceptions.NameError at 0x00934900>
> py> e.__class__.__name__
> 'NameError'
>
> STeVe

To sum up:

def typename(obj):
    try:
        return obj.__class__.__name__
    except AttributeError:
        return type(obj).__name__


George





More information about the Python-list mailing list