Python 3.10可选参数:键入联合vs none默认值
这不是一个大问题,但是作为样式,我想知道指示可选函数参数的最佳方法
... /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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
per pep-484 :
因此,官方答案是否定的。您应该指定
... |无=可选参数的无
。Per PEP-484:
So the official answer is no. You should specify
... | None = None
for optional arguments.