getattr and mro (was Re: [Python-Dev] PEP 246, redux) (original) (raw)

Guido van Rossum gvanrossum at gmail.com
Wed Jan 12 16:52:15 CET 2005


[Armin]

> ... is that the adapt() and conform() methods should work just > like all other special methods for new-style classes. The confusion > comes from the fact that the reference implementation doesn't do that. > It should be fixed by replacing: > > conform = getattr(type(obj), 'conform', None) > > with: > > for basecls in type(obj).mro: > if 'conform' in basecls.dict: > conform = basecls.dict['conform'] > break > else: > # not found > > and the same for 'adapt'. > > The point about tpxxx slots is that when implemented in C with slots, you get > the latter (correct) effect for free. This is how metaconfusion is avoided in > post-2.2 Python. Using getattr() for that is essentially broken. Trying to > call the method and catching TypeErrors seems pretty fragile -- e.g. if you > are calling a conform() which is implemented in C you won't get a Python > frame in the traceback either.

[Thomas]

I'm confused. Do you mean that

getattr(obj, "somemethod")(...) does something different than obj.somemethod(...) with new style class instances? Doesn't getattr search the dict's along the mro list?

No, he's referring to the (perhaps not widely advertised) fact that

obj[X]

is not quite the same as

obj.__getitem__(X)

since the explicit method invocation will find obj.dict["getitem"] if it exists but the operator syntax will start the search with obj.class.dict.

-- --Guido van Rossum (home page: http://www.python.org/~guido/)



More information about the Python-Dev mailing list