Type variables with upper bounds
A type variable can also be restricted to having values that aresubtypes of a specific type. This type is called the upper bound ofthe type variable, and is specified with the bound=…
keywordargument to TypeVar
.
- from typing import TypeVar, SupportsAbs
- T = TypeVar('T', bound=SupportsAbs[float])
In the definition of a generic function that uses such a type variableT
, the type represented by T
is assumed to be a subtype ofits upper bound, so the function can use methods of the upper bound onvalues of type T
.
- def largest_in_absolute_value(*xs: T) -> T:
- return max(xs, key=abs) # Okay, because T is a subtype of SupportsAbs[float].
In a call to such a function, the type T
must be replaced by atype that is a subtype of its upper bound. Continuing the exampleabove,
- largest_in_absolute_value(-3.5, 2) # Okay, has type float.
- largest_in_absolute_value(5+6j, 7) # Okay, has type complex.
- largest_in_absolute_value('a', 'b') # Error: 'str' is not a subtype of SupportsAbs[float].
Type parameters of generic classes may also have upper bounds, whichrestrict the valid values for the type parameter in the same way.
A type variable may not have both a value restriction (seeType variables with value restriction) and an upper bound.