Skip to content

Commit da189bd

Browse files
authored
Use Union[bytes, Text] instead of AnyStr
It seems that AnyStr has the main advantage of ensuring that multiple arguments (or argument(s) and return values) have the same type (i.e. `str` and `bytes` are both okay but shouldn't be mixed). However it makes it significantly more difficult to cast to a single type. With a Union, something like: ```python def foo(a: Union[bytes, Text]) -> Text: if isinstance(a, bytes): a = a.decode() return "Hello, " + a ``` works fine. With AnyStr, you have to define a new intermediate variable, something like: ```python def foo(a: AnyStr) -> str: if isinstance(a, bytes): b = a.decode() else: b = a return "Hello, " + b ``` If there's no advantage to using AnyStr (since there's no other AnyStr argument or return value), I think the Union would be simpler, have no significant disadvantage, and there is [precedent for similar changes](python#1054). > It's only the case that if there's exactly one parameter of type exactly AnyStr, and no other use of AnyStr in the signature, then Union[str, bytes] should be acceptable. - [gvanrossum](python#439 (comment)) Discussion: - python#1054 - python/mypy#1141 - python#439
1 parent 7073bc0 commit da189bd

1 file changed

Lines changed: 3 additions & 3 deletions

File tree

‎stdlib/3.4/asyncio/protocols.pyi‎

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
11
from asyncio import transports
2-
from typing import AnyStr, List, Tuple
2+
from typing import List, Text, Tuple, Union
33

44
__all__: List[str]
55

@@ -15,10 +15,10 @@ class Protocol(BaseProtocol):
1515
def eof_received(self) -> bool: ...
1616

1717
class DatagramProtocol(BaseProtocol):
18-
def datagram_received(self, data: AnyStr, addr: Tuple[str, int]) -> None: ...
18+
def datagram_received(self, data: Union[bytes, Text], addr: Tuple[str, int]) -> None: ...
1919
def error_received(self, exc: Exception) -> None: ...
2020

2121
class SubprocessProtocol(BaseProtocol):
22-
def pipe_data_received(self, fd: int, data: AnyStr) -> None: ...
22+
def pipe_data_received(self, fd: int, data: Union[bytes, Text]) -> None: ...
2323
def pipe_connection_lost(self, fd: int, exc: Exception) -> None: ...
2424
def process_exited(self) -> None: ...

0 commit comments

Comments
 (0)