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