确定是否传递了命名参数
我想知道是否可以确定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 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
约定通常是使用 arg=None 并用于
检查它是否通过。 允许用户传递
None
,这将被解释为参数未被传递。The convention is often to use
arg=None
and useto check if it was passed or not. Allowing the user to pass
None
, which would be interpreted as if the argument was not passed.我猜当你说“命名参数”时,你的意思是“关键字参数”。 dict.pop() 不接受关键字参数,因此这部分问题没有实际意义。
也就是说,检测是否提供了参数的方法是使用
*args
或**kwargs
语法。 例如:通过一些工作,并且也使用
**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.That said, the way to detect whether an argument was provided is to use the
*args
or**kwargs
syntax. For example: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.您可以这样做:
有关完整信息,请参阅有关 调用 的 Python 文档。
You can do it like this:
See the Python documentation on calls for full information.
我不确定我是否完全理解你想要什么; 但是:
这符合你的要求吗? 如果没有,那么正如其他人所建议的那样,您应该使用
*args, **kwargs
语法声明您的函数,并在 kwargs 字典中检查参数是否存在。I am not certain if I fully understand what is it you want; however:
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.如果这就是你问题的确切含义,我认为没有办法区分默认值中的 2 和已传递的 2 。 即使在 inspect 中,我也没有找到如何实现这种区别 模块。
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.