Skip to content

[flake8-pyi] Fix false positive for PEP 695 generic __exit__ methods (PYI036)#26381

Draft
kpeis695 wants to merge 1 commit into
astral-sh:mainfrom
kpeis695:fix/pyi036-clean
Draft

[flake8-pyi] Fix false positive for PEP 695 generic __exit__ methods (PYI036)#26381
kpeis695 wants to merge 1 commit into
astral-sh:mainfrom
kpeis695:fix/pyi036-clean

Conversation

@kpeis695

Copy link
Copy Markdown

Summary

Fixes #25905.

When __exit__ or __aexit__ uses a PEP 695 type parameter bound to BaseException, annotations like type[T] | None and T | None are valid but PYI036 incorrectly flags them:

class Foo:
    def __exit__[T: BaseException](
        self, exc_type: type[T] | None, exc: T | None, tb: TracebackType | None, /
    ) -> bool: ...
# PYI036: The first argument in `__exit__` should be annotated with `object` or `type[BaseException] | None`
# PYI036: The second argument in `__exit__` should be annotated with `object` or `BaseException | None`

The validators is_base_exception_type and the second-arg check only matched type[BaseException] and BaseException literally. The fix passes the function's PEP 695 type params into the validators so type[T] and T are accepted when T is a type parameter whose bound is BaseException.

Type parameters with no bound (or a bound other than BaseException) continue to be flagged as before.

Test Plan

Snapshot tests (cargo nextest run and cargo insta test).

…ods (`PYI036`)

Fixes astral-sh#25905.

When `__exit__` uses a PEP 695 type parameter bound to `BaseException`
(e.g. `def __exit__[T: BaseException](...)`), annotations like `type[T] | None`
and `T | None` are valid but PYI036 incorrectly flags them as bad.

The rule's validators only matched `type[BaseException]` and `BaseException`
literally. The fix passes the function's type params into the validators so
they can recognise `type[T]` and `T` when `T` is a type param whose bound is
`BaseException`.

Type params with no bound (or a bound other than `BaseException`) continue to
be flagged as before.
@astral-sh-bot astral-sh-bot Bot requested a review from ntBre June 25, 2026 16:59
@kpeis695

Copy link
Copy Markdown
Author

Sorry about that. The previous PR had unrelated commits because I branched off my other fix instead of main. Reopened from a clean branch, this one only has the PYI036 changes.

@ntBre ntBre marked this pull request as draft June 25, 2026 18:23
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.

bad-exit-annotation (PYI036) - false positive when using a generic for the exception type

1 participant