Skip to content

Commit 4d21d5a

Browse files
authored
codecs: allow str to bytes decoding for "hex", fix overloads (#7118)
Fixes #7115 Co-authored-by: hauntsaninja <>
1 parent fc60d02 commit 4d21d5a

File tree

1 file changed

+12
-6
lines changed

1 file changed

+12
-6
lines changed

stdlib/codecs.pyi

Lines changed: 12 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -35,8 +35,8 @@ class _IncrementalDecoder(Protocol):
3535
def __call__(self, errors: str = ...) -> IncrementalDecoder: ...
3636

3737
# The type ignore on `encode` and `decode` is to avoid issues with overlapping overloads, for more details, see #300
38-
# mypy and pytype disagree about where the type ignore can and cannot go, so alias the long type
39-
_BytesToBytesEncodingT = Literal[
38+
# https://docs.python.org/3/library/codecs.html#binary-transforms
39+
_BytesToBytesEncoding = Literal[
4040
"base64",
4141
"base_64",
4242
"base64_codec",
@@ -54,17 +54,23 @@ _BytesToBytesEncodingT = Literal[
5454
"zlib",
5555
"zlib_codec",
5656
]
57+
# https://docs.python.org/3/library/codecs.html#text-transforms
58+
_StrToStrEncoding = Literal["rot13", "rot_13"]
5759

5860
@overload
59-
def encode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ...
61+
def encode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ...
6062
@overload
61-
def encode(obj: str, encoding: Literal["rot13", "rot_13", "hex"] = ..., errors: str = ...) -> str: ... # type: ignore[misc]
63+
def encode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ... # type: ignore[misc]
6264
@overload
6365
def encode(obj: str, encoding: str = ..., errors: str = ...) -> bytes: ...
6466
@overload
65-
def decode(obj: bytes, encoding: _BytesToBytesEncodingT, errors: str = ...) -> bytes: ... # type: ignore[misc]
67+
def decode(obj: bytes, encoding: _BytesToBytesEncoding, errors: str = ...) -> bytes: ... # type: ignore[misc]
6668
@overload
67-
def decode(obj: str, encoding: Literal["rot13", "rot_13", "hex"] = ..., errors: str = ...) -> str: ...
69+
def decode(obj: str, encoding: _StrToStrEncoding, errors: str = ...) -> str: ...
70+
71+
# hex is officially documented as a bytes to bytes encoding, but it appears to also work with str
72+
@overload
73+
def decode(obj: str, encoding: Literal["hex", "hex_codec"], errors: str = ...) -> bytes: ...
6874
@overload
6975
def decode(obj: bytes, encoding: str = ..., errors: str = ...) -> str: ...
7076
def lookup(__encoding: str) -> CodecInfo: ...

0 commit comments

Comments
 (0)