How do I enter a hint parameter or isinstancecheck an object that should be iterable and works with len? I assume that almost all objects with length are iterable, so it's really about what type, if any, represents objects that implement __len__.
def n_and_list(x: ???):
return len(x), [y for y in x]
This is not typing.Iterableor collections.Iterable, because they are true for things that do not have length, for example zip.
In [1]: from typing import Iterable
In [2]: isinstance(zip([]), Iterable)
Out[3]: True
In [3]: from collections import Iterable
In [4]: isinstance(zip([]), Iterable)
Out[4]: True
In [5]: len(zip([]))
TypeError Traceback (most recent call last)
<ipython-input-27-86d411a5426c> in <module>()
TypeError: object of type 'zip' has no len()
This is not typing.Sequenceor collections.Sequence, because they are false for things having a length, such as dictionary keys and numpy arrays.
In [6]: from typing import Sequence
In [7]: isinstance({}.keys(), Sequence)
Out[7]: False
In [8]: from numpy import asarray
In [9]: isinstance(asarray([]), Sequence)
Out[9]: False
In [10]: from collections import Sequence
In [11]: isinstance({}.keys(), Sequence)
Out[11]: False
In [12]: from numpy import asarray
In [13]: isinstance(asarray([]), Sequence)
Out[13]: False
This is not iterableor iterbecause they are not types. This is not listor tuplebecause they are too narrow.
source
share