Skip to content

Commit

Permalink
Don't emit 'unused-variable' or 'unused-import' on names in string li…
Browse files Browse the repository at this point in the history
…teral type annotations (pylint-dev#3299)
  • Loading branch information
lggruspe committed Sep 2, 2022
1 parent 880095c commit 89351a5
Show file tree
Hide file tree
Showing 2 changed files with 39 additions and 0 deletions.
18 changes: 18 additions & 0 deletions pylint/checkers/variables.py
Original file line number Diff line number Diff line change
Expand Up @@ -2341,6 +2341,10 @@ def _check_is_unused(
if name in comprehension_target_names:
return

# Ignore names in string literal type annotation.
if name in self._type_annotation_names:
return

argnames = node.argnames()
# Care about functions with unknown argument (builtins)
if name in argnames:
Expand Down Expand Up @@ -2904,6 +2908,20 @@ def _check_potential_index_error(
)
return

@utils.only_required_for_messages(
"unused-import",
"unused-variable",
)
def visit_const(self, node: nodes.Const) -> None:
"""Take note of names that appear inside string literal type annotations."""
if node.pytype() != "builtins.str":
return
if not utils.is_node_in_type_annotation_context(node):
return
if not node.value.isidentifier():
return
self._type_annotation_names.append(node.value)


def register(linter: PyLinter) -> None:
linter.register_checker(VariablesChecker(linter))
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
"""Test if pylint sees names inside string literal type annotations. #3299"""
from argparse import ArgumentParser, Namespace
from pathlib import Path
from typing import TypeAlias

def unused_variable_should_not_be_emitted():
"""unused-variable shouldn't be emitted for Example1."""
Example1: TypeAlias = int
result: set["Example1"] = set()
return result

# unused-import shouldn't be emitted for Path
example2: set["Path"] = set()

def example3(_: "ArgumentParser"):
"""unused-import shouldn't be emitted for ArgumentParser"""

# pylint: disable=too-few-public-methods
class Class:
"""unused-import shouldn't be emitted for Namespace"""
cls: "Namespace"

0 comments on commit 89351a5

Please sign in to comment.