0

I've the following functions

def query_url_input() -> Dict:
    # code
    # fetch input from another url
    return output_dict

def process_query(queryid: str) -> Dict:
   d = query_url_input()    # how to call this only once
   # code uses requests/urllib with key value input of d + queryid to return results
   value = results
   return {queryid: value}

if __name__ == '__main__':
   for item in ['1.2', 'w.2', 'c.q']
       output = process_query(queryid=item)

In the above sample code, the function process_query is called multiple times and query_url_input is also called from process_query multiple times. But for all the calls query_url_input returns the same output. So I want to call query_url_input only once(first call) and store d for later calls. I would like to ask for suggestions on how to do this using a Class.(I've used classes in MATLAB for performing similar tasks, but I am not sure how this has to be done in Python).

Natasha
  • 1,111
  • 5
  • 28
  • 66

1 Answers1

1

You can use the lru_cache decorator (python >= 3.2) for this purpose.You can see an example here.

import functools
 
@functools.lru_cache()
def query_url_input():
    print("query_url_input")
    output_dict = dict()
    return output_dict

def process_query(queryid):
    print("process_query")
    d = query_url_input()
    value = "Some results"
    return {queryid: value}

if __name__ == '__main__':
    for item in ['1.2', 'w.2', 'c.q']:
        output = process_query(queryid=item)

output:

process_query
query_url_input
process_query
process_query
Neabfi
  • 4,411
  • 3
  • 32
  • 42