brewedbits.dev

Personal blog with guides and news on selfhosting, Linux and AI, from the Netherlands

nextDash nextdash --aboutYour bookmarks. Your terminal. checks your links knows your Docker host one container, no cloudLive demo →nextdash.cc ↗

Tip: Python's ThreadPoolExecutor.map runs slow network calls side by side

Python
~/tips/tip-python-threadpoolexecutor-map

from concurrent.futures import ThreadPoolExecutor

Speed up a script that waits on many downloads or API calls with a thread pool.

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

More Python tips import asyncio from enum import StrEnum, auto except* ValueError as eg: import pytest pytest --maxfail=2 All Python tips (107) All topics

Link