Choose Bounds or Constraints
Core idea
A bound permits subtypes of a specified type and can preserve the subtype in the result. Constraints require a checker to solve the type variable to one of listed alternatives; subtype arguments may be promoted to a listed type. Neither mechanism validates arguments at runtime.
from typing import TypeVarclass Label(str): passT = TypeVar('T', bound=str)def preserve(x:T)->T: return xprint(type(preserve(Label('bay'))).__name__)The bound allows a str subclass; the function returns the original object.
Constrain matching representations
from typing import TypeVarS = TypeVar('S', str, bytes)def join(a:S,b:S)->S: return a+bprint(join('A','B'), join(b'A',b'B'))A checker selects str or bytes for the call; addition does the runtime work.
Common mistake
Constraints are not a union that independently accepts either alternative for each argument. Mixing str and bytes in join is invalid.
Practice
Compare the inferred return type of a subclass argument under a str bound and a str/bytes constraint.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Bounds and constraints
Check your understanding of bounds and constraints.
What is printed?
from typing import TypeVarT=TypeVar('T',bound=int)print(T.__bound__.__name__)What is printed?
from typing import TypeVarT=TypeVar('T',int,str)print(len(T.__constraints__))Which better preserves a subclass in an identity function?
What should a checker do with str and bytes passed to join above?