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] https://github.com/python/mypy/issues/1212
This commit is contained in:
wouter bolsterlee
2020-06-30 20:40:25 +02:00
committed by GitHub
parent 8cf3cd398e
commit 83e955b52f
2 changed files with 4 additions and 2 deletions

View File

@@ -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): ...

View File

@@ -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): ...