Description
Bug Report
When using --no-strict-optional
the determined type within a one-line boolean expression does not always get calculated correctly
To Reproduce
from contextlib import nullcontext
import pytest
def test(raises: bool) -> None:
ctx = pytest.raises(ValueError) if raises else nullcontext()
#ctx = nullcontext() if not raises else pytest.raises(ValueError)
import typing
if typing.TYPE_CHECKING:
reveal_type(ctx)
with ctx:
pass
Expected Behavior
The context manager types would be resolved correctly
Actual Behavior
(.venv) vfazio@VFAZIO1:~/development/xtf$ mypy --no-strict-optional contextlib_check.py
contextlib_check.py:9:21: note: Revealed type is "builtins.object"
contextlib_check.py:10:10: error: "object" has no attribute "__enter__" [attr-defined]
contextlib_check.py:10:10: error: "object" has no attribute "__exit__" [attr-defined]
Found 2 errors in 1 file (checked 1 source file)
(.venv) vfazio@VFAZIO1:~/development/xtf$ mypy -V
mypy 1.11.0 (compiled: yes)
If you use the line that's commented out, it "works" and it only changes the order of object evaluation:
(xtf-py3.11) (.venv) vfazio@VFAZIO1:~/development/xtf$ mypy --no-strict-optional contextlib_check.py
contextlib_check.py:9:21: note: Revealed type is "contextlib.AbstractContextManager[_pytest._code.code.ExceptionInfo[builtins.ValueError], builtins.bool]"
Success: no issues found in 1 source file
If --no-strict-optional
is not passed, it also checks fine:
(.venv) vfazio@VFAZIO1:~/development/xtf$ mypy contextlib_check.py
contextlib_check.py:9:21: note: Revealed type is "contextlib.AbstractContextManager[Union[_pytest._code.code.ExceptionInfo[builtins.ValueError], None], Union[builtins.bool, None]]"
In all cases, rightly (probably) or wrongly, the revealed type is also different than it was in 1.10.x.
(.venv) vfazio@VFAZIO1:~/development/xtf$ mypy --no-strict-optional contextlib_check.py
contextlib_check.py:9:21: note: Revealed type is "contextlib.AbstractContextManager[_pytest._code.code.ExceptionInfo[builtins.ValueError]]"
Success: no issues found in 1 source file
(.venv) vfazio@VFAZIO1:~/development/xtf$ mypy -V
mypy 1.10.1 (compiled: yes)
(.venv) vfazio@VFAZIO1:~/development/xtf$ mypy contextlib_check.py
contextlib_check.py:9:21: note: Revealed type is "contextlib.AbstractContextManager[Union[_pytest._code.code.ExceptionInfo[builtins.ValueError], None]]"
I think I'd expect some cooked down version of _pytest.python_api.RaisesContext[builtins.ValueError] | contextlib.nullcontext[None]
. it's not clear to me where the builtins.bool
value is coming from in 1.11.x.
In the meantime, i can restructure the code, but this wasn't necessary in previous versions.
ctx: AbstractContextManager
if raises:
ctx = pytest.raises(ValueError)
else:
ctx = nullcontext()
Your Environment
- Mypy version used: 1.11.0
- Mypy command-line flags: --no-strict-optional
- Mypy configuration options from
mypy.ini
(and other config files): - Python version used: 3.11