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:
parent
f712231777
commit
a04c3acd3f
27
pep-0484.txt
27
pep-0484.txt
|
@ -722,32 +722,21 @@ Type variables with an upper bound
|
||||||
A type variable may specify an upper bound using ``bound=<type>`` (note:
|
A type variable may specify an upper bound using ``bound=<type>`` (note:
|
||||||
<type> itself cannot be parameterized by type variables). This means that an
|
<type> itself cannot be parameterized by type variables). This means that an
|
||||||
actual type substituted (explicitly or implicitly) for the type variable must
|
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
|
be a subtype of the boundary type. Example::
|
||||||
``Comparable`` type that works well enough to catch the most common errors::
|
|
||||||
|
|
||||||
from typing import TypeVar
|
from typing import TypeVar, Sized
|
||||||
|
|
||||||
class Comparable(metaclass=ABCMeta):
|
ST = TypeVar('ST', bound=Sized)
|
||||||
@abstractmethod
|
|
||||||
def __lt__(self, other: Any) -> bool: ...
|
|
||||||
... # __gt__ etc. as well
|
|
||||||
|
|
||||||
CT = TypeVar('CT', bound=Comparable)
|
def longer(x: ST, y: ST) -> ST:
|
||||||
|
if len(x) > len(y):
|
||||||
def min(x: CT, y: CT) -> CT:
|
|
||||||
if x < y:
|
|
||||||
return x
|
return x
|
||||||
else:
|
else:
|
||||||
return y
|
return y
|
||||||
|
|
||||||
min(1, 2) # ok, return type int
|
longer([1], [1, 2]) # ok, return type List[int]
|
||||||
min('x', 'y') # ok, return type str
|
longer({1}, {1, 2}) # ok, return type Set[int]
|
||||||
|
longer([1], {1, 2}) # ok, return type Collection[int]
|
||||||
(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.)
|
|
||||||
|
|
||||||
An upper bound cannot be combined with type constraints (as in used
|
An upper bound cannot be combined with type constraints (as in used
|
||||||
``AnyStr``, see the example earlier); type constraints cause the
|
``AnyStr``, see the example earlier); type constraints cause the
|
||||||
|
|
Loading…
Reference in New Issue