Skip to content

Commit

Permalink
More robust typing literal handling
Browse files Browse the repository at this point in the history
Includes `typing.Literal` in the checks, adds a test case, and
wraps the call to `parse_expression` in a try/except just in case.

Fix #377

ghstack-source-id: 01775325c8aa7907568531ff47e60862e02d2915
Pull Request resolved: #400
  • Loading branch information
amyreese committed Oct 24, 2023
1 parent 79d2080 commit 21360fe
Showing 1 changed file with 19 additions and 2 deletions.
21 changes: 19 additions & 2 deletions src/fixit/rules/no_string_type_annotation.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,14 @@ def foo() -> typing.Optional[typing.Literal["a", "b"]]:
return "a"
"""
),
Valid(
"""
import typing
def foo() -> typing.Optional[typing.Literal["class", "function"]]:
return "class"
"""
),
]

INVALID = [
Expand Down Expand Up @@ -273,7 +281,12 @@ def visit_Subscript(self, node: cst.Subscript) -> None:
metadata=m.MatchMetadataIfTrue(
QualifiedNameProvider,
lambda qualnames: any(
n.name == "typing_extensions.Literal" for n in qualnames
n.name
in (
"typing.Literal",
"typing_extensions.Literal",
)
for n in qualnames
),
)
),
Expand All @@ -295,4 +308,8 @@ def visit_SimpleString(self, node: cst.SimpleString) -> None:
value = node.evaluated_value
if isinstance(value, bytes):
value = value.decode("utf-8")
self.report(node, replacement=cst.parse_expression(value))
try:
repl = cst.parse_expression(value)
self.report(node, replacement=repl)
except cst.ParserSyntaxError:
self.report(node)

0 comments on commit 21360fe

Please sign in to comment.