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):
elif isinstance(x, Set):
One of the "gotchas" that spurred me several times is that str
, bytes
and s bytearray
are 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]))
, , : , ( ). , , 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.)