How to distinguish between sequence and display

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): # How to implement this? def isseq(arg): return hasattr(arg,"__iter__") def operation(arg): if ismap(arg): # Do something with a dict-like object elif isseq(arg): # Do something with a sequence-like object else: # Do something else 

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__'): # Do something with a map elif hasattr(arg, '__iter__'): # Do something with a sequence/iterable else: # Do something else 

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.

+6
python dictionary sequence
source share
2 answers
 >>> from collections import Mapping, Sequence >>> isinstance('ac', Sequence) True >>> isinstance('ac', Mapping) False >>> isinstance({3:42}, Mapping) True >>> isinstance({3:42}, Sequence) False 

collections abstract base classes (ABC)

+10
source share

Sequences have the __add__ method, which implements the + operator. Maps do not have this method, since adding to a map requires both a key and a value, and the + operator has only one right side.

So you can try:

 def ismap(arg): return isseq(arg) and not hasattr(arg, "__add__") 
+1
source share

All Articles