On 2019-09-27 17:05, Steven D'Aprano wrote:
I keep finding myself needing to test for objects that support subscripting. This is one case where EAFP is *not* actually easier:
try: obj[0] except TypeError: subscriptable = False except (IndexError, KeyError): subscriptable = True else: subscriptable = True if subscriptable: ...
But I don't like manually testing for it like this:
if getattr(obj, '__getitem__', None) is not None: ...
because it is wrong. (Its wrong because an object with __getitem__ defined as an instance attribute isn't subscriptable; it has to be in the class, or a superclass.)
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'?