为了避免打字问题,我经常遇到同样的问题.
例如,我有一个函数x
,它很少返回值None
,其他时候它返回int
.
def x(i: int) -> Union[int, None]:
if i == 0:
return
return i
def test(i: int):
a = x(i)
# typing issue: *= not supported for types int | None and int
a *= 25
x
在代码库中经常使用,大多数时候i
已经被判断了一百次,x(i)
确实会返回int
而不是None
.
使用它作为int
立即创建键入警告—例如,你不能乘以可能的None
值.
这个案子的最佳做法是什么?
我考虑过的 idea 是:
- 没有真正意义的判断它
None
与if a is None: return
,因为它已经known. -
a *= 25 # type: ignore
将使a
成为Unknown
类型. -
a = x(i) # type: int
次警告就会消失.但会创建一个新的警告"int| None不能分配给int " -
a = cast(int, x(i))
个,还没试过很多.
我通常会将返回类型x
改为int
,在return # type: ignore
中添加ignore
,并在文档字符串中提到它可以返回None
,这有助于避免类型警告污染整个代码库.这是最好的办法吗?
def x(i: int) -> int:
"""might also return `None`"""
if i == 0:
return # type: ignore
return i