Skip to content

fix: allow None for exc_tb in Traveller.__exit__ type annotations#974

Open
madhavcodez wants to merge 1 commit into
python-pendulum:masterfrom
madhavcodez:fix/traveller-exit-type-973
Open

fix: allow None for exc_tb in Traveller.__exit__ type annotations#974
madhavcodez wants to merge 1 commit into
python-pendulum:masterfrom
madhavcodez:fix/traveller-exit-type-973

Conversation

@madhavcodez

Copy link
Copy Markdown

When a with block exits without an exception, CPython calls __exit__(None, None, None), so all three parameters must accept None. On the travellers, exc_type and exc_val were already optional, but exc_tb was typed as TracebackType without | None. A type checker correctly infers that the traveller is not a valid context manager, which produces the invalid-context-manager error on with pendulum.travel_to(...) reported in #973.

What changed

Annotate exc_tb as TracebackType | None in BaseTraveller.__exit__ and the time_machine-backed Traveller.__exit__ (the remaining Traveller subclasses inherit from BaseTraveller).

Closes #973. The underlying false-positive trigger is also tracked upstream at astral-sh/ty#3832.

Verification

Reproduced the invalid-context-manager diagnostic before the change and confirmed it clears afterward (reverting the annotation brings it back). ruff and mypy --strict stay clean. This is annotation-only with no runtime or behavior change, so no tests were added. Happy to add a CHANGELOG entry once this PR has a number if you would like one.

CPython calls __exit__(None, None, None) when a with block exits without an
exception, so all three parameters must accept None. exc_type and exc_val were
already optional on the travellers, but exc_tb was annotated TracebackType
without | None, so a type checker infers the traveller is not a valid context
manager and reports invalid-context-manager on with pendulum.travel_to(...).

Annotate exc_tb as TracebackType | None in BaseTraveller.__exit__ and the
time_machine-backed Traveller.__exit__ (the other Traveller subclasses inherit
from BaseTraveller).

Closes python-pendulum#973
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

Type checker thinks pendulum.travel_to() does not implement Traveller.__exit__

1 participant