Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Commit 87f1588

Browse files
Chessing234claude
andcommitted
Suppress misleading Foo[...] suggestion when annotation has keyword args
When a call expression with keyword arguments is used in a type annotation (e.g., `Foo(arg=val)`), mypy previously suggested using `Foo[...]` instead. However, `Foo[arg=val]` is a SyntaxError in Python, making the suggestion misleading. This change suppresses the bracket syntax suggestion when the call contains keyword arguments. Fixes #16506 Co-Authored-By: Claude Opus 4.6 (1M context) <[email protected]>
1 parent a7bdffd commit 87f1588

3 files changed

Lines changed: 20 additions & 1 deletion

File tree

mypy/fastparse.py

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1957,7 +1957,9 @@ def visit_Call(self, e: Call) -> Type:
19571957

19581958
if not isinstance(self.parent(), ast3.List):
19591959
note = None
1960-
if constructor:
1960+
if constructor and not e.keywords:
1961+
# Only suggest Foo[...] when there are no keyword arguments,
1962+
# since Foo[arg=val] is a SyntaxError (see #16506).
19611963
note = "Suggestion: use {0}[...] instead of {0}(...)".format(constructor)
19621964
return self.invalid_type(e, note=note)
19631965
if not constructor:

test-data/unit/check-errorcodes.test

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -122,6 +122,11 @@ for v in x: # type: int, int # E: Syntax error in type annotation [syntax] \
122122
# N: Suggestion: Use Tuple[T1, ..., Tn] instead of (T1, ..., Tn)
123123
pass
124124

125+
[case testErrorCodeSyntaxError4_no_native_parse]
126+
# Keyword arguments in type annotation should not suggest Foo[...] (see #16506)
127+
def f(a: Foo(arg=int)) -> int: # E: Invalid type comment or annotation [valid-type]
128+
pass
129+
125130
[case testErrorCodeSyntaxErrorIgnoreNote]
126131
# This is a bit inconsistent -- syntax error would be more logical?
127132
x: 'a b' # type: ignore[valid-type]

test-data/unit/check-fastparse.test

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -207,6 +207,18 @@ 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 testFasterParseTypeErrorCustomWithKeyword_no_native_parse]
211+
212+
from typing import TypeVar, Generic
213+
T = TypeVar('T')
214+
class Foo(Generic[T]):
215+
pass
216+
217+
def f(a: Foo(arg=int)) -> int:
218+
pass
219+
[out]
220+
main:7: error: Invalid type comment or annotation
221+
210222
[case testFastParseMatMul]
211223

212224
from typing import Any

0 commit comments

Comments
 (0)