Skip to content

Commit

Permalink
Suggest PEP 604 annotation when on Python 3.10
Browse files Browse the repository at this point in the history
Code running on Python 3.10 can use PEP 604 annotations, so suggest
those instead.
  • Loading branch information
pranavrajpal committed May 20, 2022
1 parent 0e137b4 commit ed2037b
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
6 changes: 5 additions & 1 deletion mypy/messages.py
Original file line number Diff line number Diff line change
Expand Up @@ -1193,14 +1193,18 @@ def need_annotation_for_var(self, node: SymbolNode, context: Context,
python_version: Optional[Tuple[int, int]] = None) -> None:
hint = ''
has_variable_annotations = not python_version or python_version >= (3, 6)
pep604_supported = python_version and python_version >= (3, 10)
# type to recommend the user adds
recommended_type = None
# Only gives hint if it's a variable declaration and the partial type is a builtin type
if python_version and isinstance(node, Var) and isinstance(node.type, PartialType):
type_dec = '<type>'
if not node.type.type:
# partial None
recommended_type = f'Optional[{type_dec}]'
if pep604_supported:
recommended_type = f'{type_dec} | None'
else:
recommended_type = f'Optional[{type_dec}]'
elif node.type.type.fullname in reverse_builtin_aliases:
# partial types other than partial None
alias = reverse_builtin_aliases[node.type.type.fullname]
Expand Down
4 changes: 4 additions & 0 deletions test-data/unit/check-inference.test
Original file line number Diff line number Diff line change
Expand Up @@ -3255,3 +3255,7 @@ reveal_type(x) # N: Revealed type is "builtins.bytes"
if x:
reveal_type(x) # N: Revealed type is "builtins.bytes"
[builtins fixtures/dict.pyi]

[case testSuggestPep604AnnotationForPartialNone]
# flags: --local-partial-types --python-version 3.10
x = None # E: Need type annotation for "x" (hint: "x: <type> | None = ...")

0 comments on commit ed2037b

Please sign in to comment.