I would like to perform an operation on an argument based on the fact that it can be an object similar to a map, or an object similar to a sequence. I understand that no strategy will be 100% reliable for type checking, but I'm looking for a reliable solution.
Based on this answer , I know how to determine if something is a sequence, and I can perform this check after checking if the object is a map.
def ismap(arg):
Since a sequence can be thought of as a card, where the keys are integers, should you just try to find a key that is not an integer? Or maybe I could take a look at the string representation? or...?
UPDATE
I chose the answer from SilentGhost because it looks like the most “correct” one, but for my needs, here is the solution I completed:
if hasattr(arg, 'keys') and hasattr(arg, '__getitem__'):
Essentially, I don't want to rely on ABC because there are so many custom classes that behave like sequences and vocabulary words, but that still don't extend the ABC ABC collections (see @Manoj comment). I thought the key attribute (mentioned by someone who deleted his / her answer) was good enough for matching.
Classes extending ABC with sequence and mapping will also work with this solution.
python dictionary sequence
Barthelemy
source share