I am using function objects as dictionary keys. I am doing that because I need to cache the result of these functions. This is roughly the code I am using:
# module cache.py:
calculation_cache = {}
def cached(func):
# func takes input as argument
def new_function(input):
try:
result = calculation_cache[(func, input)]
except KeyError:
result = func(input)
calculation_cache[(func, input)] = result
return result
return new_function
# module stuff.py
@cached
def func(s):
# do something time-consuming to s
# ...
return result
I could use func.__module__ + func.__name__ instead of func, but if func works fine, I'd rather use it since I'm afraid of possible name conflicts (e.g., for lambda functions or nested functions or functions that were replaced by another with the same name, etc.)
This seems to work fine, but I suspect that this may cause problems in some hard-to-test situations.
For example, I am concerned about a function being somehow deleted and another function reusing its memory space. In this case, my cache would be invalid, but it would not know about it. Is this a valid concern? If so, is there any way to address it?
Can a function be deleted? Does reloading a module move a function to a new address (thus changing its hash value, and releasing the old memory address for new functions)? Can someone (for some strange reason) simply delete a function defined in a module (again making the memory available for a new function)?
If it is only safe to do this with functions explicitly defined with def, then I can prohibit the use of cached except as a decorator (I don't know how to enforce it, but I can just document it in the cached docstring).