gpt4 book ai didi

python - 防止变量关键字参数中的拼写错误

转载 作者:行者123 更新时间:2023-11-28 22:45:44 25 4
gpt4 key购买 nike

在 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)

当正确调用时,这一切都很好,但当我向 some_fun() 提供一个或多个错误的关键字参数时,我想得到一个类型错误,就像 Python3 一样。

最佳答案

不是使用 .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 不同

关于python - 防止变量关键字参数中的拼写错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28260559/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com