I am trying to introduce function annotation in Python 2 according to PEP 484 . The function accepts a container that must implement both __len__, and __iter__. The source code in which I want to add this annotation is quite complicated, so consider an example function that returns the product of all intin the container sif it len(s)is equal and returns 1 otherwise.
If I want to annotate a container where only it is required __len__, I would annotate it as type: (Sized) -> int. If I wanted to annotate a container where only needed __iter__, I would annotate it as type: (Iterable[int]) -> int. But how can I completely annotate a container in which I need both?
Edit:
I tried this as suggested by piotr-Ćwiek:
from __future__ import print_function
from typing import Sized, Iterable
class SizedIterable(Sized, Iterable[int]):
pass
def product2(numbers):
if len(numbers)%2 == 1:
return 1
else:
p = 1
for n in numbers:
p*= n
return p
print(product2([1, 2, 3, 4]))
print(product2({1, 2, 3, 4}))
but this failed with this error:
prod2.py:17: error: Argument 1 to "product2" has incompatible type List[int]; expected "SizedIterable"
prod2.py:18: error: Argument 1 to "product2" has incompatible type Set[int]; expected "SizedIterable"
source
share