Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python Mypy:elif中的tell参数在没有assert的情况下为None_Python_Mypy - Fatal编程技术网

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
not
cast

这两种
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