Skip to content

Fix reachability for generic context managers with bool __exit__ - #11488

Merged
Rich Chiodo (rchiodo) merged 2 commits into
microsoft:mainfrom
KirtiRamchandani:fix/generic-context-manager-exit-type-11483
Jun 24, 2026
Merged

Rich Chiodo (rchiodo) merged 2 commits into
microsoft:mainfrom
KirtiRamchandani:fix/generic-context-manager-exit-type-11483

Conversation

@KirtiRamchandani

Copy link
Copy Markdown
Contributor

Fixes #11483

isExceptionContextManager only treated __exit__ as swallowing exceptions when the declared return type was literally bool. For ContextManager[bool], the declared return is the TypeVar T.

Specialize the return type from the context manager instance type args before the bool check. Added with7.py regression sample.

Specialize __exit__ return TypeVars from the context manager instance
type arguments so ContextManager[bool] is treated as swallowing exceptions.

Fixes microsoft#11483
}
}

// Generic context managers (e.g. ContextManager[bool]) declare __exit__ as returning

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
Positional typeArgs[0] is the wrong type argument for any context manager whose __exit__ TypeVar isn't the class's first type parameter. All three reviewers tool-verified this: AbstractContextManager(Protocol[_T_co, _ExitT_co]) puts the __enter__ type at slot 0 and the __exit__ type at slot 1. Concretely, CM[bool, int] with def __exit__(...) -> T (T at slot 1, actual return int) is read as typeArgs[0] = bool → cmSwallowsExceptions = true, a regression: pre-PR this correctly returned false. Conversely CM[int, bool] reads slot 0 = int and fails to fix the bug. Replace with identity-aware specialization: returnType = partiallySpecializeType(returnType, cmType, /* typeClassType */ undefined); (typeUtils.ts:1496). This resolves the TypeVar by identity regardless of slot, handles multi-param, inherited-base, and async cases uniformly, and lets you drop the isTypeVar / typeArgs.length guards entirely.

[verified]

}
}

// Generic context managers (e.g. ContextManager[bool]) declare __exit__ as returning

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
The PR's titled scenario typing.ContextManager[bool] only passes by coincidence. Tool-verified: typing.ContextManager[_T_co] subclasses AbstractContextManager[_T_co, bool | None], so its real __exit__ return is the union bool | None, while typeArgs[0] reads the enter type bool. typing.ContextManager[int] (enter int, exit still bool | None) would regress to not-swallowing. Fixing the slot via partiallySpecializeType addresses this, but note the downstream isClassInstance(returnType) && ClassType.isBuiltIn(returnType, 'bool') check (line ~1985) still won't recognize bool inside a bool | None union — consider widening it to treat a union as swallowing if any subtype is a non-False-literal bool.

[verified]

}
}

// Generic context managers (e.g. ContextManager[bool]) declare __exit__ as returning

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
The new block executes after the __aexit__ Coroutine unwrap, so async generic managers (async with CM[bool, int]() where __aexit__ -> Coroutine[Any, Any, T]) hit the same positional mismapping and the same reachability corruption. The PR neither addresses the async case correctly nor tests it. The partiallySpecializeType fix above covers sync and async uniformly.

[verified]

}
}

// Generic context managers (e.g. ContextManager[bool]) declare __exit__ as returning

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
Root-cause note (all reviewers): the fix targets the right layer — specializing the __exit__ return before the bool check rather than guarding reachability downstream — but uses the wrong mechanism. The underlying cause is reading the unspecialized exitType.shared.declaredReturnType and then re-deriving the substitution by hand with an index, reaching around the type system's existing identity-based specialization. This is 'right place, wrong tool,' which the recommended partiallySpecializeType call resolves at the origin.

[verified]


T = TypeVar("T", bound="bool|None")


Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Copilot generated:
The sample only exercises the single-type-parameter shape (class ContextManager(Generic[T]) with __exit__ -> T at slot 0) — the one case the positional shortcut happens to get right, so the suite stays green even though the implementation is wrong. Add cases that actually constrain the fix: (1) a two-typevar manager where __exit__ returns the second TypeVar (e.g. CM[bool, int] returning the slot-1 type — the regression direction), (2) the named typing.ContextManager[...] case, (3) an inherited generic __exit__ (TypeVar scoped to a base class in the MRO), and (4) an async with variant.

[verified]

