Skip to content

AbstractContextManager.__enter__ not properly annotated #13950

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
mharding-hpe opened this issue May 5, 2025 · 1 comment
Open

AbstractContextManager.__enter__ not properly annotated #13950

mharding-hpe opened this issue May 5, 2025 · 1 comment
Labels
stubs: false negative Type checkers do not report an error, but should

Comments

@mharding-hpe
Copy link

mharding-hpe commented May 5, 2025

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.

@srittau srittau transferred this issue from python/typing May 6, 2025
@srittau srittau added the stubs: false negative Type checkers do not report an error, but should label May 6, 2025
@srittau
Copy link
Collaborator

srittau commented May 6, 2025

This is due to the duality of AbstractContextManager being both an ABC and a protocol. As a protocol it makes sense that it is generic over the return type of __enter__. Ideally we'd give the type variable a default of Self, but I'm not sure that that's possible.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
stubs: false negative Type checkers do not report an error, but should
Projects
None yet
Development

No branches or pull requests

2 participants