确定是否传递了命名参数

时间:2008-11-01 02:23:27

标签: 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

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

由于

5 个答案:

答案 0 :(得分:11)

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

def foo(arg=None):
    if arg is None:
        arg = "default value"
        # other stuff
    # ...

检查是否通过了。允许用户传递None,这将被解释为参数而不是已被传递。

答案 1 :(得分:8)

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

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

也就是说,检测是否提供参数的方法是使用*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]

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

答案 2 :(得分:2)

你可以这样做:

def isdefarg(*args):
    if len(args) > 0:
        print len(args), "arguments"
    else:
        print "no arguments"

isdefarg()
isdefarg(None)
isdefarg(5, 7)

有关完整信息,请参阅calls上的Python文档。

答案 3 :(得分:2)

def f(one, two=2):
   print "I wonder if", two, "has been passed or not..."

f(1, 2)

如果这是你问题的确切含义,我认为没有办法区分默认值中的2和已经传递的2。即使在inspect模块中,我也没有找到如何实现这种区别。

答案 4 :(得分:1)

我不确定我是否完全理解你想要的是什么;但是:

def fun(arg=Ellipsis):
    if arg is Ellipsis:
        print "No arg provided"
    else:
        print "arg provided:", repr(arg)

这样做你想要的吗?如果没有,那么正如其他人所建议的那样,你应该使用*args, **kwargs语法声明你的函数,并检查kwargs dict中是否存在参数。