如果我将默认设置为 None 可以省略 Optional 吗?

编程入门 行业动态 更新时间:2024-10-27 02:29:35
本文介绍了如果我将默认设置为 None 可以省略 Optional 吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

例如:

def foo(bar: int = None): pass

当我检查 bar 的类型/注释时,pycharm 告诉我它是 Optional[int].

When I check a type/annotation of bar pycharm tells me that it is Optional[int].

bar: int = None 看起来比 bar: Optional[int] = None 简洁得多,尤其是当你有 10 个以上的参数时.

bar: int = None looks much cleaner rather then bar: Optional[int] = None, especially when you have 10+ parameters.

那么我可以简单地省略 Optional 吗?像 mypy 或其他 linter 这样的工具是否会将这种情况突出显示为错误?

So can I simply omit Optional? Will tools like mypy or other linters highlight this case as en error?

看起来python本身不喜欢这个想法:

Looks like python itself doesn't like the idea:

In [1]: from typing import Optional In [2]: from inspect import signature In [3]: def foo(a: int = None): pass In [4]: def bar(a: Optional[int] = None): pass In [5]: signature(foo).parameters['a'].annotation Out[5]: int In [6]: signature(bar).parameters['a'].annotation Out[6]: typing.Union[int, NoneType]

推荐答案

没有.省略 Optional 以前是允许的,但后来被删除了.

No. Omitting Optional was previously allowed, but has since been removed.

此 PEP 的过去版本当默认值为 None [...]

A past version of this PEP allowed type checkers to assume an optional type when the default value is None [...]

这不再是推荐的行为.类型检查器应该朝着要求明确可选类型的方向发展.

This is no longer the recommended behavior. Type checkers should move towards requiring the optional type to be made explicit.

某些工具可能仍会提供旧版支持的旧行为.即使是这样,也不要指望将来会支持它.

Some tools may still provide the old behaviour for legacy support. Even if that is the case, do not rely on it being supported in the future.

具体来说,mypy 仍然默认支持隐式 Optional,但明确指出这在未来可能会发生变化:

In specific, mypy still supports implicit Optional by default, but explicitly notes this may change in the future:

[...] 您可以使用 --no-implicit-optional 命令行选项停止将具有 None 默认值的参数视为具有隐式 Optional[...] 类型.这可能会成为未来的默认行为.

Optional types and the None type (mypy v0.782)

[...] You can use the --no-implicit-optional command-line option to stop treating arguments with a None default value as having an implicit Optional[...] type. It’s possible that this will become the default behavior in the future.

mypy/#9091

更多推荐

如果我将默认设置为 None 可以省略 Optional 吗?

本文发布于:2023-11-28 14:47:13,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1642845.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:我将   设置为   Optional

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!