example-code-2e/08-def-type-hints/typevars_constrained.py

27 lines
453 B
Python
Raw Normal View History

2021-05-24 03:12:13 +02:00
from typing import TypeVar, TYPE_CHECKING
from decimal import Decimal
# tag::TYPEVAR_RESTRICTED[]
RT = TypeVar('RT', float, Decimal)
def triple1(a: RT) -> RT:
return a * 3
2021-08-07 05:44:01 +02:00
res1 = triple1(2)
2021-05-24 03:12:13 +02:00
if TYPE_CHECKING:
reveal_type(res1)
# end::TYPEVAR_RESTRICTED[]
# tag::TYPEVAR_BOUNDED[]
BT = TypeVar('BT', bound=float)
def triple2(a: BT) -> BT:
return a * 3
2021-08-07 05:44:01 +02:00
res2 = triple2(2)
2021-05-24 03:12:13 +02:00
if TYPE_CHECKING:
reveal_type(res2)
# tag::TYPEVAR_BOUNDED[]