Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Fix Literal parse error in RemoveImportsVisitor #1130

Merged
merged 1 commit into from
May 3, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
11 changes: 10 additions & 1 deletion libcst/codemod/visitors/_gather_string_annotation_names.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,11 @@ def visit_Annotation(self, node: cst.Annotation) -> bool:
def leave_Annotation(self, original_node: cst.Annotation) -> None:
self._annotation_stack.pop()

def visit_Subscript(self, node: cst.Subscript) -> bool:
qnames = self.get_metadata(QualifiedNameProvider, node)
# A Literal["foo"] should not be interpreted as a use of the symbol "foo".
return not any(qn.name == "typing.Literal" for qn in qnames)

def visit_Call(self, node: cst.Call) -> bool:
qnames = self.get_metadata(QualifiedNameProvider, node)
if any(qn.name in self._typing_functions for qn in qnames):
Expand Down Expand Up @@ -71,7 +76,11 @@ def handle_any_string(
value = node.evaluated_value
if value is None:
return
mod = cst.parse_module(value)
try:
mod = cst.parse_module(value)
except cst.ParserSyntaxError:
# Not all strings inside a type annotation are meant to be valid Python code.
return
extracted_nodes = m.extractall(
mod,
m.Name(
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -80,3 +80,14 @@ def test_dotted_names(self) -> None:
visitor.names,
{"api", "api.http_exceptions", "api.http_exceptions.HttpException"},
)

def test_literals(self) -> None:
visitor = self.gather_names(
"""
from typing import Literal
a: Literal["in"]
b: list[Literal["1x"]]
c: Literal["Any"]
"""
)
self.assertEqual(visitor.names, set())
Loading