我试图声明一个参数对于
typing
库来说是可选的。由于这个参数可以是 int | None
,如果我尝试用它做一个数学表达式,我首先必须检查它是否是 None
,否则会引发错误。
我的代码片段(部分实现的代码):
def foo(filename: str, size: Optional[int] = None):
# open filename, if it doesn't exist, create it if size is not None and size is multiple of someConstant
# if file exists, read and get trueFileSize
...
if size is not None and trueFileSize != size * someConstant:
# if trueFileSize is different than size times someConstant, rewrites file here
...
据我了解,如果
and
逻辑运算符第一次检查返回 False
,则后续检查将被忽略,就像在 C 中一样。如果我是正确的,为什么 mypy
告诉我这个
... error: Unsupported operand types for * ("int" and "None")
当我第一次检查
size
是否不是 None
?
我知道用两个 if 语句重写代码可以解决问题,但是为什么
mypy
无法处理前面的代码片段,但不会在下面的代码片段中引发错误?
def foo(filename: str, size: Optional[int] = None):
# open filename, if it doesn't exist, create it size is not None
# if file exists, read and get trueFileSize
...
if size is not None:
if trueFileSize != size * someConstant: # mypy: doesn't raise error
# if trueFileSize is different than size times someConstant, rewrite file
...
试试这个:
if size is not None and trueFileSize != (size * someConstant):
将乘法放在括号中以确定其优先级。