python:是否可以要求函数的参数都是关键字?

max*_*max 10 python coding-style function python-3.x

为了避免明显的错误,我想阻止使用某些函数的位置参数.有没有办法实现这一目标?

JBe*_*rdo 28

只有Python 3才能正确完成(你使用了python3标签,所以没关系):

def function(*, x, y, z):
    print(x,y,z)
Run Code Online (Sandbox Code Playgroud)

使用**kwargs将让用户输入任何参数,除非您稍后检查.此外,它将隐藏内省的真实参数名称.

**kwargs 不是这个问题的答案.

测试程序:

>>> function(1,2,3)
Traceback (most recent call last):
  File "<pyshell#1>", line 1, in <module>
    function(1,2,3)
TypeError: function() takes exactly 0 positional arguments (3 given)
>>> function(x=1, y=2, z=3)
1 2 3
Run Code Online (Sandbox Code Playgroud)


Zac*_*now 8

您可以定义一个装饰器,如果它装饰的函数使用任何位置参数,则使用内省会导致错误.这允许您阻止对某些函数使用位置参数,同时允许您根据需要定义这些函数.

举个例子:

def kwargs_only(f):
    def new_f(**kwargs):
        return f(**kwargs)
    return new_f
Run Code Online (Sandbox Code Playgroud)

要使用它:

@kwargs_only
def abc(a, b, c): return a + b + c
Run Code Online (Sandbox Code Playgroud)

你不能这样使用它(类型错误):

abc(1,2,3)
Run Code Online (Sandbox Code Playgroud)

你可以这样使用它:

abc(a=1,b=2,c=3)
Run Code Online (Sandbox Code Playgroud)

更强大的解决方案将使用该decorator模块.

免责声明:深夜答案不保证!