Skip to content

Commit c469567

Browse files
committed
Suggest PEP 604 annotation when on Python 3.10
Code running on Python 3.10 can use PEP 604 annotations, so suggest those instead.
1 parent 6c91b91 commit c469567

File tree

2 files changed

+9
-1
lines changed

2 files changed

+9
-1
lines changed

mypy/messages.py

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1193,14 +1193,18 @@ def need_annotation_for_var(self, node: SymbolNode, context: Context,
11931193
python_version: Optional[Tuple[int, int]] = None) -> None:
11941194
hint = ''
11951195
has_variable_annotations = not python_version or python_version >= (3, 6)
1196+
pep604_supported = python_version and python_version >= (3, 10)
11961197
# type to recommend the user adds
11971198
recommended_type = None
11981199
# Only gives hint if it's a variable declaration and the partial type is a builtin type
11991200
if python_version and isinstance(node, Var) and isinstance(node.type, PartialType):
12001201
type_dec = '<type>'
12011202
if not node.type.type:
12021203
# partial None
1203-
recommended_type = f'Optional[{type_dec}]'
1204+
if pep604_supported:
1205+
recommended_type = f'{type_dec} | None'
1206+
else:
1207+
recommended_type = f'Optional[{type_dec}]'
12041208
elif node.type.type.fullname in reverse_builtin_aliases:
12051209
# partial types other than partial None
12061210
alias = reverse_builtin_aliases[node.type.type.fullname]

test-data/unit/check-inference.test

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3255,3 +3255,7 @@ reveal_type(x) # N: Revealed type is "builtins.bytes"
32553255
if x:
32563256
reveal_type(x) # N: Revealed type is "builtins.bytes"
32573257
[builtins fixtures/dict.pyi]
3258+
3259+
[case testSuggestPep604AnnotationForPartialNone]
3260+
# flags: --local-partial-types --python-version 3.10
3261+
x = None # E: Need type annotation for "x" (hint: "x: <type> | None = ...")

0 commit comments

Comments
 (0)