Mehdi Khlifi
Mehdi Khlifi

Reputation: 415

Pass an object's function as parameter to another function

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.

Upvotes: 0

Views: 152

Answers (1)

pygame
pygame

Reputation: 131

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)

Upvotes: 1

Related Questions