I have a function that uses the len function on one of it\'s parameters and iterates over the parameter. Now I can choose whether to annotate the type with
Starting from Python3.6 there's a new type called Collection. See here.
In the future Protocols will be introduced. They are already available through typing_extensions. See also PEP 544. Using Protocol the code above would be:
from typing_extensions import Protocol
class SizedIterable(Protocol):
def __len__(self):
pass
def __iter__(self):
pass
def foo(some_thing: SizedIterable):
print(len(some_thing))
for part in some_thing:
print(part)
foo(['a', 'b', 'c'])
mypy takes that code without complaining. But PyCharm is saying
Expected type 'SizedIterable', got 'List[str]'
about the last line.
You should go with Sequence from typing if you plan to use only list or tuple and access its elements by index, like x[0]. Sequence is both Sized and Iterable, see here.
Maybe you need a class like this?
class MyArray:
_array: list
def as_tuple(self):
return tuple(self._array)
def as_list(self):
return self._array
# More Feature to implement