我写了一个装饰器工厂,它接受输入和输出文件名:
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"
更新时运行它,等等。如何在不更改功能定义或其装饰的情况下执行此操作?