example-code-2e/15-more-types/mysum.py

15 lines
381 B
Python
Raw Normal View History

2021-06-09 05:13:02 +02:00
import functools
import operator
from collections.abc import Iterable
from typing import overload, Union, TypeVar
2020-06-11 19:58:15 +02:00
T = TypeVar('T')
2021-06-09 05:13:02 +02:00
S = TypeVar('S') # <1>
2020-06-11 19:58:15 +02:00
@overload
2021-06-09 05:13:02 +02:00
def sum(it: Iterable[T]) -> Union[T, int]: ... # <2>
2020-06-11 19:58:15 +02:00
@overload
2021-06-09 05:13:02 +02:00
def sum(it: Iterable[T], /, start: S) -> Union[T, S]: ... # <3>
def sum(it, /, start=0): # <4>
return functools.reduce(operator.add, it, start)