Skip to content

Commit 6a23335

Browse files
committed
fix(mypy): properly describe link between parameter and return types
This gives mypy all information that it needs to determine what the return type of a function call is *iff* it knows the argument's type. As a result it can now stop complaining about passing None to str.join() in exc.py.
1 parent 74a1b17 commit 6a23335

File tree

1 file changed

+28
-2
lines changed

1 file changed

+28
-2
lines changed

git/compat.py

+28-2
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,16 @@
1818

1919
# typing --------------------------------------------------------------------
2020

21-
from typing import IO, Any, AnyStr, Dict, Optional, Type, Union
21+
from typing import (
22+
Any,
23+
AnyStr,
24+
Dict,
25+
IO,
26+
Optional,
27+
Type,
28+
Union,
29+
overload,
30+
)
2231
from git.types import TBD
2332

2433
# ---------------------------------------------------------------------------
@@ -30,6 +39,12 @@
3039
defenc = sys.getfilesystemencoding()
3140

3241

42+
@overload
43+
def safe_decode(s: None) -> None: ...
44+
45+
@overload
46+
def safe_decode(s: Union[IO[str], AnyStr]) -> str: ...
47+
3348
def safe_decode(s: Union[IO[str], AnyStr, None]) -> Optional[str]:
3449
"""Safely decodes a binary string to unicode"""
3550
if isinstance(s, str):
@@ -42,6 +57,12 @@ def safe_decode(s: Union[IO[str], AnyStr, None]) -> Optional[str]:
4257
raise TypeError('Expected bytes or text, but got %r' % (s,))
4358

4459

60+
@overload
61+
def safe_encode(s: None) -> None: ...
62+
63+
@overload
64+
def safe_encode(s: AnyStr) -> bytes: ...
65+
4566
def safe_encode(s: Optional[AnyStr]) -> Optional[bytes]:
4667
"""Safely encodes a binary string to unicode"""
4768
if isinstance(s, str):
@@ -54,6 +75,12 @@ def safe_encode(s: Optional[AnyStr]) -> Optional[bytes]:
5475
raise TypeError('Expected bytes or text, but got %r' % (s,))
5576

5677

78+
@overload
79+
def win_encode(s: None) -> None: ...
80+
81+
@overload
82+
def win_encode(s: AnyStr) -> bytes: ...
83+
5784
def win_encode(s: Optional[AnyStr]) -> Optional[bytes]:
5885
"""Encode unicodes for process arguments on Windows."""
5986
if isinstance(s, str):
@@ -65,7 +92,6 @@ def win_encode(s: Optional[AnyStr]) -> Optional[bytes]:
6592
return None
6693

6794

68-
6995
def with_metaclass(meta: Type[Any], *bases: Any) -> 'metaclass': # type: ignore ## mypy cannot understand dynamic class creation
7096
"""copied from https://github.com/Byron/bcore/blob/master/src/python/butility/future.py#L15"""
7197

0 commit comments

Comments
 (0)