python - 标准库中有Python inspect.getcallargs 的逆操作吗?

标签 python

有没有办法从 inspect.getcallargs(func) 的返回值返回到一个 *args, **kw 对,它实际上可以用来调用 func?

用例:假设我正在编写一个装饰器,我想通过名称更改函数的特定参数。下面是执行此操作的一些代码的开头:

@fix_x
def a(x):
    print x

@fix_x
def b(**q):
    print q['x']

def fix_x(func):
    def wrapper(*args, **kw):
        argspec = inspect.getargspec(func)
        callargs = inspect.getcallargs(func, *args, **kw)
        if 'x' in callargs:
            callargs['x'] += 5
        elif 'x' in callargs[argspec.keywords]:
            callargs[argspec.keywords]['x'] += 5
        # ...and now I'd like a simple way to call func with callargs...?

(实际上我在构建它们和想与它们通话之间对 callargs 做一些更精细的事情,但这应该让我知道我在寻找什么。)

最佳答案

不,目前还没有一个好的方法来做到这一点,但是它正在为 Python 3.3 工作!

参见 PEP 362 -- Function Signature Object了解这项新功能的工作原理。

关于python - 标准库中有Python inspect.getcallargs 的逆操作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10940871/

相关文章:

python - dict.__setitem__(key, x) 是否比 dict[key] = x 慢(或快),为什么?

python - 如果列全部为 nan,则使 numpy.nanargmin 返回 nan

python - Scrapy xpath utf-8 文字

python - 计算 networkx 中两个图 'edge wise' 之间的差异

python - Python 字典中的键盘错误

python 数据库抽象来存储未腌制的数据结构

Python:将随机数放入列表中

python - pip安装virtualenvwrapper-powershell不起作用

python 二进制到十六进制的转换

python - Pytest - pytest_generate_tests 中的 tmpdir_factory