Improve type for setdefault() (#6941)

- With one argument, it may return None
- With two arguments, it returns the default's type or the dict's value type.
- Also remove incorrect `= ...` from `pop()`. The one-argument case has its own overload.

Context: https://github.com/python/typing/discussions/1033#discussioncomment-1986359

Co-authored-by: Shantanu <12621235+hauntsaninja@users.noreply.github.com>
This commit is contained in:
Jelle Zijlstra
2022-01-19 21:44:15 -08:00
committed by GitHub
parent aea52b35d1
commit 1f000d2881

View File

@@ -468,9 +468,13 @@ class MutableMapping(Mapping[_KT, _VT], Generic[_KT, _VT]):
@overload
def pop(self, __key: _KT) -> _VT: ...
@overload
def pop(self, __key: _KT, __default: _VT | _T = ...) -> _VT | _T: ...
def pop(self, __key: _KT, __default: _VT | _T) -> _VT | _T: ...
def popitem(self) -> tuple[_KT, _VT]: ...
def setdefault(self, __key: _KT, __default: _VT = ...) -> _VT: ...
# This overload should be allowed only if the value type is compatible with None.
@overload
def setdefault(self: MutableMapping[_KT, _T | None], __key: _KT) -> _T | None: ...
@overload
def setdefault(self, __key: _KT, __default: _VT) -> _VT: ...
# 'update' used to take a Union, but using overloading is better.
# The second overloaded type here is a bit too general, because
# Mapping[Tuple[_KT, _VT], W] is a subclass of Iterable[Tuple[_KT, _VT]],