PEP570新语法: 只接受位置参数
source link: http://www.dongwm.com/post/136/?amp%3Butm_medium=referral
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.
最近 PEP 570被接受了,其实要加的这个 Positional-Only Parameters
原来在内置的C函数上有很多都用到了:
In : __builtin__.eval Out: <function eval(source, globals=None, locals=None, /)> In : __builtin__.len Out: <function len(obj, /)> In : __builtin__.divmod Out: <function divmod(x, y, /)>
看它们的签名,最后都有一个 /
, /
用途是
在 /
左面的这些参数,只能是位置参数(不能是关键字参数)
:
In : divmod(3, 2) Out: (1, 1) In : divmod(x=3, y=2) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) <ipython-input-28-6668f56246b2> in <module> ----> 1 divmod(x=3, y=2) TypeError: divmod() takes no keyword arguments
如果使用关键字参数的方式,会报错。当然这个错有点莫名其妙。为什么要搞 Positional-Only
呢? 就是强制使用者用位置参数!
再看一个例子(bytes):
In [68]: bytes?? Init signature: bytes(self, /, *args, **kwargs) Docstring: bytes(iterable_of_ints) -> bytes bytes(string, encoding[, errors]) -> bytes bytes(bytes_or_buffer) -> immutable copy of bytes_or_buffer bytes(int) -> bytes object of size given by the parameter initialized with null bytes bytes() -> empty bytes object ... In : bytes('哈哈', 'utf-8') Out: b'\xe5\x93\x88\xe5\x93\x88' In : bytes('哈哈', encoding='utf-8') Out: b'\xe5\x93\x88\xe5\x93\x88'
虽然bytes也有 /
,但是它只约束了左边的参数(这里只有一个 self
),之后的 encoding
可以用位置参数,也能用关键字参数。
通过PEP 570,我们写的Python代码也可以支持了。你可以这样写:
def name(p1, p2, /, p_or_kw, *, kw): def name(p1, p2=None, /, p_or_kw=None, *, kw): def name(p1, p2=None, /, *, kw): def name(p1, p2=None, /): def name(p1, p2, /, p_or_kw): def name(p1, p2, /):
在 Python 3.8 时我们就能使用这个新语法啦。现在可以通过 PEP里面的几个简单例子,感受一下它的用法,期待哟
延伸阅读
Recommend
-
86
-
36
1、let和const命令let命令,用来声明变量。它的用法类似于var,但是所声明的变量,只在let命令所在的代码块内有效。{ let a = 10; var b = 1; } a // ReferenceError: a is not defin
-
47
-
48
最近沉迷与 MIT 6.824 这门分布式系统的课,无心写文章。不过看到 PEP570 被接受了,决定还是写篇水文随便聊聊 PEP 570 Python 的 argument 在聊 PEP570...
-
44
-
16
byzhangxinxu from https://www.zhangxinxu.com/wordpress/?p=9535 本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可以联系授权。...
-
25
byzhangxinxu from https://www.zhangxinxu.com/wordpress/?p=9595 本文欢迎分享与聚合,全文转载就不必了,尊重版权,圈子就这么大,若急用可以联系授权。...
-
8
近日,Vue 作者尤雨溪在社区意见征求稿(RFC)上提交了一份 Ref 语法糖的提案,引起了开发者们的争议。 起因是一个新语法糖 尤雨溪在该 Ref 语法糖的提案中加入了一个新的功能:在单个文件组件(SFC)中引入了新的 s...
-
1
Qt Quick 5.15.0 Connections 新语法 发表评论 过去的 Connection 连接某个对象的信号时是这样写的: Connections...
-
1
"组合API"是vue3扩充的全新语法, 前面基础课中讲解的语法叫"选项API". 2种API在vue3中都支持.解决了什么?"组合API"可以更进一步拆分"选项API"中的JS逻辑...
About Joyk
Aggregate valuable and interesting links.
Joyk means Joy of geeK