How to check sequences that are not string using Python 3 standard library

For some time, Python has had Abstract base classes (proposed in PEP 3119 ) that, especially for container types, make it easy to write code that generalizes custom types. For instance,

from collections.abc import Sequence, Set

if isinstance(x, Sequence):
    # Handle lists, tuples, or custom objects that behave like lists
elif isinstance(x, Set):
    # Handle anything that behaves like a set

One of the "gotchas" that spurred me several times is that str, bytesand s bytearrayare considered Sequence, in addition to more explicitly similar list objects:

from collections.abc import ByteString, Sequence

s = 'hello'
b = b'hello'
ba = bytearray(b'hello')
lst = [0, 1, 2]
t = (0, 1, 2)

islistlike = lambda x: isinstance(x, Sequence)

list(map(islistlike, [s, b, ba, lst, t])) # -> [True, True, True, True, True]

, , : , ( ). , , x , ? :

islistlike = lambda x: isinstance(x, Sequence) and not isinstance(x, (str, ByteString))

list(map(islistlike, [s, b, ba, lst, t])) # -> [False, False, False, True, True]

, , , - .

  • abc Python, islistlike = lambda x: isinstance(x, abc) ?
  • - Sequence ? ( PEP 3119.)
+6
1

, , str bytes . , .

+1

Source: https://habr.com/ru/post/1016643/


All Articles