python - 如何从另一个函数的 kwargs 中弹出元素?

标签 python python-3.x keyword-argument

我有一个函数负责从其他几个函数的 kwargs 中获取数据。

其他函数将它们自己的 kwargs 连同一个 keep 参数传递给这个函数,该参数决定是否将这些属性保留在 kwargs 中——即是否使用 getpop

def _handle_kwargs(keep, **kwargs):
    # keep: whether to keep the kwarg when we're done with it (i.e. get or pop)
    if keep: func = getattr(kwargs, 'get')
    else: func = getattr(kwargs, 'pop')

    # get or pop some kwargs individually
    debug = func('debug', False)
    assert isinstance(debug, bool)
    ...
    # repeated for several different possible kwargs
    return debug, some_other_kwarg, ...

def normal_function(**kwargs)
    debug, some_other_kwarg = _handle_kwargs(False, **kwargs)

从 kwargs 获取值工作正常。但是,如果我尝试 pop kwargs,那么它们仍然存在于原始函数的 kwargs 中。我怀疑这是因为 _handle_kwargs 只是在修改它自己的 kwargs。

如果我使用 pop,我如何确保 kwargs 被删除,即使它来自另一个函数?

最佳答案

我怀疑你是否可以传递给 **kwargs,因为它似乎是按值传递的,但是如果可以修改内部函数,你可以将 kwargs 作为普通字典传递,即没有 * *

def test(x):
    print(x)
    x.pop('test')
    print(x)

def real(**kwargs):
    test(kwargs)
    print(kwargs)

real(test='nothing', real='something')

输出

{'test': 'nothing', 'real': 'something'}
{'real': 'something'}
{'real': 'something'}

关于python - 如何从另一个函数的 kwargs 中弹出元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57416801/

相关文章:

python - 如果数字介于两个值之间则返回 [Python]

当提供 -w 参数时,python 2to3 不会更改 Huey 文件

ruby - 为什么关键字参数必须作为带有符号键的散列传递,而不是 Ruby 中的字符串键?

python - 如果为真 : turn following values to True in list of booleans until nth position after True is reached

python - 使用嵌套 if 的替代方法

python-3.x - PySide2 v5.12 : Creating a FileDialog on a click of a button

python - 扭曲的 python : the correct way to pass a kwarg through the component system to a factory

python - 尝试理解 Python 中的可选参数、列表参数和命名参数

Python编译/解释过程

python - 如何迭代 python 中的列以查找键值的匹配项?