确保使用特定kwarg调用方法的一种方法是:
def mymethod(self, *args, **kwargs):
assert "required_field" in kwargs
Run Code Online (Sandbox Code Playgroud)
提升一个AssertionError似乎不是最合适的事情.是否有一个商定的内置异常来处理这个错误消息?
更多信息:存在第三方子类化问题,其中*args和**kwargs有点'需要传递,因此使"required_field"成为位置参数并不是一个好的选择.
Ott*_*ger 33
>>> def foo(bar): pass
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'bar'
Run Code Online (Sandbox Code Playgroud)
我只是选择TypeError ..
Mik*_*bov 18
+1为TypeError.这就是Python 3为必需的仅限关键字参数引发的内容:
>>> def foo(*, x):
... pass
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() needs keyword-only argument x
>>> foo(2)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() takes exactly 0 positional arguments (1 given)
>>> foo(x=2)
Run Code Online (Sandbox Code Playgroud)
(TypeError建议已经给出(并被接受);我写了这个答案,提到了这个Python 3的特性).
mgi*_*son 15
当标准库TypeError获得错误的参数数量时,它似乎想要提升.这基本上是你的问题所以我会提出这个问题.
也就是说,**kwargs基本上大部分时间都填写默认参数,因此拥有一个必需的默认参数似乎有点令人惊讶/困惑.
请注意,python很乐意让您通过关键字调用位置参数:
>>> def foo(a, b):
... print a, b
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
Run Code Online (Sandbox Code Playgroud)
但我想,那么他们都必须通过foo(2, a=2)你可能不想要的关键字(不起作用)来引用.
| 归档时间: |
|
| 查看次数: |
11368 次 |
| 最近记录: |