我有一个连续的模拟模型,它由python包中几个模块的数百个python函数组成,每个模块代表{{1}}形式的模型组件,其中y = f(t)
是当前的模特时间。
在给定的时间步长中,这些函数在其他函数中被调用多次,因此有一个非常简单的缓存可以保存当前时间步的函数结果。我有两个问题:
这是我到目前为止所做的:
t
我想我已经将缓存实现为一种装饰器,但我没有使用# Imports all functions in the python package
# (__init__.py start imports them)
import model
def cache(f):
t1 = None
y = None
def cached_func(t2):
if t1 != t2:
t1 = t2
y = f(t2)
return y
return cached_func
# Iterate through each function and apply the cache
for name, obj in model.__dict__.items():
obj = cache(obj)
语法来应用它,因为它会在模型代码中添加数百行。相反,我是在模型集成之前完成的。
当我测试@decorator
函数并调用结果时,我最终得到:
cache
这可能有意义,但我认为t1将作为Traceback (most recent call last):
File "C:\Users\pbreach\Anaconda3\lib\site-packages\IPython\core\interactiveshell.py", line 2885, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-14-c0c62e8a0eaa>", line 1, in <module>
cached_test_func(3)
File "<ipython-input-9-780e50b4626f>", line 5, in cached_func
if t1 == t2:
UnboundLocalError: local variable 't1' referenced before assignment
的全局。
我的第二个问题是模型函数实际上不会被修改,因为它们将从已经在行cached_func
中导入的其他函数调用。这是真的,除了装饰各自文件中的所有功能外,我怎么能绕过这个呢?