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))? 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. _GenericAlias is probably not the best example here, but it is an example. But it is close to the same thing. I can’t think of too many cases where you want to work with sequences and mappings and generic static types the same way. Plus, it seems like it’s actually a more direct LBYL translation of what you’re EAFPing with your except (IndexError, KeyError) test. I think the only real issue is that it’s no too uncommon to create a type that acts like a sequence but doesn’t register with Sequence. Maybe that’s enough to make it unusable for some important uses? Your Indexable class could be implicit (like Sized, Iterable, etc.), which would solve that problem if it’s a problem (at the cost of possibly unintentionally including things like _GenericAlias, but that may not be much cost—and may not even be unintentional?). Or I may be missing something that makes (Sequence, Mapping) inappropriate, of course.