Skip to content

Commit 6c3d109

Browse files
Add type annotations to compat.to_str() and compat.to_bytes().
- I'm not sure if these functions are truly necessary if the library no longer supports Python 2, but the use of it with `encoding` is prevalant enough around the library that it seems worth typing. - The overloads are necessary to account for None being a passthrough value. - Two cases of this are `ParseResult.copy_with()` and `ParseResultBytes.copy_with()`. The `attrs_dict` dictionary in those methods is allowed to have None, and None is allowed for all of the component parameters (from what I can tell). Thus, whether intentional or not, `compat.to_(bytes|str)()`'s ability to let values pass through without modification, so long as they aren't bytes, is depended upon.
1 parent 9df0355 commit 6c3d109

File tree

1 file changed

+29
-2
lines changed

1 file changed

+29
-2
lines changed

src/rfc3986/compat.py

+29-2
Original file line numberDiff line numberDiff line change
@@ -12,21 +12,48 @@
1212
# See the License for the specific language governing permissions and
1313
# limitations under the License.
1414
"""Compatibility module for Python 2 and 3 support."""
15+
import typing as t
1516

1617
__all__ = (
1718
"to_bytes",
1819
"to_str",
1920
)
2021

2122

22-
def to_str(b, encoding="utf-8"):
23+
@t.overload
24+
def to_str(b: t.Union[str, bytes], encoding: str = "utf-8") -> str:
25+
...
26+
27+
28+
@t.overload
29+
def to_str(b: None, encoding: str = "utf-8") -> None:
30+
...
31+
32+
33+
def to_str(
34+
b: t.Optional[t.Union[str, bytes]],
35+
encoding: str = "utf-8",
36+
) -> t.Optional[str]:
2337
"""Ensure that b is text in the specified encoding."""
2438
if hasattr(b, "decode") and not isinstance(b, str):
2539
b = b.decode(encoding)
2640
return b
2741

2842

29-
def to_bytes(s, encoding="utf-8"):
43+
@t.overload
44+
def to_bytes(s: t.Union[str, bytes], encoding: str = "utf-8") -> bytes:
45+
...
46+
47+
48+
@t.overload
49+
def to_bytes(s: None, encoding: str = "utf-8") -> None:
50+
...
51+
52+
53+
def to_bytes(
54+
s: t.Optional[t.Union[str, bytes]],
55+
encoding: str = "utf-8",
56+
) -> t.Optional[bytes]:
3057
"""Ensure that s is converted to bytes from the encoding."""
3158
if hasattr(s, "encode") and not isinstance(s, bytes):
3259
s = s.encode(encoding)

0 commit comments

Comments
 (0)