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