AbstractContextManager.enter not properly annotated · Issue #13950 · python/typeshed (original) (raw)
Per the Python docs, AbstractContextManager
provides a default __enter__
implementation which just returns self
. But this does not appear to be properly type annotated (using Self
):
from typing import reveal_type, Optional, Self from types import TracebackType from contextlib import AbstractContextManager
class A1(AbstractContextManager): def exit( # pylint: disable=useless-return self, exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]: return None
class A2(AbstractContextManager): def exit( # pylint: disable=useless-return self, exc_type: Optional[type[BaseException]], exc_val: Optional[BaseException], exc_tb: Optional[TracebackType]) -> Optional[bool]: return None
def __enter__(self) -> Self:
return self
class B1(A1): pass
class B2(A2): pass
with B1() as d1: reveal_type(d1)
with B2() as d2: reveal_type(d2)
Running this with mypy, only the second case properly reveals the type as B2
. The first one just says Any
.
At runtime, the behavior of both is identical.
I have recreated this on both Python 3.12 and Python 3.13.