Note that there are some explanatory texts on larger screens.

plurals
  1. POpython decorator parameter using variable from function its wrapping
    primarykey
    data
    text
    <p>I'm looking for a way to create a decorator to have a function parameter that actually uses a variable passed into the function its wrapping.</p> <p>for example, lets say I have</p> <pre><code>@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 </code></pre> <p>The goal is to write a caching wrapper. the decorator will need the cache key, but the key is going to include variables passed into the function, and be different for each function it wraps.</p> <p>Ideally, this lets the decorator do a check for a cached value for a given key, and if its not found execute the function to get the value and cache it. That way if the value is in the cache, its not executing the code that creates the value (i.e. my_function). if its not found, it executes my_function and stores the result in the cache and also returns it.</p> <p>Another alternative would be something akin to blocks:</p> <pre><code>def my_function(foo, bar): cache_value("my_key_{}".format(foo),{block of code to generate value that is only called if necessary}) </code></pre> <p>in Objective-C or js, this would be a block so i can keep the value generation both locally defined and changeable, but only executed if necessary. I'm too new to python to fully grasp how to do this with its verison of closures.</p> <p>Thanks!</p> <p><strong>Update</strong><br> While the solution below worked for decorators, I ended up going the block-like route because of the extra metadata required to attach to each cache entry to ensure it can be properly invalidated. Having this metadata defined with the value generation (as opposed to inside the caching function) is easier to maintain. This looks like:</p> <pre><code>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 </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload