运行函数时更改装饰器参数?

时间:2013-06-12 21:00:44

标签: python decorator

我写了一个装饰器工厂,它接受输入和输出文件名:

def run_predicate(source, target):
    '''This is a decorator factory used to test whether the target file is older than the source file .'''
    import os    
    def decorator(func):
        '''This is a decorator that does the real work to check the file ages.'''
        def wrapper(*args, **kwargs):
            '''Run the function if target file is older than source file.'''
            if not os.path.exists(target) or \
               os.path.getmtime(source) > os.path.getmtime(target):
                return func(*args, **kwargs)
            else:
                return None
        return wrapper
    return decorator

和装饰功能:

@run_predicate("foo.in", "foo.out")
def foo(a, b):
    return a + b

这基本上设置为仅在输入文件晚于输出文件更新时才运行foo()。问题是我想根据不同的情况动态地改变依赖关系,即输入和输出文件名。例如,如果foo()"foo.in"更新,有时我想运行"foo.out";其他时候,我只想在"spam.in""spam.out"更新时运行它,等等。如何在不更改功能定义或其装饰的情况下执行此操作?

0 个答案:

没有答案
相关问题