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).

1 Answer 1

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
Sign up to request clarification or add additional context in comments.

Comments

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.