On Fri, Sep 27, 2019 at 9:14 AM Steven D'Aprano <steve@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