Skip to content

possibly-used-before-assignment does not understand assert_never #9643

@efroemling

Description

@efroemling

Bug description

The new possibly-used-before-assignment checker does not seem to understand assert_never(), which is useful these days with type checkers for exhaustive conditional handling/etc.

"""Code for bad.py"""

from enum import Enum
from typing import assert_never

class MyEnum(Enum):
    """A lovely enum."""
    VAL1 = 1
    VAL2 = 2
    VAL3 = 3

# Pylint correctly gives 'possibly-used-before-assignment' for this.
def do_thing(val: MyEnum) -> None:
    """Do a thing."""
    if val is MyEnum.VAL1:
        note = 'got 1'
    elif val is MyEnum.VAL2:
        note = 'got 2'
    elif val is MyEnum.VAL3:
        note = 'got 3'

    print('Note:', note)

# Pylint understands this correction.
def do_thing_2(val: MyEnum) -> None:
    """Do a thing."""
    if val is MyEnum.VAL1:
        note = 'got 1'
    elif val is MyEnum.VAL2:
        note = 'got 2'
    elif val is MyEnum.VAL3:
        note = 'got 3'
    else:
        raise ValueError('Should never get here.')

    print('Note:', note)

# But not this one (which integrates better with type checkers).
def do_thing_3(val: MyEnum) -> None:
    """Do a thing."""
    if val is MyEnum.VAL1:
        note = 'got 1'
    elif val is MyEnum.VAL2:
        note = 'got 2'
    elif val is MyEnum.VAL3:
        note = 'got 3'
    else:
        assert_never(val)

    print('Note:', note)

Configuration

No response

Command used

pylint bad.py

Pylint output

bad.py:22:19: E0606: Possibly using variable 'note' before assignment (possibly-used-before-assignment)
bad.py:50:19: E0606: Possibly using variable 'note' before assignment (possibly-used-before-assignment)

Expected behavior

assert_never should prevent the error in do_thing_3, just as the exception does for do_thing_2

Pylint version

pylint 3.2.0
astroid 3.2.1
Python 3.12.3 (main, Apr  9 2024, 08:09:14) [Clang 15.0.0 (clang-1500.3.9.4)]

OS / Environment

macOS 14.5

Additional dependencies

No response

Metadata

Metadata

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

Relationships

None yet

Development

No branches or pull requests

Issue actions