Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Closed
james-johnston-thumbtack opened this issue Apr 1, 2023 · 2 comments
Labels
bug mypy got something wrong

Comments

@james-johnston-thumbtack

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
@Anexen
Copy link

Anexen commented Sep 4, 2023

I suppose that trigger_segment has inferred type None. You could try the following workaround:

trigger_segment: int | None = None

@hauntsaninja
Copy link
Collaborator

Fixed by #18433

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
bug mypy got something wrong
Projects
None yet
Development

No branches or pull requests

3 participants