On Fri, Sep 27, 2019 at 10:11:15AM -0700, Andrew Barnert wrote:
On Sep 27, 2019, at 09:05, Steven D'Aprano <steve@pearwood.info> wrote:
What I'd really like to do is use the collections.abc module to do the check:
if isinstance(obj, collections.abc.Subscriptable): ...
What about isinstance(obj, (Sequence, Mapping))?
No, they require more than just being subscriptable. py> class Test(object): ... def __getitem__(self, idx): ... return idx**2 ... py> squares = Test() py> squares[5] 25 py> from collections.abc import Sequence, Mapping py> isinstance(squares, (Sequence, Mapping)) False One of the tests I want is for something which is subscriptable but not sized, like squares above. To be a (virtual) subclass of Sequence, the object has to provide __getitem__ and __len__, and to be a Mapping it also has to provide __iter__. Neither __len__ nor __iter__ are necessary for my purposes, and in fact __len__ may be undesirable.
That isn’t quite the same thing, since you can have types that are subscriptable, but its subscripts don’t mean either index or key.
Its not even close to the same thing :-(
_GenericAlias is probably not the best example here, but it is an example.
Where is that from?
Plus, it seems like it’s actually a more direct LBYL translation of what you’re EAFPing with your except (IndexError, KeyError) test.
Sorry, that doesn't fly. There's nothing in my except test which requires the existence of __len__. All I need is an object that supports subscripting, but the current state of the ABCs requires that I either roll my own test which will probably be wrong, or test for methods that I don't need or want. -- Steven