确定是否传递了命名参数

Jak*_*ake 14 python default-value named-parameters

我想知道是否可以确定是否在Python中传递了具有默认值的函数参数.例如,dict.pop是如何工作的?

>>> {}.pop('test')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
KeyError: 'pop(): dictionary is empty'
>>> {}.pop('test',None)
>>> {}.pop('test',3)
3
>>> {}.pop('test',NotImplemented)
NotImplemented
Run Code Online (Sandbox Code Playgroud)

pop方法如何确定第一次没有传递默认返回值?这是否只能在C中完成?

谢谢

Mar*_*rot 12

惯例通常是使用arg=None和使用

def foo(arg=None):
    if arg is None:
        arg = "default value"
        # other stuff
    # ...
Run Code Online (Sandbox Code Playgroud)

检查是否通过了.允许用户传递None,这将被解释为没有传递参数.

  • 如果`None`也是参数的有意义值,这没有用.示例是`dict.pop`及其未找到键时的行为 - 如果存在则返回第二个参数,否则引发KeyError. (9认同)
  • 在这种情况下,您可以使用对象创建一个闭包变量.`MISSING = object(); def foo(arg = MISSING):如果arg是MISSING:......` (6认同)

dda*_*daa 8

我猜你的意思是"关键字参数",当你说"命名参数"时.dict.pop()不接受关键字参数,所以这部分问题没有实际意义.

>>> {}.pop('test', d=None)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: pop() takes no keyword arguments
Run Code Online (Sandbox Code Playgroud)

也就是说,检测是否提供参数的方法是使用*args**kwargs语法.例如:

def foo(first, *rest):
    if len(rest) > 1:
        raise TypeError("foo() expected at most 2 arguments, got %d"
                        % (len(rest) + 1))
    print 'first =', first
    if rest:
        print 'second =', rest[0]
Run Code Online (Sandbox Code Playgroud)

通过一些工作,并使用**kwargs语法也可以完全模拟python调用约定,其中参数可以通过位置或名称提供,并且多次提供的参数(按位置和名称)会导致错误.