确定是否传递了命名参数

发布于 2024-07-08 09:52:26 字数 427 浏览 12 评论 0原文

我想知道是否可以确定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 来做的事情吗?

谢谢

I would like to know if it is possible to determine if a function parameter with a default value was passed in Python.
For example, how does dict.pop work?

>>> {}.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

How does the pop method determine that the first time a default return value was not passed? Is this something that can only be done in C?

Thanks

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

赏烟花じ飞满天 2024-07-15 09:52:26

约定通常是使用 arg=None 并用于

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

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

The convention is often to use arg=None and use

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

to check if it was passed or not. Allowing the user to pass None, which would be interpreted as if the argument was not passed.

野稚 2024-07-15 09:52:26

我猜当你说“命名参数”时,你的意思是“关键字参数”。 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 调用约定,其中参数可以按位置或按名称提供,并且可以多次提供参数(按位置和名称)导致错误。

I guess you mean "keyword argument", when you say "named parameter". dict.pop() does not accept keyword argument, so this part of the question is moot.

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

That said, the way to detect whether an argument was provided is to use the *args or **kwargs syntax. For example:

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]

With some work, and using the **kwargs syntax too it is possible to completely emulate the python calling convention, where arguments can be either provided by position or by name, and arguments provided multiple times (by position and name) cause an error.

不乱于心 2024-07-15 09:52:26

您可以这样做:

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

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

有关完整信息,请参阅有关 调用 的 Python 文档。

You can do it like this:

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

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

See the Python documentation on calls for full information.

墨落画卷 2024-07-15 09:52:26

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

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

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

I am not certain if I fully understand what is it you want; however:

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

does that do what you want? If not, then as others have suggested, you should declare your function with the *args, **kwargs syntax and check in the kwargs dict for the parameter existence.

旧伤还要旧人安 2024-07-15 09:52:26
def f(one, two=2):
   print "I wonder if", two, "has been passed or not..."

f(1, 2)

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

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

f(1, 2)

If this is the exact meaning of your question, I think that there is no way to distinguish between a 2 that was in the default value and a 2 that has been passed. I didn't find how to accomplish such distinction even in the inspect module.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文