如何解决不兼容类型可选类型冲突?

问题描述 投票:0回答:1

嗨,有人知道如何解决 py3 中的此错误吗?收到错误消息,例如:

“int”具有不兼容的类型“Union[float, int, str, None]”;预期的 “联合[str,字节,SupportsInt,SupportsIndex,SupportsTrunc]

我的类型是可选值

Union[float, int, str, None]
。我想在它是 int 时进行转换
int(VALUE)
。 Union 来自
typing
模块

option-type pylint python-3.10 union-types
1个回答
0
投票

mypy 中找到的解决方案给出了不兼容类型“Optional[int]”的错误;预期“Union[SupportsFloat、str、bytes、bytearray]

示例

  value = 10 // Type is Union[float, str, int, None], an optional value
  assert isinstance(value, int)
  assert int(value) == 10

类似于

float
str
或列表中的值
[int(t) for t in list if isinstance(t, int)]

© www.soinside.com 2019 - 2024. All rights reserved.