PEP 484: Clarify definition of AnyStr (#744)
The definition of AnyStr as given makes sense only in Python 3, as observed by @srittau. To prevent confusion, this PR changes the definition to use Text instead of str. I also changed the two places where AnyStr was defined as an example, and made a few other related adjustments: - Remove mention of None as modifying the type, which is not true as of #689. - Move Text up in the list of convenience definition because we now need it for the definition of AnyStr. - Modify definition of Optional to use `None` instead of `type(None)`, because the latter is not a valid static type.
This commit is contained in:
parent
b991d19bf9
commit
18b3312574
17
pep-0484.txt
17
pep-0484.txt
|
@ -312,9 +312,9 @@ example, we can define a type variable that ranges over just ``str`` and
|
|||
``bytes``. By default, a type variable ranges over all possible types.
|
||||
Example of constraining a type variable::
|
||||
|
||||
from typing import TypeVar
|
||||
from typing import TypeVar, Text
|
||||
|
||||
AnyStr = TypeVar('AnyStr', str, bytes)
|
||||
AnyStr = TypeVar('AnyStr', Text, bytes)
|
||||
|
||||
def concat(x: AnyStr, y: AnyStr) -> AnyStr:
|
||||
return x + y
|
||||
|
@ -1357,8 +1357,7 @@ without specifying the actual default value. For example::
|
|||
def foo(x: AnyStr, y: AnyStr = ...) -> AnyStr: ...
|
||||
|
||||
What should the default value look like? Any of the options ``""``,
|
||||
``b""`` or ``None`` fails to satisfy the type constraint (actually,
|
||||
``None`` will *modify* the type to become ``Optional[AnyStr]``).
|
||||
``b""`` or ``None`` fails to satisfy the type constraint.
|
||||
|
||||
In such cases the default value may be specified as a literal
|
||||
ellipsis, i.e. the above example is literally what you would write.
|
||||
|
@ -1785,9 +1784,9 @@ A constrained ``TypeVar`` type can often be used instead of using the
|
|||
``@overload`` decorator. For example, the definitions of ``concat1``
|
||||
and ``concat2`` in this stub file are equivalent::
|
||||
|
||||
from typing import TypeVar
|
||||
from typing import TypeVar, Text
|
||||
|
||||
AnyStr = TypeVar('AnyStr', str, bytes)
|
||||
AnyStr = TypeVar('AnyStr', Text, bytes)
|
||||
|
||||
def concat1(x: AnyStr, y: AnyStr) -> AnyStr: ...
|
||||
|
||||
|
@ -2024,12 +2023,12 @@ A few one-off types are defined that test for single special methods
|
|||
|
||||
Convenience definitions:
|
||||
|
||||
* Optional, defined by ``Optional[t] == Union[t, type(None)]``
|
||||
|
||||
* AnyStr, defined as ``TypeVar('AnyStr', str, bytes)``
|
||||
* Optional, defined by ``Optional[t] == Union[t, None]``
|
||||
|
||||
* Text, a simple alias for ``str`` in Python 3, for ``unicode`` in Python 2
|
||||
|
||||
* AnyStr, defined as ``TypeVar('AnyStr', Text, bytes)``
|
||||
|
||||
* NamedTuple, used as
|
||||
``NamedTuple(type_name, [(field_name, field_type), ...])``
|
||||
and equivalent to
|
||||
|
|
Loading…
Reference in New Issue