Skip to content

false positive bad-context-manager for overloaded __exit__ #1221

@jorenham

Description

@jorenham

Describe the Bug

from types import TracebackType
from typing import overload

class CM:
    def __enter__(self, /) -> None: ...
    @overload
    def __exit__(self, tp: None, ex: None, tb: None) -> None: ...
    @overload
    def __exit__(self, tp: type, ex: BaseException, tb: TracebackType) -> None: ...
    def __exit__(self, tp: type | None, ex: BaseException | None, tb: TracebackType | None) -> None: ...

with CM():
    pass
ERROR sandbox.py:12:6-10: Cannot use `CM` as a context manager [[bad-context-manager](https://pyrefly.org/en/docs/error-kinds/#bad-context-manager)]
  No matching overload found for function `CM.__exit__`
  Possible overloads:
  (tp: None, ex: None, tb: None) -> None [closest match]
  (tp: type, ex: BaseException, tb: TracebackType) -> None

I realize that that this is tighter than how e.g. typeshed annotates __exit__, but I believe that it's correct like this.

Sandbox Link

https://pyrefly.org/sandbox/?project=N4IgZglgNgpgziAXKOBDAdgEwEYHsAeAdAA4CeS4ATrgLYAEALqcfHRDcbpQ3QCqWoAxjGxCA1r2YwAOujDV6TYhHQBzNhy49cANxiUouVJlmzBUVHDh0AwgFlEsus7qYYYOgH1PMdA33eABRwMFBgADR0APQAlHQAtAB8dAByuOgwiHSEOU4uAAK6%2BobGec5uHt4w%2BBAMQSFhkQzEWWkZkdWt6TBN2F0ZcUmp3Vk5hGV0hXoGRiboLq7uXj41dZ7BoRGMLYxSHfhZAEKWMACi%2BMLEDBDpvVn8QiLikiyDyW2Z2bnzLhXL1bV6psmjslDA6AAfYbtOidOjHELnS7XdKQ6E9Rh9PgCYSiQQSKRoj5vdGjb6yADutQAFrY7IEYo4fs5iJY4LIQOEQABXa5QOAkciIEAAYjoAFU%2BbVSHQwNz0IIUeh2ehZH8wFwaKg6uhuTRsPpAgc2H4SXAGJQmQtKDAGNzKPMwNIQCk9QbLXRgPgAL7OjnerlCa56ABi0BgFDQWDwRDIIG9QA&version=3.13

(Only applicable for extension issues) IDE Information

No response

Metadata

Metadata

Assignees

Labels

UserBugs reported by external users that should be prioritisedneeds-discussionAn issue where it's not clear whether there is a bug or we are behaving as expected.

Type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions