-
Notifications
You must be signed in to change notification settings - Fork 1.8k
Fix #11483: Incorrect type inference from context manager __exit__ return type with Generic #11502
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
rchiodo
wants to merge
3
commits into
microsoft:main
Choose a base branch
from
rchiodo:fix11483
base: main
Could not load branches
Branch not found: {{ refName }}
Loading
Could not load tags
Nothing to show
Loading
Are you sure you want to change the base?
Some commits from the old base branch may be removed from the timeline,
and old review comments may become outdated.
+22
−0
Open
Changes from 2 commits
Commits
Show all changes
3 commits
Select commit
Hold shift + click to select a range
File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
49 changes: 49 additions & 0 deletions
49
.github/plans/archived/FIX_11483_CONTEXT_MANAGER_GENERIC_EXIT_PLAN.md
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,49 @@ | ||
| # Fix #11483 — Incorrect type inference from context manager `__exit__` return type with Generic | ||
| ## Status: ✅ Complete | ||
|
|
||
| Status: ✅ Complete (pending pipeline push/PR) | ||
|
|
||
| Issue: https://github.com/microsoft/pyright/issues/11483 | ||
|
|
||
| ## Problem | ||
|
|
||
| When a generic context manager annotates its `__exit__` (or `__aexit__`) return | ||
| type with a `TypeVar` (e.g. `class ContextManager(Generic[T])` whose `__exit__` | ||
| returns `T` with `T` bound to `bool | None`), pyright determines exception | ||
| suppression from the **unspecialized declared** return type instead of the | ||
| solved type argument. As a result `ContextManager[bool]` was treated as | ||
| non-suppressing, so code-flow narrowing after the `with` block was wrong | ||
| (`reveal_type(foo)` was `Literal[1]` instead of `Literal["str", 1]`). | ||
|
|
||
| ## Root cause (debugger-verified) | ||
|
|
||
| `isExceptionContextManager` in `packages/pyright-internal/src/analyzer/codeFlowEngine.ts` | ||
| read `exitType.shared.declaredReturnType`, which is the raw declared return type. | ||
|
|
||
| Debugger evidence at the `bool` case breakpoint: | ||
| - `exitType.shared.declaredReturnType.shared.name` = `"T"` (TypeVar — the bug) | ||
| - `exitType.priv.specializedTypes.returnType.shared.name` = `"bool"` (solved) | ||
|
|
||
| Because the declared type was the TypeVar `T`, the `ClassType.isBuiltIn(returnType, 'bool')` | ||
| check never matched and `cmSwallowsExceptions` stayed `false`. | ||
|
|
||
| ## Fix | ||
|
|
||
| Use `FunctionType.getEffectiveReturnType(exitType, /* includeInferred */ false)`, | ||
| which prefers `priv.specializedTypes.returnType` over `shared.declaredReturnType`. | ||
| This returns the specialized `bool` / `None` and covers both `__exit__` and | ||
| `__aexit__` (the async Coroutine-unwrapping logic is preserved). | ||
|
|
||
| ## Tests | ||
|
|
||
| - Sample: `packages/pyright-internal/src/tests/samples/with7.py` — generic sync | ||
| and async context managers specialized to `None` and `bool`, asserting the | ||
| narrowed type after the block via `assert_type`. | ||
| - Test case: `With7` in `packages/pyright-internal/src/tests/checker.test.ts`. | ||
|
|
||
| ## Validation | ||
|
|
||
| - Red → green: With7 failed before the fix (4 assert_type mismatches), passes after. | ||
| - Debugger confirmed declared=`T` vs specialized=`bool`/`None`. | ||
| - `checker.test` (72) and `typeEvaluator1-8` (1163) suites pass. | ||
| - Prettier, ESLint (legacy config), and `tsc --noEmit` clean. | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| Original file line number | Diff line number | Diff line change |
|---|---|---|
| @@ -0,0 +1,46 @@ | ||
| # This sample tests that the exception-swallowing behavior of a context | ||
| # manager is determined from the specialized __exit__ / __aexit__ return | ||
| # type when the context manager is generic and the return type is annotated | ||
| # with a TypeVar. | ||
|
|
||
| from typing import Generic, Literal, Self, TypeVar, assert_type | ||
|
|
||
| T = TypeVar("T", bound="bool | None") | ||
|
|
||
|
|
||
| class ContextManager(Generic[T]): | ||
| def __enter__(self) -> Self: ... | ||
| def __exit__(self, exc_type, exc_val, exc_tb) -> T: ... | ||
|
|
||
|
|
||
| # The __exit__ return type specializes to None, so the exception is never | ||
| # suppressed and the entire body must have run. | ||
| foo = "str" | ||
| with ContextManager[None]() as ctx: | ||
| foo = 1 | ||
| assert_type(foo, Literal[1]) | ||
|
|
||
|
|
||
| # The __exit__ return type specializes to bool, so the exception may have | ||
| # been suppressed and the body may not have run. | ||
| bar = "str" | ||
| with ContextManager[bool]() as ctx: | ||
| bar = 1 | ||
| assert_type(bar, Literal["str", 1]) | ||
|
|
||
|
|
||
| class AsyncContextManager(Generic[T]): | ||
| async def __aenter__(self) -> Self: ... | ||
| async def __aexit__(self, exc_type, exc_val, exc_tb) -> T: ... | ||
|
|
||
|
|
||
| async def func1() -> None: | ||
| baz = "str" | ||
| async with AsyncContextManager[None]() as ctx: | ||
| baz = 1 | ||
| assert_type(baz, Literal[1]) | ||
|
|
||
| qux = "str" | ||
| async with AsyncContextManager[bool]() as ctx: | ||
| qux = 1 | ||
| assert_type(qux, Literal["str", 1]) | ||
|
rchiodo marked this conversation as resolved.
Outdated
|
||
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.