From f1ad6c55fb3e03e0279e89ade66c86736e8d3edb Mon Sep 17 00:00:00 2001 From: wouter bolsterlee Date: Tue, 30 Jun 2020 19:51:57 +0200 Subject: [PATCH] Use correct return type annotation for BaseException.with_traceback MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit The return type of the BaseException.with_traceback() method [1] is not specific enough. The return type is guaranteed to be of the same type as ‘self’, which is usually a subclass of BaseException. In fact, .with_traceback() returns ‘self’: try: raise ValueError except Exception as exc: assert exc.with_traceback(None) is exc Fix the annotation to reflect this using the self-type annotation technique described in PEP484 [2], which is supported by (at least) mypy [3]. [1] https://docs.python.org/3/library/exceptions.html#BaseException.with_traceback [2] https://www.python.org/dev/peps/pep-0484/#annotating-instance-and-class-methods [3] https://github.com/python/mypy/issues/1212 --- stdlib/2/__builtin__.pyi | 3 ++- stdlib/2and3/builtins.pyi | 3 ++- 2 files changed, 4 insertions(+), 2 deletions(-) diff --git a/stdlib/2/__builtin__.pyi b/stdlib/2/__builtin__.pyi index 24c93a18e857..650a19fa8a26 100644 --- a/stdlib/2/__builtin__.pyi +++ b/stdlib/2/__builtin__.pyi @@ -82,6 +82,7 @@ _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _TT = TypeVar("_TT", bound="type") _LT = TypeVar("_LT", bound=_SupportsLessThan) +_TBE = TypeVar("_TBE", bound="BaseException") class object: __doc__: Optional[str] @@ -1775,7 +1776,7 @@ class BaseException(object): def __getitem__(self, i: int) -> Any: ... def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... if sys.version_info >= (3,): - def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... + def with_traceback(self: _TBE, tb: Optional[TracebackType]) -> _TBE: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ... diff --git a/stdlib/2and3/builtins.pyi b/stdlib/2and3/builtins.pyi index 24c93a18e857..650a19fa8a26 100644 --- a/stdlib/2and3/builtins.pyi +++ b/stdlib/2and3/builtins.pyi @@ -82,6 +82,7 @@ _T4 = TypeVar("_T4") _T5 = TypeVar("_T5") _TT = TypeVar("_TT", bound="type") _LT = TypeVar("_LT", bound=_SupportsLessThan) +_TBE = TypeVar("_TBE", bound="BaseException") class object: __doc__: Optional[str] @@ -1775,7 +1776,7 @@ class BaseException(object): def __getitem__(self, i: int) -> Any: ... def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ... if sys.version_info >= (3,): - def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ... + def with_traceback(self: _TBE, tb: Optional[TracebackType]) -> _TBE: ... class GeneratorExit(BaseException): ... class KeyboardInterrupt(BaseException): ...