函数装饰器,将指定函数参数的值记录在可访问的python对象中

时间:2018-09-13 08:21:04

标签: python python-decorators

我正在尝试创建一个函数装饰器,该函数装饰器将指定值的函数参数记录在可访问的python对象中。我已经可以使用代码了,但是我缺少完成这一工作的一部分。

首先,我有对象日志,可以在其中正确保存内容:

class Borg:
    _shared_state = {}

    def __init__(self):
        self.__dict__ = self._shared_state

class Log(Borg):

    def __init__(self):
        Borg.__init__(self)
        if not hasattr(self, 'tape'):
            self.tape = []

    def add(self, this):
        self.tape.append(this)

    def __str__(self):
        return '\n'.join([str(line) for line in self.tape])

然后我有一个通用调用对象和装饰器实现(缺少代码):

import inspect
import functools

class Call:

    def __init__(self, name, **saved_arguments):
        self.name = name
        self.saved_arguments = saved_arguments

    def __str__(self):
        return f'Call(name={self.name}, saved_arguments={self.saved_arguments})'

def record(func, save_args_names=None):
    if save_args_names is None:
        save_args_names = {}
    name = func.__name__
    args = inspect.getfullargspec(func).args
    if save_args_names and not set(save_args_names).issubset(set(args)):
        raise ValueError(f'Arguments not present in function: {set(save_args_names) - set(args)}')
    log = Log()

    @functools.wraps(func)
    def wrapper(*func_args, **func_kwargs):
        # **here** I am missing something to replace 0 with the correct values!
        saved_arguments = {a: 0 for a in save_args_names}
        log.add(Call(name, **saved_arguments))
        return_value = func(*func_args, **func_kwargs)
        return return_value

    return wrapper

要对此进行测试,我设置了以下功能:

def inner(x, add=0):
    return sum(x) + add

def outer(number, add=0):
    x = range(number)
    return inner(x, add)

和基本用例(不保存参数)有效:

inner = record(inner)
print(outer(1), outer(2), outer(3))
print(Log())

它正确输出:

0 1 3
Call(name=inner, saved_arguments={})
Call(name=inner, saved_arguments={})
Call(name=inner, saved_arguments={})

我所缺少的是使用此案例的一种方式:

inner = record(inner, save_args_names=['x'])
print(outer(1), outer(2), outer(3))
print(Log())

输出:

0 1 3
Call(name=inner, saved_arguments={'x': range(0, 1)})
Call(name=inner, saved_arguments={'x': range(0, 2)})
Call(name=inner, saved_arguments={'x': range(0, 3)})

这也应适用于关键字参数,例如:

inner = record(inner, save_args_names=['x', 'add'])
print(outer(1, 2), outer(2, 3), outer(3, 4))
print(Log())

应输出:

2 4 7
Call(name=inner, saved_arguments={'x': range(0, 1), 'add': 2})
Call(name=inner, saved_arguments={'x': range(0, 2), 'add': 3})
Call(name=inner, saved_arguments={'x': range(0, 3), 'add': 4})

我觉得我已经很接近了,inspect库应该可以帮助我解决这个问题,但是一点帮助将不胜感激!

1 个答案:

答案 0 :(得分:2)

您要寻找的功能是Signature.bind。像这样定义您的wrapper函数:

@functools.wraps(func)
def wrapper(*func_args, **func_kwargs):
    signature = inspect.signature(func)
    bound_args = signature.bind(*func_args, **func_kwargs)
    saved_arguments = {a: bound_args.arguments[a] for a in save_args_names}

    log.add(Call(name, **saved_arguments))
    return_value = func(*func_args, **func_kwargs)
    return return_value