[英]Python: required kwarg, which exception to raise?
确保使用特定kwarg调用方法的一种方法是:
def mymethod(self, *args, **kwargs):
assert "required_field" in kwargs
提出AssertionError
似乎不是最合适的事情。 是否有一个商定的内置异常来处理这个错误消息?
更多信息:存在第三方子类化问题,其中* args和** kwargs有点'需要传递,因此使“required_field”成为位置参数并不是一个好的选择。
>>> def foo(bar): pass
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: foo() missing 1 required positional argument: 'bar'
我只是选择TypeError ..
+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)
(TypeError建议已经给出(并被接受);我写了这个答案,提到了这个Python 3的特性)。
标准库似乎喜欢在获取错误数量的参数时引发TypeError
。 这基本上是你的问题所以我会提出这个问题。
也就是说, **kwargs
在大多数情况下基本上填写默认参数,因此具有所需的默认参数似乎有点令人惊讶/困惑。
请注意,python很乐意让您通过关键字调用位置参数:
>>> def foo(a, b):
... print a, b
...
>>> foo(a=1, b=2)
1 2
>>> foo(b=1, a=2)
2 1
但我想,那么他们都必须通过关键字引用( foo(2, a=2)
不起作用),你可能不想要。
如果您需要它是必需的关键字,请执行以下操作:
def mymethod(self,myrequired=None):
if myrequired==None:
#raise error
#do other stuff down here
你真的不需要从kwargs中取出它。
我认为KeyError
是最合适的,因为**kwargs
是一个dict
。
>>> def foo(**kwargs):
... print kwargs['abc']
...
>>> foo()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "<stdin>", line 2, in foo
KeyError: 'abc'
如果实际需要该字段,您可以检查它
try:
kwargs['required']
except KeyError:
raise KeyError('required is a Required Argument')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.