Python: check if an object is a sequence

后端 未结 8 2039
长情又很酷
长情又很酷 2020-12-05 09:17

In python is there an easy way to tell if something is not a sequence? I tried to just do: if x is not sequence but python did not like that

8条回答
  •  清歌不尽
    2020-12-05 09:41

    Since Python "adheres" duck typing, one of the approach is to check if an object has some member (method).

    A sequence has length, has sequence of items, and support slicing [doc]. So, it would be like this:

    def is_sequence(obj):
        t = type(obj)
        return hasattr(t, '__len__') and hasattr(t, '__getitem__')
        # additionally: and hasattr(t, '__setitem__') and hasattr(t, '__delitem__')
    

    They are all special methods, __len__() should return number of items, __getitem__(i) should return an item (in sequence it is i-th item, but not with mapping), __getitem__(slice(start, stop, step)) should return subsequence, and __setitem__ and __delitem__ like you expect. This is such a contract, but whether the object really do these or not depends on whether the object adheres the contract or not.

    Note that, the function above will also return True for mapping, e.g. dict, since mapping also has these methods. To overcome this, you can do a heavier work:

    def is_sequence(obj):
        try:
            len(obj)
            obj[0:0]
            return True
        except TypeError:
            return False
    

    But most of the time you don't need this, just do what you want as if the object is a sequence and catch an exception if you wish. This is more pythonic.

提交回复
热议问题