pip install joblib★No required deps. Python 3.9+. (Often already present via scikit-learn.)from joblib import Parallel, delayed Parallel(n_jobs=4)(delayed(f)(x) for x in range(10))★The core idiom:delayed(f)(x)packages a call without running it;Parallel(n_jobs=)runs the whole generator across workers and returns a list in order.import math Parallel(n_jobs=-1)(delayed(math.sqrt)(i**2) for i in range(10))★n_jobs=-1uses all cores;-2= all but one. Results come back in the same order as the input.# delayed(f(x)) -> WRONG: runs f now, in the main processgotchaIt'sdelayed(f)(x), notdelayed(f(x)). The first defers the call; the second executes it immediately.
results = Parallel(n_jobs=4)( delayed(process)(item) for item in dataset)★Map a function over a collection — the 90% use case. Each call must be a picklable, ideally pure function.Parallel(n_jobs=4)(delayed(f)(x, y, key=z) for x,y,z in args)Positional and keyword args pass straight throughdelayed(f)(...).with Parallel(n_jobs=4) as parallel: a = parallel(delayed(f)(x) for x in xs) b = parallel(delayed(g)(y) for y in ys)★Reuse oneParallelcontext across several batches to keep the worker pool warm (avoids re-spawning processes).# nested loops: parallelize the OUTER loop onlyDon't nestParallelcalls naively — joblib coordinates nesting, but usually parallelize the coarsest loop and keep inner work sequential.