Skip to content

Different behavior for Optional with if condition not Var and Var is not None #7696

Closed

Description

@actionless
  • Are you reporting a bug, or opening a feature request?
    Bug
  • Please insert below the code you are checking with mypy,
    or a mock-up repro if the source is private. We would appreciate
    if you try to simplify your case to a minimal repro.
from typing import List, Optional, Any

class MyClass1:

    _result: Optional[List[str]] = None
    _foo: Any = None

    @classmethod
    def get(cls, some_arg: Optional[str]) -> List[str]:
        if cls._result is None:
            cls._result = [some_arg or 'a'] + (
                cls._foo.split(',') if cls._foo else []
            )
        return cls._result

class MyClass2:

    _result: Optional[List[str]] = None
    _foo: Any = None

    @classmethod
    def get(cls, some_arg: Optional[str]) -> List[str]:
        if not cls._result:
            cls._result = [some_arg or 'a'] + (
                cls._foo.split(',') if cls._foo else []
            )
        return cls._result
#       ^ [mypy] : Incompatible return value type (got "Optional[List[str]]", expected "List[str]")

  • What is the actual behavior/output?
    mypy_func.py:44: error: Incompatible return value type (got "Optional[List[str]]", expected "List[str]")
    Found 1 error in 1 file (checked 1 source file)

  • What are the versions of mypy and Python you are using?
    Do you see the same issue after installing mypy from Git master?

$ python -m mypy --version
mypy 0.740+dev.742d33a41271206d6eb7dd2e4b04659de4683597

$ python --version
Python 3.7.4

Activity

  1. JukkaL commented on Oct 11, 2019

    @JukkaL
    Collaborator

    Yeah, this looks inconsistent. Here's a bit shorter example:

    from typing import Optional, List, Any
    
    a: Any
    
    def f(x: Optional[List[int]]) -> None:
        if not x:
            x = a
        reveal_type(x)  # Optional[List[int]]
    
    def g(x: Optional[List[int]]) -> None:
        if x is None:
            x = a
        reveal_type(x)  # Union[List[int], Any]
    
    def h(x: Optional[List[int]]) -> None:
        x = a
        reveal_type(x)  # Optional[List[int]]

    Maybe assigning Any to a variable with type Optional[X] should bind the type to Union[X, Any].

  2. ilevkivskyi commented on Feb 5, 2025

    @ilevkivskyi
    Member

    Mypy now consistently narrows to Union[X, Any] in all cases.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions