Python: check if an object is a sequence

后端 未结 8 2040
长情又很酷
长情又很酷 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:59

    For Python 3 and 2.6+, you can check if it's a subclass of collections.Sequence:

    >>> import collections
    >>> isinstance(myObject, collections.Sequence)
    True
    

    In Python 3.7 you must use collections.abc.Sequence (collections.Sequence will be removed in Python 3.8):

    >>> import collections.abc
    >>> isinstance(myObject, collections.abc.Sequence)
    True
    

    However, this won't work for duck-typed sequences which implement __len__() and __getitem__() but do not (as they should) subclass collections.Sequence. But it will work for all the built-in Python sequence types: lists, tuples, strings, etc.

    While all sequences are iterables, not all iterables are sequences (for example, sets and dictionaries are iterable but not sequences). Checking hasattr(type(obj), '__iter__') will return True for dictionaries and sets.

提交回复
热议问题