Skip to content

Type narrowing with if None not in Sequence[Any | None] not working as expected #15001

Closed as not planned
@sebdivinity

Description

@sebdivinity

Bug Report

I expected that I could easily narrow multiple variables at once by using None not in Sequence[Any | None]. However mypy does not infer that. Nevertheless, after this condition it's impossible that variables have type None.

To Reproduce

def test(a: int|None, b: int|None) -> int:
    if None not in [a, b]:
        reveal_type(a)
        reveal_type(b)
        return a+b
    elif b is None:
        return a
    elif a is None:
        return b
    else:
        return 0

https://mypy-play.net/?mypy=latest&python=3.11&gist=40a2a733aa93c342e4ce013382949229

Expected Behavior

main.py:3: note: Revealed type is "builtins.int"
main.py:4: note: Revealed type is "builtins.int"

Actual Behavior

main.py:3: note: Revealed type is "Union[builtins.int, None]"
main.py:4: note: Revealed type is "Union[builtins.int, None]"
main.py:5: error: Unsupported operand types for + ("int" and "None") [operator]
main.py:5: error: Unsupported operand types for + ("None" and "int") [operator]
main.py:5: error: Unsupported left operand type for + ("None") [operator]
main.py:5: note: Both left and right operands are unions
main.py:7: error: Incompatible return value type (got "Optional[int]", expected "int") [return-value]

  • Mypy version used: 1.1.1
  • Mypy command-line flags: None
  • Mypy configuration options from mypy.ini (and other config files): None
  • Python version used: 3.11

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugmypy got something wrongtopic-type-narrowingConditional type narrowing / binder

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions