我正在用 python 编写一些带有类型注释的代码。我对可选类型有疑问。例如,对于这样的代码:
maybe_number : Optional[int] = ... # definition
if maybe_number == None:
...
else:
# I know its int because i checked, but it is a typechecking error
number : int = maybe_number
...
我收到错误:
Incompatible types in assignment (expression has type "Optional[int]", variable has type "int")
如何在 python 中表达我知道某个分支中 Union 或Optional 类型的实际值类型。我需要以特定方式检查类型吗?
最佳答案
相等实际上并不能告诉你太多关于对象类型的信息,因为这两个对象可能有 __eq__
方法允许它们相同但类型不同,甚至不相关。您可以检查是否 maybe_number
是值 None
通过使用身份比较:
if maybe_number is None:
...
else:
number : int = maybe_number
关于python-3.x - 可选类型注释。检查是否为“无”后使用值?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54641598/