Python 3.10可选参数:键入联合vs none默认值

发布于 2025-01-24 15:33:38 字数 965 浏览 0 评论 0原文

这不是一个大问题,但是作为样式,我想知道指示可选函数参数的最佳方法

... /code>:

def my_func(a, b = None)

在Python 3.10之前,使用类型提示:

def my_func(a, b: Optional[str])

使用Python 3.10的可爱管道型符号(请参阅“ noreferrer”> PEP 604 ):

def my_func(a, b: str | None)

后者似乎是三个选项的明显选择,但是我想知道这是否完全消除了指定 default none value,这将是:

def my_func(a, b: str | None = None)

编辑:感谢@deceze和@jonrsharpe指出def my_func(a,b:b:b:str | none)仍然需要您将值传递给b :如果您愿意,您将明确必须通过

因此,最简洁的方法是确保b是可选的(即,呼叫者确实必须完全传递一个值)是:

def my_func(a, b: str = None)

造型上,合并显式键入,是def my_func(a,b:str | none = none),即显式可选键入 plus plus default none none 值

It's not a huge issue, but as a matter of style, I was wondering about the best way to indicate optional function parameters...

Before type hints, it was like this for parameter b:

def my_func(a, b = None)

Before Python 3.10, using type hints:

def my_func(a, b: Optional[str])

With Python 3.10's lovely pipe-type notation (see PEP 604):

def my_func(a, b: str | None)

The latter seems the obvious choice of the three options, but I was wondering if this completely eliminates the need to specify the default None value, which would be:

def my_func(a, b: str | None = None)

EDIT: Thanks to @deceze and @jonrsharpe for pointing out that def my_func(a, b: str | None) would still require you to pass a value to b: you would explicitly have to pass None if you wanted that.

So, the most concise one that will work to ensure that b is optional (i.e. the caller does not have to pass a value at all) is:

def my_func(a, b: str = None)

Stylistically, incorporating explicit typing, is def my_func(a, b: str | None = None), i.e. explicit optional typing plus default None value, ever an option?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

云淡风轻 2025-01-31 15:33:38

per pep-484

此PEP的过去版本允许类型的Checkers假设默认值不在时假设一个可选类型,如此代码:

def handle_employee(e:雇员= none):...

这不再是推荐行为。类型的跳棋应朝着要求明确的可选类型迈进。

因此,官方答案是否定的。您应该指定... |无=可选参数的无

Per PEP-484:

A past version of this PEP allowed type checkers to assume an optional type when the default value is None, as in this code:

def handle_employee(e: Employee = None): ...

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

So the official answer is no. You should specify ... | None = None for optional arguments.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文