PEP 484: Fix upper bound example (#1421)

The example in the PEP was incorrect: it does not work since it would require `Comparable` to be defined as a Protocol, which were introduced in a later PEP (PEP 544).

For more info see #1419.
This commit is contained in:
Matt 2020-06-05 21:30:54 -07:00 committed by GitHub
parent f712231777
commit a04c3acd3f
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with 8 additions and 19 deletions

View File

@ -722,32 +722,21 @@ Type variables with an upper bound
A type variable may specify an upper bound using ``bound=<type>`` (note:
<type> itself cannot be parameterized by type variables). This means that an
actual type substituted (explicitly or implicitly) for the type variable must
be a subtype of the boundary type. A common example is the definition of a
``Comparable`` type that works well enough to catch the most common errors::
be a subtype of the boundary type. Example::
from typing import TypeVar
from typing import TypeVar, Sized
class Comparable(metaclass=ABCMeta):
@abstractmethod
def __lt__(self, other: Any) -> bool: ...
... # __gt__ etc. as well
ST = TypeVar('ST', bound=Sized)
CT = TypeVar('CT', bound=Comparable)
def min(x: CT, y: CT) -> CT:
if x < y:
def longer(x: ST, y: ST) -> ST:
if len(x) > len(y):
return x
else:
return y
min(1, 2) # ok, return type int
min('x', 'y') # ok, return type str
(Note that this is not ideal -- for example ``min('x', 1)`` is invalid
at runtime but a type checker would simply infer the return type
``Comparable``. Unfortunately, addressing this would require
introducing a much more powerful and also much more complicated
concept, F-bounded polymorphism. We may revisit this in the future.)
longer([1], [1, 2]) # ok, return type List[int]
longer({1}, {1, 2}) # ok, return type Set[int]
longer([1], {1, 2}) # ok, return type Collection[int]
An upper bound cannot be combined with type constraints (as in used
``AnyStr``, see the example earlier); type constraints cause the