From fc2117b65c42718e629c8fe3d7a8ea469aa33746 Mon Sep 17 00:00:00 2001 From: Amethyst Reese Date: Tue, 24 Oct 2023 12:25:49 -0700 Subject: [PATCH] More robust typing literal handling 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: https://github.com/Instagram/Fixit/pull/400 --- src/fixit/rules/no_string_type_annotation.py | 21 ++++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/fixit/rules/no_string_type_annotation.py b/src/fixit/rules/no_string_type_annotation.py index 2b931be5..721c4c00 100644 --- a/src/fixit/rules/no_string_type_annotation.py +++ b/src/fixit/rules/no_string_type_annotation.py @@ -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 = [ @@ -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 ), ) ), @@ -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)