@@ -201,3 +201,65 @@ You can also use a ``TypeVar`` with a restricted set of possible
201201values when defining a generic class. For example, mypy uses the type
202202``typing.Pattern[AnyStr] `` for the return value of ``re.compile ``,
203203since regular expressions can be based on a string or a bytes pattern.
204+
205+ .. _type-variable-upper-bound :
206+
207+ Type variables with upper bounds
208+ ********************************
209+
210+ A type variable can also be restricted to having values that are
211+ subtypes of a specific type. This type is called the upper bound of
212+ the type variable, and is specified with the ``bound=... `` keyword
213+ argument to ``TypeVar ``.
214+
215+ .. code-block :: python
216+
217+ from typing import TypeVar, SupportsAbs
218+
219+ T = TypeVar(' T' , bound = SupportsAbs[float ])
220+
221+ In the definition of a generic function that uses such a type variable
222+ ``T ``, the type represented by ``T `` is assumed to be a subtype of
223+ its upper bound, so the function can use methods of the upper bound on
224+ values of type ``T ``.
225+
226+ .. code-block :: python
227+
228+ def largest_in_absolute_value (* xs : T) -> T:
229+ return max (xs, key = abs ) # Okay, because T is a subtype of SupportsAbs[float].
230+
231+ In a call to such a function, the type ``T `` must be replaced by a
232+ type that is a subtype of its upper bound. Continuing the example
233+ above,
234+
235+ .. code-block :: python
236+
237+ largest_in_absolute_value(- 3.5 , 2 ) # Okay, has type float.
238+ largest_in_absolute_value(5 + 6j , 7 ) # Okay, has type complex.
239+ largest_in_absolute_value(' a' , ' b' ) # Error: 'str' is not a subtype of SupportsAbs[float].
240+
241+ Type parameters of generic classes may also have upper bounds, which
242+ restrict the valid values for the type parameter in the same way.
243+
244+ A type variable may not have both a value restriction (see
245+ :ref: `type-variable-value-restriction `) and an upper bound.
246+
247+ One common application of type variable upper bounds is in declaring
248+ the types of decorators that do not change the type of the function
249+ they decorate:
250+
251+ .. code-block :: python
252+
253+ from typing import TypeVar, Callable, Any
254+
255+ AnyCallable = TypeVar(' AnyCallable' , bound = Callable[... , Any])
256+
257+ def my_decorator (f : AnyCallable) -> AnyCallable: ...
258+
259+ @my_decorator
260+ def my_function (x : int , y : str ) -> bool :
261+ ...
262+
263+ The decorated ``my_function `` still has type ``Callable[[int, str],
264+ bool] ``. Due to the bound on ``AnyCallable ``, an application of the
265+ decorator to a non-function like ``my_decorator(1) `` will be rejected.
0 commit comments