对于 mypy 来说,一个注释比另一个注释更好吗?

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

考虑以下两个注释:

def foo1(arg: tuple[datetime, int] | tuple[datetime, None]) -> datetime
    ...

def foo2(arg: tuple[datetime, int | None]) -> datetime
    ...

有理由使用其中一种而不是另一种吗?(除了偏好)

据我所知,它们在逻辑上是等价的;他们是吗?

python python-3.x annotations type-hinting mypy
1个回答
0
投票

两者并不完全等同。

tuple[datetime, int | None]
传递给第一个变体是无效的,但对第二个变体有效。

给定

def foo1(arg: tuple[datetime, int] | tuple[datetime, None]) -> datetime
    ...

def foo2(arg: tuple[datetime, int | None]) -> datetime
    ...

代码

x: tuple[datetime, int | None] = ...

foo1(x)
foo2(x)

使用 mypy 进行类型检查失败并显示消息

error: Argument 1 to "foo1" has incompatible type "tuple[datetime, int | None]"; expected "tuple[datetime, int] | tuple[datetime, None]"  [arg-type]

这是否有用取决于您的用例。

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