0

I have function that will get the data from the cache if it exists else it will query the DB and save it in the cache.

def get_ref_from_cache_or_db(obj, key, duration=60):
data = get_routes_from_cache(key=key)
if data:
    response = json.loads(data)
else:
    response = obj.fetch().to_dict()
    set_routes_to_cache(key=key, duration=duration, value=json.dumps(response))
return response

Sometimes I have to return different results from the same object, for example I need to call

response = obj.fetch().to_dict()

or

response = obj.fetch().to_other_dict()

If it were a simple simple function call my code would simply be:

def get_ref_from_cache_or_db(func, key, duration=60):
    data = get_routes_from_cache(key=key)
    if data:
        response = json.loads(data)
    else:
        response = func()
        set_routes_to_cache(key=key, duration=duration, value=json.dumps(response))
    return response

But in this case I don't know how to pass the function that will be called from the object returned from another function, i.e i want to call something like this get_ref_from_cache_or_db(obj.fetch.to_dict, key, duration). I don't want to call the fetch() beforehand because it will always get the data from the DB.

1 Answer 1

1

If you want to call the fetch() only when needed, you can use a lambda: get_ref_from_cache_or_db(lambda: obj.fetch().to_dict() , key, duration)

Sign up to request clarification or add additional context in comments.

2 Comments

Can you please explain more how this works?
A lambda is a one liner function definition, so here you create a function that calls your function. I would suggest to read more about lambdas.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.