Skip to content

False positive for E0601 when variable first assigned in assignment expression in if clause of a comprehension #9460

Open
@deFractal

Description

@deFractal

Bug description

Pylint flags a false positive for use of a variable before assignment if the variable is used in a list or tuple comprehension, or as the key or value in a dict comprehension, and that variable is first assigned with an assignment expression in the if clause of the same comprehension.

For example, I was using the following to explore the socket module when I stumbled on the issue:

from socket import getservbyport


def getservbyport_or_not(port: int, protocol='tcp') -> str | None:
    try:
        return getservbyport(port, protocol)
    except OSError:
        return None


known_services = [
    service for port in range(1, 49151) if
    (service := getservbyport_or_not(port))
]

print(known_services)

Configuration

No response

Command used

pylint scratch.py

Pylint output

scratch.py:12:10: E0601: Using variable 'service' before assignment (used-before-assignment)

Expected behavior

Pylint should look ahead to the if clause of the comprehension (if one exists), which occurs last in text but first in time, and check for an assignment expression there, before determining whether a variable is assigned before use.

Pylint version

Original versions:
pylint 2.17.4
astroid 2.15.5
Python 3.11.6 (tags/v3.11.6:8b6ee5b, Oct  2 2023, 14:57:12) [MSC v.1935 64 bit (AMD64)]

Current versions:
pylint 3.0.4
astroid 3.0.3
Python 3.12.1 (tags/v3.12.1:2305ca5, Dec  7 2023, 22:03:25) [MSC v.1937 64 bit (AMD64)]

OS / Environment

Occurs independently of OS (Windows/Linux/macOS), shell (Bash/PowerShell), and whether pylint is called used through an IDE or directly at the command line.

Additional dependencies

No response

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