I am looking for a way to create a decorator to have a function parameter that actually uses the variable passed to the function, its wrapping.
for example, let's say that I have
@cache_decorator("my_key_{}".format(foo)) def my_function(foo, bar): pass @cache_decorator("another_key_{}_{}".format(foo, bar) def another_function(user, foo, bar): pass
The goal is to write a caching shell. the decorator will need a cache key, but the key will include the variables passed to the function, and will be different for each function that it wraps.
Ideally, this allows the decorator to check the cached value for the given key, and if it is not found, execute the function to get the value and cache it. Thus, if the value is in the cache, it does not execute the code that creates the value (i.e. My_function). if it is not found, it executes my_function and stores the result in the cache and also returns it.
Another alternative would be something like blocks:
def my_function(foo, bar): cache_value("my_key_{}".format(foo),{block of code to generate value that is only called if necessary})
in Objective-C or js, this will be a block, so I can keep the value generation both locally defined and mutable, but only necessary if necessary. I'm too new to python to fully understand how to do this with its close check.
Thanks!
Update
While the solution below worked for decorators, I ended up on a block-like route due to the additional metadata needed to attach to each cache entry to make sure it might be invalid. The presence of this metadata defined during value generation (as opposed to the internal caching function) is easier to maintain. It looks like this:
def my_function(foo, bar): def value_func(): return code_to_generate_value_using_foo_bar return get_set_cache(key, value_func, ...) def get_set_cache(key, value_function, ...): value = cache.get(key) if value is None: value = value_function() cache.set(key, value) return value