On Dec 30, 2015, at 10:09, Sven R. Kunze email@example.com wrote:
On 29.12.2015 03:59, Nick Coghlan wrote:
On 28 December 2015 at 03:04, Guido van Rossum firstname.lastname@example.org wrote: [ABCs are one honking great idea -- let's do more of those!]
[collections.abc.Indexable would be a good one.]
Maybe, I still cannot wrap my mind enough around the types-everywhere-in-python-please world.
But, what's so wrong about checking for __getitem__ or __len__ if necessary?
Well, for one thing, that will pick up mappings, generic types, and various other things that aren't indexable but use __getitem__ for other purposes.
It's the same problem as this thread in reverse: checking for __iter__ gives you false negatives because of the old-style sequence protocol; checking for __getitem__ gives you false positives because of the mapping protocol. But false positives are generally worse. Normally, you'd just EAFP it and write seq[idx] and deal with any exception; if you have to LBYL for some reason, a test that incorrectly passes many common values is not very helpful.
Of course you could try a more stringent test--check for __getitem__ but not keys and not __extra__ and so on--but then you have to do that test everywhere; better to centralize it in one place.
Or, even better, to just accept that some things are not feasible for structural tests and just test for types that explicitly declare themselves Indexable (by inheritance or registration). That way, you may get false negatives, but not on common types, and it only takes one line of code to register that third-party class with Sequence if you need to--and no false positives.
Also, of course, ABCs are often useful as mixins. The fact that I can write a fully-fledged sequence with all the bells and whistles in 10 lines of code by inheriting from Sequence is pretty nice. Getting things like __iter__ for free by inheriting from Indexable (especially if the old-style sequence protocol is deprecated) would be similarly nice.
Again, you don't need to test for this all over the place--most of the time, you'll just EAFP. But when you do need to have a test, better to have one that says what it means, and doesn't pass false positives, and can be easily hooked for weird third-party classes, and so on.