簡體   English   中英

Python:需要kwarg,哪個例外要加注?

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM