Skip to content

"if condition is always false [redundant-expr]" false positive when variable set in a loop after the conditional #14993

Closed
@james-johnston-thumbtack

Description

Bug Report

The redundant-expr gives a false positive if you conditionally read a variable for another conditional inside a loop.

To Reproduce

def mypytest() -> int | None:
    trigger_segment = None
    violations = None
    for segment in [1, 2]:
        if segment == 2:
            violations = trigger_segment if trigger_segment else segment
        trigger_segment = segment
    return violations

The rule will trigger with error: If condition is always false [redundant-expr] on the if trigger_segment part of the ternary.

Expected Behavior

Mypy should not report anything because clearly the if condition is not always false: running print(mypytest()) will print 1.

Actual Behavior

The rule will trigger with error: If condition is always false [redundant-expr] on the if trigger_segment part of the ternary.

Your Environment

My configuration:


[tool.mypy]
plugins = [
    "pydantic.mypy"
]
files = "src/**/*.py,tests/**/*.py"
strict = true
# These are additional checks not covered by strict:
disallow_any_unimported = true
enable_error_code = """\
    ignore-without-code,\
    truthy-bool,\
    truthy-iterable,\
    redundant-expr,\
    redundant-self,\
    unused-awaitable\
    """
warn_unreachable = true
mypy 1.1.1 (compiled: yes)
% python --version
Python 3.11.1

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrong

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions