diff --git a/pep-0484.txt b/pep-0484.txt index 564343cd5..ac0c7f65b 100644 --- a/pep-0484.txt +++ b/pep-0484.txt @@ -722,32 +722,21 @@ Type variables with an upper bound A type variable may specify an upper bound using ``bound=`` (note: 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