Correct way to detect sequence parameter?

后端 未结 12 1556
情书的邮戳
情书的邮戳 2020-11-28 13:48

I want to write a function that accepts a parameter which can be either a sequence or a single value. The type of value is str, int, etc., but I don\'t want

12条回答
  •  夕颜
    夕颜 (楼主)
    2020-11-28 14:10

    Sequences are described here: https://docs.python.org/2/library/stdtypes.html#sequence-types-str-unicode-list-tuple-bytearray-buffer-xrange

    So sequences are not the same as iterable objects. I think sequence must implement __getitem__, whereas iterable objects must implement __iter__. So for example string are sequences and don't implement __iter__, xrange objects are sequences and don't implement __getslice__.

    But from what you seen to want to do, I'm not sure you want sequences, but rather iterable objects. So go for hasattr("__getitem__", X) you want sequences, but go rather hasattr("__iter__", X) if you don't want strings for example.

提交回复
热议问题