The Python Oracle

How can I get the arguments I sent to ThreadPoolExecutor when iterating through future results?

--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------

Music by Eric Matyas
https://www.soundimage.org
Track title: Life in a Drop

--

Chapters
00:00 How Can I Get The Arguments I Sent To Threadpoolexecutor When Iterating Through Future Results?
00:53 Accepted Answer Score 18
01:04 Answer 2 Score 0
01:14 Thank you

--

Full question
https://stackoverflow.com/questions/6336...

--

Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...

--

Tags
#python #python3x #multithreading #concurrency #concurrentfutures

#avk47



ACCEPTED ANSWER

Score 18


While submitting the task, you could create a mapping from future to its proxy.

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    future_proxy_mapping = {} 
    futures = []
    for proxy in proxies:
        future = executor.submit(is_proxy_alive, proxy)
        future_proxy_mapping[future] = proxy
        futures.append(future)
    
    for future in futures:
        proxy = future_proxy_mapping[future]
        print(proxy)
        print(future.result())



ANSWER 2

Score 0


You have appended to futures in the same order that you read from proxies, so they are in the same order, so you can just zip them up.

with concurrent.futures.ThreadPoolExecutor(max_workers=5) as executor:
    futures = []
    for proxy in proxies:
        future = executor.submit(is_proxy_alive, proxy)
        futures.append(future)
    
    for future, proxy in zip(futures, proxies):
        # do whatever