如果列表 arg 仅包含 None,则 Python 键入返回 None 的函数
我正在使用一个有点像这样的函数(作为示例,超级简化):
def foo(*stuff: None | int):
stuff_not_none = [x for x in stuff if x is not None]
if len(stuff_not_none) is 0:
return None
return sum(stuff_not_none)
如果我使用以下方式调用该函数:
foo(*[1, 2, 3])
,我' d 希望将返回类型推断为int
。foo(*[None, None])
,我希望将返回类型推断为None
。foo(*[1, None])
,梦会被推断为int
,但如果None | 则可以。 int
。
我尝试过泛型/重载,但我无法解决这个难题。我怎样才能实现这个目标?
I'm working with a function that is a bit like this (super simplified, as an example):
def foo(*stuff: None | int):
stuff_not_none = [x for x in stuff if x is not None]
if len(stuff_not_none) is 0:
return None
return sum(stuff_not_none)
If I call the function using:
foo(*[1, 2, 3])
, I'd want the return type to be inferred toint
.foo(*[None, None])
, I'd want the return type to be inferred toNone
.foo(*[1, None])
, the dream would be inferred toint
, but ok ifNone | int
.
I've tried with generics / overloads, but I couldn't figure out this puzzle. How can I achieve this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
解决方案:
Mypy 讨厌这种事情,因为重载重叠。但您会发现,如果您在正确的位置添加
type:ignore
注释,它完全能够推断出正确的类型。 (我是一个 typeshed 维护者,我们一直在 typeshed 做这种事情。)请注意,重载的顺序非常重要:类型检查器总是首先尝试第一个重载,然后,只有当不匹配时,他们才会尝试第二次过载。这就是当我们传入
int
和None
的混合时获得int
显示类型的方式:第一个重载不匹配,由于int
的存在,因此类型检查器被迫尝试第二次重载。Mypy Playground 演示: https://mypy-play.net/?mypy=latest&python=3.10&gist=ff07808e0a314208fdfa6291dcf9f717
The solution:
Mypy hates this kind of thing, because the overloads overlap. But you'll find that if you add a
type: ignore
comment in the right place, it's perfectly able to infer the correct types anyway. (I'm a typeshed maintainer, and we do this kind of thing at typeshed all the time.)Note that the order of the overloads is very important: type checkers will always try the first overload first, and then, only if that doesn't match, will they try the second overload. This is how we get the
int
revealed type when we pass in a mixture ofint
s andNone
s: the first overload doesn't match, because of the presence ofint
s, so the type checker is forced to try the second overload.Mypy playground demo: https://mypy-play.net/?mypy=latest&python=3.10&gist=ff07808e0a314208fdfa6291dcf9f717