Skip to content

Commit 83e955b

Browse files
authored
Use correct return type annotation for BaseException.with_traceback (#4298)
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] python/mypy#1212
1 parent 8cf3cd3 commit 83e955b

File tree

2 files changed

+4
-2
lines changed

2 files changed

+4
-2
lines changed

stdlib/2/__builtin__.pyi

+2-1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ _T4 = TypeVar("_T4")
8282
_T5 = TypeVar("_T5")
8383
_TT = TypeVar("_TT", bound="type")
8484
_LT = TypeVar("_LT", bound=_SupportsLessThan)
85+
_TBE = TypeVar("_TBE", bound="BaseException")
8586

8687
class object:
8788
__doc__: Optional[str]
@@ -1775,7 +1776,7 @@ class BaseException(object):
17751776
def __getitem__(self, i: int) -> Any: ...
17761777
def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ...
17771778
if sys.version_info >= (3,):
1778-
def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ...
1779+
def with_traceback(self: _TBE, tb: Optional[TracebackType]) -> _TBE: ...
17791780

17801781
class GeneratorExit(BaseException): ...
17811782
class KeyboardInterrupt(BaseException): ...

stdlib/2and3/builtins.pyi

+2-1
Original file line numberDiff line numberDiff line change
@@ -82,6 +82,7 @@ _T4 = TypeVar("_T4")
8282
_T5 = TypeVar("_T5")
8383
_TT = TypeVar("_TT", bound="type")
8484
_LT = TypeVar("_LT", bound=_SupportsLessThan)
85+
_TBE = TypeVar("_TBE", bound="BaseException")
8586

8687
class object:
8788
__doc__: Optional[str]
@@ -1775,7 +1776,7 @@ class BaseException(object):
17751776
def __getitem__(self, i: int) -> Any: ...
17761777
def __getslice__(self, start: int, stop: int) -> Tuple[Any, ...]: ...
17771778
if sys.version_info >= (3,):
1778-
def with_traceback(self, tb: Optional[TracebackType]) -> BaseException: ...
1779+
def with_traceback(self: _TBE, tb: Optional[TracebackType]) -> _TBE: ...
17791780

17801781
class GeneratorExit(BaseException): ...
17811782
class KeyboardInterrupt(BaseException): ...

0 commit comments

Comments
 (0)