A type annotates a function parameter as derived from several abstract base classes in Python

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):
    # type: (SizedIterable) -> int
    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"
+4
source share
1 answer

In python 3.6 there exists typing.Collectionone that works almost perfectly for your use case (it also inferred from Container, but really everything you want to use is likely to have one __contains__). Unfortunately, there is no solution for python 2.

SizedIterable , , , Sized Iterable, mypy, ; mypy , , Sized Iterable SizedIterable.

Mypy ; , , :

class A(Sized, Iterable[int]):
  def g(self) -> None:
    ...

def f(x: A) -> None:
  a.g()

# passes type check because [1, 2] is Sized and Iterable
# but fails in run-time
f([1, 2])

, mypy , .

mypy , mypy .

:

  • ( @PiotrĆwiek); , , Iterable Sized
  • ; , , , , , numbers __len__ __iter__

typing __instancecheck__ , ( -) - mypy - , (.. , ..). , mypy - , , (, python, ..).

0

All Articles