Home > database >  lazy evaluation python data structure
lazy evaluation python data structure

Time:12-13

I have the following code:

def get_data():
    return {"a": 1, "b":2}


def main():
    lazy_dic = lambda : get_data()
    a_value = lazy_dic()["a"]
    b_value = lazy_dic()["b"]

I want the get_data() function to be evaluated only once, and only the first time it is called. when calling the assignment for b_value, I don't want the get_data function to be called again, but in this example, it is called twice.

Is there a simple way to achieve what I am looking for?

*Edit

I write the code to show a simple example, In my use case, I want the dictionary only to be evaluated when it is accessed. (let's say the get_data takes the data from a database)

CodePudding user response:

Maybe try something like this (cache)

from functools import cache

@cache
def get_data():
    return {"a":1, "b":2}

Here's a full example checking the status of the cache with cache_info():

from functools import cache

@cache
def get_data():
    return {"a":1, "b":2}

get_data.cache_info()
# Out: CacheInfo(hits=0, misses=0, maxsize=None, currsize=0)

lazy_dic = lambda : get_data()

lazy_dic()["a"]
# Out: 1

get_data.cache_info()
# Out: CacheInfo(hits=0, misses=1, maxsize=None, currsize=1)

CodePudding user response:

OK here is the solution for the problem.

def get_data():
   print("I got called only one time")
   return {"a":1,"b":2}

def main():
   lazy_dix = (lambda a: a)(get_data())
   output1 = lazy_dix["a"]
   output2 = lazy_dix["b"]
   print("output1 : ",output1,"\noutput2 : ",output2)

main()

#OUTPUT
I got called only one time
output1 :  1 
output2 :  2
  • Related