Skip to content

Commit

Permalink
Prevent false positive undefined-variable for user-specified builti…
Browse files Browse the repository at this point in the history
…ns given type annotations (#6392)
  • Loading branch information
jacobtylerwalls authored and Pierre-Sassoulas committed Apr 20, 2022
1 parent 7231dd5 commit ddca4dd
Show file tree
Hide file tree
Showing 5 changed files with 35 additions and 2 deletions.
5 changes: 5 additions & 0 deletions ChangeLog
Expand Up @@ -31,6 +31,11 @@ Release date: TBA
Closes #5815
Closes #5406

* Fixed a false positive for ``unused-variable`` when a builtin specified in
``--additional-builtins`` is given a type annotation.

Closes #6388

* Fixed an ``AstroidError`` in 2.13.0 raised by the ``duplicate-code`` checker with
``ignore-imports`` or ``ignore-signatures`` enabled.

Expand Down
5 changes: 5 additions & 0 deletions doc/whatsnew/2.13.rst
Expand Up @@ -597,6 +597,11 @@ Other Changes

Closes #5394

* Fixed a false positive for ``unused-variable`` when a builtin specified in
``--additional-builtins`` is given a type annotation.

Closes #6388

* Fix false positive for 'nonexistent-operator' when repeated '-' are
separated (e.g. by parens).

Expand Down
10 changes: 8 additions & 2 deletions pylint/checkers/variables.py
Expand Up @@ -2062,12 +2062,18 @@ def _maybe_used_and_assigned_at_once(defstmt: nodes.Statement) -> bool:
or any(isinstance(arg, nodes.IfExp) for arg in value.args)
)

@staticmethod
def _is_only_type_assignment(node: nodes.Name, defstmt: nodes.Statement) -> bool:
def _is_only_type_assignment(
self, node: nodes.Name, defstmt: nodes.Statement
) -> bool:
"""Check if variable only gets assigned a type and never a value."""
if not isinstance(defstmt, nodes.AnnAssign) or defstmt.value:
return False

if node.name in self.linter.config.additional_builtins or utils.is_builtin(
node.name
):
return False

defstmt_frame = defstmt.frame(future=True)
node_frame = node.frame(future=True)

Expand Down
15 changes: 15 additions & 0 deletions tests/functional/u/undefined/undefined_variable_typing.py
Expand Up @@ -4,9 +4,24 @@
# Ensure attribute lookups in type comments are accounted for.
# Reported in https://github.com/PyCQA/pylint/issues/4603

from typing import TYPE_CHECKING, Any, Dict

import foo
from foo import Bar, Boo

a = ... # type: foo.Bar
b = ... # type: foo.Bar[Boo]
c = ... # type: Bar.Boo


if TYPE_CHECKING:
__additional_builtin__: Dict[str, Any]
# For why this would emit redefined-builtin: https://github.com/PyCQA/pylint/pull/3643
# pylint: disable-next=redefined-builtin
repr: Any


def run():
"""https://github.com/PyCQA/pylint/issues/6388"""
print(repr)
return __additional_builtin__["test"]
2 changes: 2 additions & 0 deletions tests/functional/u/undefined/undefined_variable_typing.rc
@@ -1,2 +1,4 @@
[testoptions]
except_implementations=PyPy
[VARIABLES]
additional-builtins=__additional_builtin__

0 comments on commit ddca4dd

Please sign in to comment.