forked from fluentpython/example-code-2e
-
Notifications
You must be signed in to change notification settings - Fork 0
/
gen_contra.py
59 lines (38 loc) · 1.55 KB
/
gen_contra.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
"""
In ``Generator[YieldType, SendType, ReturnType]``,
``SendType`` is contravariant.
The other type variables are covariant.
This is how ``typing.Generator`` is declared::
class Generator(Iterator[T_co], Generic[T_co, T_contra, V_co]):
(from https://docs.python.org/3/library/typing.html#typing.Generator)
"""
from typing import Generator
# Generator[YieldType, SendType, ReturnType]
def gen_float_take_int() -> Generator[float, int, str]:
received = yield -1.0
while received:
received = yield float(received)
return 'Done'
def gen_float_take_float() -> Generator[float, float, str]:
received = yield -1.0
while received:
received = yield float(received)
return 'Done'
def gen_float_take_complex() -> Generator[float, complex, str]:
received = yield -1.0
while received:
received = yield abs(received)
return 'Done'
# Generator[YieldType, SendType, ReturnType]
g0: Generator[float, float, str] = gen_float_take_float()
g1: Generator[complex, float, str] = gen_float_take_float()
## Incompatible types in assignment
## expression has type "Generator[float, float, str]"
## variable has type "Generator[int, float, str]")
# g2: Generator[int, float, str] = gen_float_take_float()
# Generator[YieldType, SendType, ReturnType]
g3: Generator[float, int, str] = gen_float_take_float()
## Incompatible types in assignment
## expression has type "Generator[float, float, str]"
## variable has type "Generator[float, complex, str]")
## g4: Generator[float, complex, str] = gen_float_take_float()