Python Mypy:elif中的tell参数在没有assert的情况下为None
我有一个函数Python Mypy:elif中的tell参数在没有assert的情况下为None,python,mypy,Python,Mypy,我有一个函数t.py: $ mypy t.py t.py:7: error: Incompatible types in assignment (expression has type "Optional[int]", variable has type "int") Found 1 error in 1 file (checked 1 source file) 从输入导入可选 定义f(a:可选[int],b:可选[int]): 如果a为无,b为无:
t.py
:
$ mypy t.py
t.py:7: error: Incompatible types in assignment (expression has type "Optional[int]", variable has type "int")
Found 1 error in 1 file (checked 1 source file)
从输入导入可选
定义f(a:可选[int],b:可选[int]):
如果a为无,b为无:
c:int=3
如果a为无:
c=b
elif b为无:
c=a
其他:
c=0
下面是运行mypy时发生的情况:
$ mypy t.py
t.py:7: error: Incompatible types in assignment (expression has type "Optional[int]", variable has type "int")
Found 1 error in 1 file (checked 1 source file)
我可以通过使用assert
:
从输入导入可选
定义f(a:可选[int],b:可选[int]):
如果a为无,b为无:
c:int=3
如果a为无:
断言b不是无
c=b
elif b为无:
c=a
其他:
c=0
然而,有没有更好的方法来做到这一点?理想情况下,解决方案不会使用
assert
notcast
这两种x是None
和x不是None
都是非常有效的比较。简单地反转比较以检查所需状态,而不是通过检查不需要的状态来暗示它
def(a:Optional[int],b:Optional[int]):
如果a为无,b为无:
c:int=3
elif b不是None:#使用b检查分支中的b
c=b
如果a不是无:#使用
c=a
其他:
c=0