Feature
If assert_never is used for exhaustive checking (per https://typing.readthedocs.io/en/latest/source/unreachable.html#assert-never-and-exhaustiveness-checking), then the possibly-undefined mypy rule should acknowledge that condition is impossible and so recognize when a variable must be defined.
Pitch
Simple example (python 3.11)
# calculate.pyimportenumfromtypingimportassert_neverclassOp(enum.Enum):
ADD=1SUBTRACT=2defcalculate(left: int, op: Op, right: int) ->int:
ifopisOp.ADD:
result=left+rightelifopisOp.SUBTRACT:
result=left-rightelse:
assert_never(op)
returnresult
With mypy 1.0.1, running mypy --enable-error-code=possibly-undefined calculate.py results in:
calculate.py:18: error: Name "result" may be undefined [possibly-undefined]
Found 1 error in 1 file (checked 1 source file)
Because we asserted that we can never enter the else case, result should not be considered "possibly undefined" in the return statement above.
The possibly-undefined rule does behave properly when raising an exception, and should do the same with assert_never. For instance, the following does not result in a mypy violation for possibly-undefined:
defcalculate(left: int, op: Op, right: int) ->int:
ifopisOp.ADD:
result=left+rightelifopisOp.SUBTRACT:
result=left-rightelse:
raiseValueError("Invalid op")
returnresult
Feature
If
assert_neveris used for exhaustive checking (per https://typing.readthedocs.io/en/latest/source/unreachable.html#assert-never-and-exhaustiveness-checking), then thepossibly-undefinedmypy rule should acknowledge that condition is impossible and so recognize when a variable must be defined.Pitch
Simple example (python 3.11)
With mypy 1.0.1, running
mypy --enable-error-code=possibly-undefined calculate.pyresults in:Because we asserted that we can never enter the
elsecase,resultshould not be considered "possibly undefined" in thereturnstatement above.The
possibly-undefinedrule does behave properly when raising an exception, and should do the same withassert_never. For instance, the following does not result in a mypy violation forpossibly-undefined: