Skip to content

Mypy doesn't narrow down the type in an else block #15916

Closed
@johndoknjas

Description

@johndoknjas

I noticed that when an if statement involves checking the type of a variable, mypy uses this information in the if block. However, if there's an else block, mypy doesn't disregard this type.
Initially I assumed this was a ternary-specific problem, related to an older issue I posted. However, this current issue seems to also be a problem in a regular if-else construct.

To Reproduce

from typing import Union

def if_statement_example(param: Union[str, int]) -> bool:
    if type(param) is str:
        return len(param) == 2
    else:
        return param < 3
    
def ternary_example(param: Union[str, int]) -> bool:
    return len(param) == 2 if type(param) is str else param < 3

Expected Behavior

No errors

Actual Behavior

type_in_condition.py:7: error: Unsupported operand types for < ("str" and "int") [operator]
type_in_condition.py:7: note: Left operand is of type "Union[str, int]"
type_in_condition.py:10: error: Unsupported operand types for < ("str" and "int") [operator]
type_in_condition.py:10: note: Left operand is of type "Union[str, int]"

Your Environment

  • Mypy version used: mypy 1.3.0 (compiled: yes)
  • Mypy command-line flags: none - just ran mypy main.py
  • Mypy configuration options from mypy.ini (and other config files): none
  • Python version used: 3.11.0
  • OS: Windows 11

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