pylint icon indicating copy to clipboard operation
pylint copied to clipboard

False positive `undefined-loop-variable` in function signature when the typing match a variable name

Open Pierre-Sassoulas opened this issue 3 years ago • 4 comments

Bug description

Consider the following file a.py

from typing import List


def parse_dict(dict_object: List[dict], name: str) -> dict:
    for dict in dict_object:
        if dict.get("name") == name:
            return dict
    return {}

Command used

pylint a.py

Pylint output

************* Module a
a.py:4:33: W0631: Using possibly undefined loop variable 'dict' (undefined-loop-variable)
a.py:4:54: W0631: Using possibly undefined loop variable 'dict' (undefined-loop-variable)

Expected behavior

No warning.

Pylint version

pylint 2.12.2
astroid 2.9.0
Python 3.8.10 (default, Sep 28 2021, 16:10:42) 
[GCC 9.3.0]

Pierre-Sassoulas avatar Dec 06 '21 11:12 Pierre-Sassoulas

Interesting, the issue only occurs with dict as variable name, not for example d.

cdce8p avatar Dec 06 '21 21:12 cdce8p

It also disappears if we do this:

- def parse_dict(dict_object: List[dict], name: str) -> dict:
+ def parse_dict(dict_object: List[Dict], name: str) -> Dict:

Pierre-Sassoulas avatar Dec 06 '21 21:12 Pierre-Sassoulas

I meant this here:

from typing import List

def parse_dict(dict_object: List[dict], name: str) -> dict:
    for d in dict_object:  # iterator key is 'd' not 'dict'
        if d.get("name") == name:
            return d
    return {}

cdce8p avatar Dec 06 '21 21:12 cdce8p

I think it's "the same name than the typing":

from typing import List

d = list

def parse_dict(dict_object: List[d], name: str) -> d:
    for d in dict_object:
        if d.get("name") == name:
            return d
    return {}

(Strangely the second error is raised twice ?)

************* Module a
a.py:6:8: W0621: Redefining name 'd' from outer scope (line 3) (redefined-outer-name)
a.py:5:33: W0631: Using possibly undefined loop variable 'd' (undefined-loop-variable)
a.py:5:51: W0631: Using possibly undefined loop variable 'd' (undefined-loop-variable)
a.py:5:51: W0631: Using possibly undefined loop variable 'd' (undefined-loop-variable)

------------------------------------------------------------------
Your code has been rated at 4.29/10 (previous run: 4.29/10, +0.00)

Pierre-Sassoulas avatar Dec 06 '21 22:12 Pierre-Sassoulas