How to find the classname of an object? (was Python Documentation)

Matt matthew_shomphe at countrywide.com
Fri May 13 17:59:13 EDT 2005


Bengt Richter wrote:
> On 13 May 2005 09:37:07 -0700, "Matt"
<matthew_shomphe at countrywide.com> wrote:
>
> >
> >Christopher J. Bottaro wrote:
> >> Christopher J. Bottaro wrote:
> >>
> >> > Bengt Richter wrote:
> >> >
> >> >>  >>> type(obj)
> >> >>  <class '__main__.A'>
> >> >>  >>> type(obj).mro()
> >> >>  [<class '__main__.A'>, <class '__main__.B1'>, <class
> >'__main__.B2'>,
> >> >>  [<class '__main__.C'>, <type 'object'>]
> >> >>  >>> tuple(x.__name__ for x in type(obj).mro())
> >> >>  ('A', 'B1', 'B2', 'C', 'object')
> >> >
> >> > Wow awesome, thats exactly what I was looking for.
> >>
> >> Wait a sec...why doesn't the following code work then?
> >>
> Well, I suspect it actually does work, technically, but I suspect
> it hints at the way old-style classes were implemented in the
environment
> of the new, rather than giving you what you might expect.
>
> >> class FWException(Exception): pass
> >> class FWA(FWException): pass
> >> class FWB(FWA): pass
> >> class FWC(FWB): pass
> >> e = FWC()
> >> print [ cl.__name__ for cl in type(e).mro() ]
> >>
> >> Thanks again.
> >> --C
> >
> >
> >Is it because you need to inherit from "object"?
> >
> >class FWException(Exception, object): pass # note "object"
> >class FWA(FWException): pass
> >class FWB(FWA): pass
> >class FWC(FWB): pass
> >e = FWC()
> >print [ cl.__name__ for cl in type(e).mro()]
> >
> >#prints ['FWC', 'FWB', 'FWA', 'FWException', 'Exception', 'object']
> >
> I'm afraid inheriting explicitly from object will make the exception
unraisable.
> Exceptions are still based on "classic" classes for some reason that
> I don't know enough about to explain.
>
> So if you were hoping to use .mro() with old-style classes to see the
> old-style inheritance chain, as opposed to new-style inheritance that
> underlies access to special entities involved in the implementation
of the old, sorry ;-/
>
> At least that's the way it looks to me, without digging in that part
of the code.
>
> Regards,
> Bengt Richter

D'oh!  So I tested the .mro() functionality but not the
Exception-raisableness (?).

It seems unintuitive to me as to why inheriting from  "object" would
prevent something that also inherited from "Exception" from being
raised.  Does anyone have insight into why this happens?




More information about the Python-list mailing list