On Fri, Sep 27, 2019 at 12:03:52PM -0700, Andrew Barnert via Python-ideas wrote: > On Sep 27, 2019, at 10:15, MRAB <pyt...@mrabarnett.plus.com> wrote: > > > >> On 2019-09-27 17:05, Steven D'Aprano wrote: > >> > >> But doing it correctly is too painful: > >> if any(getattr(T, '__getitem__', None) is not None for T in > >> type(obj).mro()) > > [snip] > > > > Is there are reason why you're using 'getattr' instead of 'hasattr'? > > There is a difference here: if some class defines __getitem__ = None, > blocks it from looking like a subscriptable type.
I wish I had been clever enough to have thought of that, but I didn't. I used getattr because I completely forgot about the existence of hasattr. And I walked the MRO because oops. On the other hand, the collections.abc walks the MRO explicitly checking for None, so perhaps I might have accidentally been less wrong than had I just tried hasattr(type(obj)). See the _check_methods function here: https://github.com/python/cpython/blob/3.7/Lib/_collections_abc.py This supports my point that this ought to be handled once, correctly, in the standard library, like the other ABCs, instead of leaving it up to people like me to get it wrong. > That idiom is used for other things like __hash__, even if it’s not > used 100% consistently for all protocols. If you look at the 3.7 collections.abc, _check_methods is now used consistently by all of the __subclasshook__ methods. -- Steven _______________________________________________ Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-le...@python.org https://mail.python.org/mailman3/lists/python-ideas.python.org/ Message archived at https://mail.python.org/archives/list/python-ideas@python.org/message/7TSCXL4JQGMVWJVT22O264W3GU7UPTMY/ Code of Conduct: http://python.org/psf/codeofconduct/