pylint-dev / pylint

It's not just a linter that annoys you!
https://pylint.readthedocs.io/en/latest/
GNU General Public License v2.0
5.32k stars 1.14k forks source link

False negative used-before-assignment when the variable is used again in try/except #9941

Open octaviancorlade opened 1 month ago

octaviancorlade commented 1 month ago

Bug description

This is highlighted as expected

import requests

try:
    response = requests.get("https://google.com", timeout=1)
except Exception:
    print(response) # correctly raises used-before-assignment

This is not

import requests

try:
    response = requests.get("https://google.com", timeout=1) 
    response2 = response
except Exception:
    print(response) # should still raise used-before-assignment

Command used

pylint script1.py

Pylint output

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

Expected behavior

************* Module script1
script1.py:8:10: E0601: Using variable 'response' before assignment (used-before-assignment)

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

Pylint version

pylint 3.3.0
astroid 3.3.3
Python 3.12.2 (main, Feb  6 2024, 20:19:44) [Clang 15.0.0 (clang-1500.1.0.2.5)]

Additional dependencies

requests==2.32.3
pylint==3.3.0
nickdrozd commented 1 month ago

The name consumption logic is a little wonky. If the variable which would be undefined in the except block is used at all in the try block, the warning is not raised.

A self-contained example:

try:
    x = 1 / 0
except ZeroDivisionError:
    print(x)  # triggers used-before-assignment

try:
    y = 1 / 0
    print(y)
except ZeroDivisionError:
    print(y)  # no warning -- false negative