Skip to content

Commit 53cfee2

Browse files
committed
fix: don't suggest Foo[...] when Foo(arg=...) is used
When a function call with keyword arguments appears in a type annotation (e.g. `Foo(sort=True)`), mypy was suggesting to use `Foo[...]` instead. This suggestion is misleading because `Foo[sort=True]` is a syntax error -- the user likely intended a function call, not a type parameterization. Now, when keyword arguments are present, mypy shows "Cannot use a function call in a type annotation" instead. The `Foo[...]` suggestion is preserved for calls with only positional arguments (e.g. `Foo(int)`) where the user likely meant `Foo[int]`. Fixes #16506
1 parent a475a9a commit 53cfee2

2 files changed

Lines changed: 15 additions & 1 deletion

File tree

mypy/fastparse.py

Lines changed: 4 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1958,7 +1958,10 @@ def visit_Call(self, e: Call) -> Type:
19581958
if not isinstance(self.parent(), ast3.List):
19591959
note = None
19601960
if constructor:
1961-
note = "Suggestion: use {0}[...] instead of {0}(...)".format(constructor)
1961+
if e.keywords:
1962+
note = "Cannot use a function call in a type annotation"
1963+
else:
1964+
note = "Suggestion: use {0}[...] instead of {0}(...)".format(constructor)
19621965
return self.invalid_type(e, note=note)
19631966
if not constructor:
19641967
self.fail(message_registry.ARG_CONSTRUCTOR_NAME_EXPECTED, e.lineno, e.col_offset)

test-data/unit/check-fastparse.test

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,17 @@ def f(a: Foo(int)) -> int:
207207
main:7: error: Invalid type comment or annotation
208208
main:7: note: Suggestion: use Foo[...] instead of Foo(...)
209209

210+
[case testFasterParseCallWithKeywordArgs_no_native_parse]
211+
212+
def Foo(sort: bool) -> type:
213+
return int
214+
215+
def f(a: Foo(sort=True)) -> int:
216+
pass
217+
[out]
218+
main:5: error: Invalid type comment or annotation
219+
main:5: note: Cannot use a function call in a type annotation
220+
210221
[case testFastParseMatMul]
211222

212223
from typing import Any

0 commit comments

Comments
 (0)