可选的类型注释.检查是否为无后使用值? [英] Optional type annotation. Using value after checking if is None?
问题描述
我正在用 python 编写一些带有类型注释的代码.我有 Optional 类型的问题.例如对于这样的代码:
I was writing some code with type annotations in python. I have problem with Optional type. For example for a code like this:
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中表示我知道某个分支中具有联合或可选类型的实际值类型.我需要以特定方式检查类型吗?
How can I express in python that I know actual type of value with Union or Optional type in certain branch. Do I need to check type in a specific way?
推荐答案
Equality 实际上并没有告诉你很多关于对象类型的信息,因为这两个对象可能有 __eq__
方法,允许它们相同但不同,甚至不相关的类型.您可以通过使用身份比较来检查 maybe_number
is 值是否为 None
:
Equality doesn't actually tell you much about an objects type, because the two objects could have __eq__
methods that allow them to be equal but of different, even unrelated, types. You can check if maybe_number
is the value None
by using identity comparison:
if maybe_number is None:
...
else:
number : int = maybe_number
这篇关于可选的类型注释.检查是否为无后使用值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!