Skip to content

Commit 620a0e4

Browse files
committed
fix(mypy): prevent incorrect type inference for awaited function calls
- Modify ExpressionChecker to handle async function calls differently - Don't propagate expected type for awaited function calls to avoid incorrect inference - Add test cases to verify correct type inference for awaited function calls
1 parent 116b92b commit 620a0e4

File tree

2 files changed

+32
-1
lines changed

2 files changed

+32
-1
lines changed

mypy/checkexpr.py

Lines changed: 10 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -6181,7 +6181,16 @@ def visit_await_expr(self, e: AwaitExpr, allow_none_return: bool = False) -> Typ
61816181
expected_type = self.type_context[-1]
61826182
if expected_type is not None:
61836183
expected_type = self.chk.named_generic_type("typing.Awaitable", [expected_type])
6184-
actual_type = get_proper_type(self.accept(e.expr, expected_type))
6184+
6185+
# For async function calls, don't propagate the expected type to avoid
6186+
# incorrect type inference affecting argument types
6187+
if isinstance(e.expr, CallExpr):
6188+
# Don't use expected type for function calls inside await to prevent
6189+
# incorrect constraint inference affecting argument types
6190+
actual_type = get_proper_type(self.accept(e.expr, None))
6191+
else:
6192+
actual_type = get_proper_type(self.accept(e.expr, expected_type))
6193+
61856194
if isinstance(actual_type, AnyType):
61866195
return AnyType(TypeOfAny.from_another_any, source_any=actual_type)
61876196
ret = self.check_awaitable_expr(

test-data/unit/check-async-await.test

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1080,3 +1080,25 @@ class Launcher(P):
10801080

10811081
[builtins fixtures/async_await.pyi]
10821082
[typing fixtures/typing-async.pyi]
1083+
1084+
[case testAwaitCallExprTypeInference]
1085+
async def func(x: int) -> str:
1086+
return str(x)
1087+
1088+
async def test_await() -> str:
1089+
# This should not cause incorrect type inference for the argument
1090+
result = await func(42)
1091+
return result
1092+
1093+
# Test that the expected type doesn't propagate incorrectly to call arguments
1094+
async def test_nested_await() -> str:
1095+
def inner() -> int:
1096+
return 123
1097+
1098+
# The await should not affect type inference of inner function call
1099+
value = inner()
1100+
result = await func(value)
1101+
return result
1102+
1103+
[builtins fixtures/async_await.pyi]
1104+
[typing fixtures/typing-async.pyi]

0 commit comments

Comments
 (0)