A loop that fetches 50 URLs one after another spends nearly all its time waiting. concurrent.futures.ThreadPoolExecutor lets several of those waits happen at the same time, with barely any change to the code.
from concurrent.futures import ThreadPoolExecutor
import urllib.request
def status(url):
with urllib.request.urlopen(url, timeout=10) as r:
return url, r.status
urls = ["https://example.com/", "https://example.org/"]
with ThreadPoolExecutor(max_workers=8) as pool:
for url, code in pool.map(status, urls):
print(code, url)
pool.map works like the built in map, but up to eight calls run at once. Results still come back in the order of the input, which keeps the output predictable. In a quick test with a function that sleeps half a second, eight calls took 0.5 seconds in total instead of 4.
Threads help when the work is waiting: network, disk, subprocesses. For pure number crunching they don’t, because only one thread runs Python code at a time. I’d swap in ProcessPoolExecutor for that.
Be careful with errors. If one call raises, the exception comes out of map when you reach that result, and the loop stops there. Catch exceptions inside the function and return them as a value if one bad URL shouldn’t end the run. And keep max_workers polite when it’s someone else’s server.
Further reading: ThreadPoolExecutor