You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
{{ message }}
Repository navigation
Different behavior for Optional with if condition not Var and Var is not None #7696
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?
Activity
JukkaL commentedon Oct 11, 2019
Yeah, this looks inconsistent. Here's a bit shorter example:
Maybe assigning
Anyto a variable with typeOptional[X]should bind the type toUnion[X, Any].ilevkivskyi commentedon Feb 5, 2025
Mypy now consistently narrows to
Union[X, Any]in all cases.