python-3.x - 可选类型注释。检查是否为“无”后使用值?

标签 python-3.x type-hinting

我正在用 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/

相关文章:

python - 字段类型取决于其他字段的类型

python - Numpy 表示 'inplace'

php - 强数据类型错误

python - 类型提示与鸭子类型

php - 如何在 PHP 类型提示中捕获 "catchable fatal error"?

python - "can be converted to"的类型提示是什么意思?

API 级别的 Django 组和权限(使用 django-rest-framework)

django - 找出 Django 代码在哪个用户下运行

Python:向方法调用添加可选参数的更优雅方式

Python沿着三角形的每条边反射图像