// a TypeVar. Specialize using the instance type args before checking for bool.
if (isTypeVar(returnType) && cmType.priv.typeArgs && cmType.priv.typeArgs.length >= 1) {
returnType = cmType.priv.typeArgs[0];
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Using cmType.priv.typeArgs[0] assumes the __exit__ return TypeVar is always the class's first type parameter. That isn't generally true. The stdlib type this PR is modeled on, contextlib.AbstractContextManager(Protocol[_T_co, _ExitT_co]), declares __exit__ -> _ExitT_co (the second parameter), so this picks the wrong arg. It also creates a new false positive: for class CM(Generic[A, B]): def __exit__(...) -> B, CM[bool, None]() actually returns None from __exit__, but this grabs typeArgs[0] == bool and wrongly marks the manager as swallowing exceptions, corrupting reachability/narrowing. Prefer resolving the declared TypeVar to its specialized return type (e.g. via the class's type-var context / effective return type) rather than assuming index 0.

// a TypeVar. Specialize using the instance type args before checking for bool.
if (isTypeVar(returnType) && cmType.priv.typeArgs && cmType.priv.typeArgs.length >= 1) {
returnType = cmType.priv.typeArgs[0];
}

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Note that typing.ContextManager[bool] expands to AbstractContextManager[bool, bool | None], where _ExitT_co defaults to bool | None. So __exit__'s return resolves to the union bool | None, not a bare TypeVar. isTypeVar(returnType) is then false, this block is skipped, and the downstream isClassInstance(returnType, 'bool') check fails on the union, meaning the actual stdlib case named in the sample may remain unfixed. Consider adding a test against contextlib.AbstractContextManager and handling a bool | None union in the bool check.

with ContextManager[bool]() as ctx:
reveal_type(ctx.__exit__(None, None, None), expected_text="bool")
foo = 1
reveal_type(foo, expected_text="Literal['str', 1]")

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This sample only covers a single-TypeVar generic where typeArgs[0] coincides with the exit TypeVar, which is the one shape the current fix gets right. Add a multi-TypeVar regression case (e.g. class CM(Generic[A, B]) with __exit__ -> B, instantiated as CM[None, bool] and as CM[bool, None]) asserting the correct swallow / no-swallow reachability behavior. This documents intent and guards against the positional-index pitfall.

@rchiodo

Copy link
Copy Markdown
Collaborator

The core fix idea is right, but resolving the exit return type by grabbing typeArgs[0] is positionally fragile. Resolve the TypeVar to its actual specialized return type instead, and add a multi-TypeVar regression test to lock the behavior in.

@rchiodo Rich Chiodo (rchiodo) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

@rchiodo Rich Chiodo (rchiodo) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

@rchiodo Rich Chiodo (rchiodo) left a comment

Copy link
Copy Markdown
Collaborator

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Approved via Review Center.

@github-actions

Copy link
Copy Markdown
Contributor

Diff from mypy_primer, showing the effect of this PR on open source code:

sympy (https://github.com/sympy/sympy)
-   .../projects/sympy/sympy/stats/drv.py:269:22 - error: Argument of type "Generator[tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | int | None, None, None]" cannot be assigned to parameter "iterable" of type "Iterable[_SupportsSumNoDefaultT@sum]" in function "sum"
+   .../projects/sympy/sympy/stats/drv.py:269:22 - error: Argument of type "Generator[tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic | int | None, None, None]" cannot be assigned to parameter "iterable" of type "Iterable[_SupportsSumNoDefaultT@sum]" in function "sum"
-     "Generator[tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | int | None, None, None]" is not assignable to "Iterable[_SupportsSumNoDefaultT@sum]"
+     "Generator[tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic | int | None, None, None]" is not assignable to "Iterable[_SupportsSumNoDefaultT@sum]"
-       Type parameter "_T_co@Iterable" is covariant, but "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | int | None" is not a subtype of "_SupportsSumNoDefaultT@sum"
+       Type parameter "_T_co@Iterable" is covariant, but "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic | int | None" is not a subtype of "_SupportsSumNoDefaultT@sum"
-         Type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | int | None" is not assignable to type "_SupportsSumWithNoDefaultGiven"
+         Type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic | int | None" is not assignable to type "_SupportsSumWithNoDefaultGiven"
-           Type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | int | None" is not assignable to type "_SupportsSumWithNoDefaultGiven"
+           Type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic | int | None" is not assignable to type "_SupportsSumWithNoDefaultGiven"
-   .../projects/sympy/sympy/stats/drv_types.py:293:16 - error: Operator "*" not supported for types "Expr" and "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic"
+   .../projects/sympy/sympy/stats/drv_types.py:293:16 - error: Operator "*" not supported for types "Expr" and "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic"
-   .../projects/sympy/sympy/stats/rv.py:473:25 - error: Argument of type "Expr | Lambda | Zero | One | Integral | Unknown | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | Add | NaN | Piecewise | Basic | NegativeOne | Integer | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | int" cannot be assigned to parameter "args" of type "Expr | complex" in function "__new__"
+   .../projects/sympy/sympy/stats/rv.py:473:25 - error: Argument of type "Expr | Lambda | Zero | One | Integral | Unknown | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | NaN | Piecewise | Basic | NegativeOne | Integer | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | int" cannot be assigned to parameter "args" of type "Expr | complex" in function "__new__"
-     Type "Expr | Lambda | Zero | One | Integral | Unknown | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | Add | NaN | Piecewise | Basic | NegativeOne | Integer | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | int" is not assignable to type "Expr | complex"
+     Type "Expr | Lambda | Zero | One | Integral | Unknown | Probability | tuple[Unknown, ...] | Sum | ZeroMatrix | NaN | Piecewise | Basic | NegativeOne | Integer | ComplexInfinity | Rational | Infinity | NegativeInfinity | Float | Number | int" is not assignable to type "Expr | complex"
-   .../projects/sympy/sympy/stats/stochastic_process_types.py:1839:25 - error: Argument of type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | Integral | Any | int" cannot be assigned to parameter "args" of type "Expr | complex" in function "__new__"
+   .../projects/sympy/sympy/stats/stochastic_process_types.py:1839:25 - error: Argument of type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic | Integral | Any | int" cannot be assigned to parameter "args" of type "Expr | complex" in function "__new__"
-     Type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Add | Zero | NaN | Piecewise | Basic | Integral | Any | int" is not assignable to type "Expr | complex"
+     Type "tuple[Unknown, ...] | Unknown | Sum | Expr | ZeroMatrix | Zero | NaN | Piecewise | Basic | Integral | Any | int" is not assignable to type "Expr | complex"
-     Return type mismatch: base method returns type "Self@Basic", override returns type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | Self@Expectation | Literal[0]"
+     Return type mismatch: base method returns type "Self@Basic", override returns type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | Self@Expectation | Literal[0]"
-       Type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | Expectation* | Literal[0]" is not assignable to type "Basic"
+       Type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | Expectation* | Literal[0]" is not assignable to type "Basic"
-     Return type mismatch: base method returns type "Basic", override returns type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | Literal[0]"
+     Return type mismatch: base method returns type "Basic", override returns type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | Literal[0]"
-       Type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | Literal[0]" is not assignable to type "Basic"
+       Type "Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | Literal[0]" is not assignable to type "Basic"
-   .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:367:12 - error: Operator "-" not supported for types "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" and "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]"
+   .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:367:12 - error: Operator "-" not supported for types "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" and "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]"
-   .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:415:21 - error: Argument of type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" cannot be assigned to parameter "expr" of type "Basic" in function "simplify"
+   .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:415:21 - error: Argument of type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" cannot be assigned to parameter "expr" of type "Basic" in function "simplify"
-     Type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" is not assignable to type "Basic"
+     Type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" is not assignable to type "Basic"
-   .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1005:21 - error: Argument of type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" cannot be assigned to parameter "expr" of type "Basic" in function "simplify"
+   .../projects/sympy/sympy/stats/tests/test_continuous_rv.py:1005:21 - error: Argument of type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" cannot be assigned to parameter "expr" of type "Basic" in function "simplify"
-     Type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Add | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" is not assignable to type "Basic"
+     Type "RandomSymbol | Basic | Expectation | Expr | tuple[Unknown, ...] | Unknown | Sum | ZeroMatrix | Zero | NaN | Piecewise | Integral | Any | ExpectationMatrix | Literal[0]" is not assignable to type "Basic"

... (truncated 90 lines) ...

@rchiodo
Rich Chiodo (rchiodo) merged commit 4ba562b into microsoft:main Jun 24, 2026
16 checks passed
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.

Incorrect type inference from context manager __exit__ return type with Generic

2 participants