如果我将默认设置为 None 可以省略 Optional 吗? [英] Can I omit Optional if I set default to None?

查看:70
本文介绍了如果我将默认设置为 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 吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