[英]prevent typos in variable keyword args
在Python3中,我可以做(感謝pep 3102 ):
def some_fun(a, *args, log=None, verbose=0):
pass
並確保如果我通過以下方式致電:
some_fun(1, 2, 3, lob=debug_log)
我在意外的關鍵字參數lob
上遇到類型錯誤。
在Python2上,我無法在任意參數列表之后使用僅關鍵字參數定義some_fun()
。 我要做:
def some_fun(a, *args, **kw):
log = kw.get("log", None)
verbose = kw.get("verbose", 0)
當正確調用時,這一切都很好,但我想像Python3一樣在我向some_fun()
提供一個或多個錯誤的關鍵字參數時遇到類型錯誤。
不要使用.get()
來檢索值,而應使用.pop()
並在彈出所有僅關鍵字參數后檢查kw
是否為空。
我為此使用一個小的輔助函數:
def check_empty_kwargs(kwargs):
import inspect
try:
keys = kwargs.keys()
assert len(keys) == 0
except AssertionError:
# uncomment if you want only one of the unexpected kwargs in the msg
# keys = keys[:1]
msg = "{0}() got an unexpected keyword argument{1} {2}".format(
inspect.stack()[1][3], # caller name
's' if len(keys) > 1 else '',
', '.join(["'{0}'".format(k) for k in keys]))
raise TypeError(msg)
您會像這樣使用它:
def some_fun(a, *args, **kw):
log = kw.pop("log", None)
verbose = kw.pop("verbose", 0)
check_empty_kwargs(kw)
調用它(假設定義了debug_log
)
some_fun(1, 2, 3, lob=debug_log)
....
TypeError: some_fun() got an unexpected keyword argument 'lob'
追溯(當然)將與Python3不同
您可以檢查允許的密鑰,例如:
def f(a, *args, **kwargs):
surplus = set(kwargs).difference(('log', 'foo', 'bar'))
if surplus:
raise TypeError('got unexpected keyword argument(s): ' + ', '.join(surplus))
如果您有一堆處理步驟,則可以將上述技術與另一種技術結合使用:
def f(a, *args, **kwargs):
# we allow xyz, a, b
xyz = kwargs.pop('xyz', 1)
# now xyz must be gone, so we can only have a and/or b
others = (lambda a=1, b=2: (a, b)(**kwargs))
# either that was ok or it failed
return xyz, others
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.