Skip to content

False positive E0601: used-before-assignment in try and while block #9689

Open
@jc-stu

Description

@jc-stu

Bug description

It seems pylint can't process nonlocal statement in try and while block correctly, but no problem in for block.

# pylint: disable=missing-docstring, bare-except

def outer():
    a = 1
    def inner_try():
        try:
            nonlocal a
            print(a)  # E0601
            a = 2
            print(a)
        except:
            pass
    def inner_while():
        i = 0
        while i < 2:
            i += 1
            nonlocal a
            print(a)  # E0601
            a = 2
            print(a)
    def inner_for():
        for _ in range(2):
            nonlocal a
            print(a)  # correct
            a = 2
            print(a)
    inner_try()
    inner_while()
    inner_for()
outer()

Command used

pylint e0601.py

Pylint output

************* Module e0601
e0601.py:8:18: E0601: Using variable 'a' before assignment (used-before-assignment)
e0601.py:18:18: E0601: Using variable 'a' before assignment (used-before-assignment)

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

Expected behavior

There should be no errors.

Pylint version

pylint 3.2.2
astroid 3.2.2
Python 3.12.3 (tags/v3.12.3:f6650f9, Apr  9 2024, 14:05:25) [MSC v.1938 64 bit (AMD64)]

OS / Environment

Windows 10 LTSC 2019
Version 1809 (OS Build 17763.5830)

Metadata

Metadata

Assignees

No one assigned

    Labels

    C: used-before-assignmentIssues related to 'used-before-assignment' checkFalse Positive 🦟A message is emitted but nothing is wrong with the codeNeeds PRThis issue is accepted, sufficiently specified and now needs an implementation

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions