From 1f000d28813d1a4720a67e4f282c00d0c904921b Mon Sep 17 00:00:00 2001 From: Jelle Zijlstra Date: Wed, 19 Jan 2022 21:44:15 -0800 Subject: [PATCH] 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> --- stdlib/typing.pyi | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/stdlib/typing.pyi b/stdlib/typing.pyi index 270b9bb56..c4f9819ed 100644 --- a/stdlib/typing.pyi +++ b/stdlib/typing.pyi @@ -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]],