我写了一个装饰器工厂,它接受输入和输出文件名:
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()
if "foo.in"
is new than "foo.out"
; 其他时候,我只想在"spam.in"
比"spam.out"
等更新时运行它。如何在不更改函数定义或其装饰的情况下做到这一点?