On Fri, Sep 27, 2019 at 9:14 AM Steven D'Aprano <st...@pearwood.info> wrote:

> But doing it correctly is too painful:
>
>     if any(getattr(T, '__getitem__', None) is not None for T in
> type(obj).mro())
>

For what it's worth, walking the MRO isn't necessary, and the None trick is
only necessary if you want to support people that reuse the __getitem__
name for something else. (And it's often reasonable to say "nope, I don't
support that.")

>>> class A(object):
...   def __getitem__(self, i): return i
>>> class B(A): pass
...
>>> hasattr(B, '__getitem__')
True

So for a given object, one could check hasattr(type(obj), '__getitem__').
Or do the None trick with it, but without checking the MRO. (Or replace
None with a sentinel object()...)

-- Devin
_______________________________________________
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/AFJISUYDKGGOLL7ZCOWNNBVTAGXJPFXX/
Code of Conduct: http://python.org/psf/codeofconduct/

Reply via email to