Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Let function return while other function finishes using threads in Python?

I have a function that modifies data and returns it to the user after modifying. At this point that is the information the user needs so I want to return it ASAP, but I need that modified_data to make calls to an API and upload data it to a DB, but this can be done in the background. Is there a way to have modify_data() return while letting get_more_data() finish?

I tried using threading, but it waits until get_more_data() returns before returning modify_data. I’ve also considered placing both into seprate threads in a parent function but I need modify_data() to generate the data for get_more_data() first.

import threading
def modify_data(data):
    #modify data... example
    modified_data = [item+1 for item in data]
    th = threading.Thread(target=get_more_data(set(modified_data)))
    th.start()
    return modified_data

def get_more_data(data):
    #call api for more data
    #upload to DB

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

In this line

th = threading.Thread(target=get_more_data(set(modified_data)))

you are executing the get_more_data method to get the target.
Try

th = threading.Thread(target=get_more_data, args=(set(modified_data),))

If you want to learn more about this, take a look here.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading