如何检查NewType值的类型?
如何在不铸造和混合类型检查的情况下检查newType
的值 str ?
我声明了一种新类型:
BoardId = NewType("BoardId", str)
除str
之外,我将其用作方法参数作为单个值或迭代
。
我使用实例
检查类型是否为str
而不是tuple
,然后我将其转换为元组,否则请按原样使用它。 问题pyright
事物boardId
是str
,因为isinstance
失败了类型检查。 另一方面,我不能使用isinstance
newType
以来
:
离开时
async def get_stickies(
self, board_id: Union[BoardId, Iterable[BoardId]]
) -> List[Sticky]:
board_ids: Iterable[BoardId] = (
(board_id,) if isinstance(board_id, str) else board_id
)
要出现这个问题:
Diagnostics:
1. Expression of type "tuple[BoardId | str] | Iterable[BoardId]" cannot be assigned to declared type "Iterable[BoardId]"
Type "tuple[BoardId | str] | Iterable[BoardId]" cannot be assigned to type "Iterable[BoardId]"
TypeVar "_T_co@Iterable" is covariant
Type "BoardId | str" cannot be assigned to type "BoardId"
"str" is incompatible with "BoardId"
How do you check the value of NewType
against its basic type str
without casting and mixing up type checking?
I declared a new type:
BoardId = NewType("BoardId", str)
that I use as a method parameter either as a single value or as an Iteration
other than str
.
I use instanceof
to check if the type is str
and not Tuple
then I convert it to a tuple otherwise use it as it is.
The problem pyright
things BoardId
is str
because of isinstance
which fails the type checking.
On the other hand, I cannot use isinstance
against NewType
since:
TypeError: isinstance() arg 2 must be a type, a tuple of types, or a union
Leaving as it is
async def get_stickies(
self, board_id: Union[BoardId, Iterable[BoardId]]
) -> List[Sticky]:
board_ids: Iterable[BoardId] = (
(board_id,) if isinstance(board_id, str) else board_id
)
causes this issue:
Diagnostics:
1. Expression of type "tuple[BoardId | str] | Iterable[BoardId]" cannot be assigned to declared type "Iterable[BoardId]"
Type "tuple[BoardId | str] | Iterable[BoardId]" cannot be assigned to type "Iterable[BoardId]"
TypeVar "_T_co@Iterable" is covariant
Type "BoardId | str" cannot be assigned to type "BoardId"
"str" is incompatible with "BoardId"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
中提出了一种解决方案。
在
;
mypy
不喜欢此无证件属性。One solution was proposed in this issue:
Playground link
The underlying type is accessible via
BoardId.__supertype__
, butmypy
doesn't like this undocumented attribute.