Skip to content

Instantly share code, notes, and snippets.

Created July 19, 2017 19:55
What would you like to do?
Dinking around with decorators
import time
import json
import random
from functools import wraps
def only_if(condition, args_=None, *, pass_value=False, cache=False):
_fn = condition if callable(condition) else lambda: condition
if args_ is None:
args_ = tuple()
elif not isinstance(args_, tuple):
args_ = (args_,)
def _only_inner(func):
cache_should_run = _fn(*args_)
def wrapper(*args, **kwargs):
if cache_should_run and cache:
if pass_value:
args = (cache_should_run, *args,)
return func(*args, **kwargs)
should_run = _fn(*args_)
if should_run:
if pass_value:
args = (should_run, *args)
return func(*args, **kwargs)
# does not run
return wrapper
return _only_inner
def random_run():
return random.randint(0, 3)
def check_config(path, feature):
with open(path, 'rb') as ins_file:
data = json.load(ins_file)
return data.get(feature, None)
@only_if(random_run, pass_value=True, cache=False)
def test_this(v):
return f'x {v}'
@only_if(check_config, (r'./config.json', 'feature_a'), pass_value=True, cache=True)
def test_config_read(value):
return f'cached config {value}'
@only_if(check_config, (r'./config.json', 'feature_a'), pass_value=True)
def test_no_cache_config_read(value):
return f'live config {value}'
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment