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.

  1. from typing import TypeVar, SupportsAbs
  2.  
  3. 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.

  1. def largest_in_absolute_value(*xs: T) -> T:
  2. 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,

  1. largest_in_absolute_value(-3.5, 2) # Okay, has type float.
  2. largest_in_absolute_value(5+6j, 7) # Okay, has type complex.
  3. 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.