Use pool.starmap(func, iterable_of_tuples) (built into Python 3.3+) to unpack each tuple of positional arguments as func(*args) across worker processes, functools.partial(func, fixed_arg=val) with pool.map() when only one argument varies while the rest stay constant, or concurrent.futures.ProcessPoolExecutor().map(func, arg1_list, arg2_list) when passing separate parallel iterables directly without zipping them manually.
Basic Example
from functools import partial
from multiprocessing import Pool
def power_and_offset(base: int, exp: int, offset: int = 0) -> int:
return (base ** exp) + offset
if __name__ == "__main__":
# 1. Recommended (Multiple varying positional arguments): `pool.starmap()`
tasks = [(2, 3, 10), (3, 2, 5), (4, 3, 0)]
with Pool(processes=4) as pool:
results = pool.starmap(power_and_offset, tasks)
print(results)
# Output: [18, 14, 64]
# 2. Recommended (One varying argument + fixed arguments/kwargs): `functools.partial()` + `pool.map()`
fixed_fn = partial(power_and_offset, exp=2, offset=100)
with Pool(processes=4) as pool:
partial_results = pool.map(fixed_fn, [1, 2, 3, 4])
print(partial_results)
# Output: [101, 104, 109, 116]
Key Details & Edge Cases
- Always guard
Pool()creation withif __name__ == "__main__"::- On Windows and macOS (
spawnstart method), worker processes re-import the main script. Creating aPoolat module top level withoutif __name__ == "__main__":causes infinite recursive process spawning and raisesRuntimeError: An attempt has been made to start a new process before the current process has finished its bootstrapping phase.
- On Windows and macOS (
- Never pass a
lambdawrapper topool.map(lambda x: fn(*x), tasks):multiprocessingserializes functions and arguments usingpickle, which cannot serializelambdafunctions or nested local functions (AttributeError: Can't pickle local object '<lambda>'). Always define worker functions at top-level module scope, or usepool.starmap()/functools.partial().
- Passing keyword arguments (
**kwargs) per task:pool.starmap()only unpacks positional*argstuples—it does not accept per-item**kwargsdictionaries. To pass varying keyword arguments per task, either:- Accept a single
dictparameter (def worker(cfg: dict): ...) and callpool.map(worker, list_of_dicts), or - Use a small top-level helper:
def _apply_kwargs(item: tuple[tuple, dict]): args, kwargs = item return power_and_offset(*args, **kwargs)
- Accept a single
- Lazy streaming for huge iterables (
pool.imap/pool.imap_unorderedvs.pool.starmap):pool.starmap()materializes the entire input iterable into a list in memory up front. If you are streaming millions of argument tuples from a generator, pack each item into a tuple and unpack inside a top-level wrapper withpool.imap(wrapper, tuple_gen, chunksize=64)to keep memory bounded and receive results lazily as workers finish.
- Combining
zip()withpool.starmap()for separate column lists:- If your arguments live in separate lists (
bases = [2, 3, 4],exps = [3, 2, 3]), passzip(bases, exps)directly topool.starmap(power_and_offset, zip(bases, exps))—or pass them directly as multiple iterables toProcessPoolExecutor.map(power_and_offset, bases, exps).
- If your arguments live in separate lists (
Comparison of Multi-Argument Parallel Mapping Approaches in Python
| Method | Supports Multiple Varying Args? | Supports **kwargs? |
Lazy / Streaming Execution? | Best Used When |
|---|---|---|---|---|
pool.starmap(, tuples) (Recommended) |
Yes (*args unpacked per tuple) |
No (positional only) | No (converts iterable to list) | Passing varying positional argument tuples (a, b, c) across multiprocessing.Pool workers. |
pool.map(partial(fn, k=v), items) (Recommended for constants) |
No (1 varying arg + fixed args/kwargs) | Yes (fixed keyword args in partial) |
No (converts iterable to list) | Mapping over a single varying iterable while sharing constant configuration parameters. |
ProcessPoolExecutor().map(fn, iter1, iter2) |
Yes (accepts multiple parallel iterables directly) | No (positional only) | Yes (yields results lazily in order) | Modern concurrent.futures codebases with separate parallel argument lists and no manual zip(). |
pool.imap(tuple_wrapper, gen, chunksize=N) |
Yes (via single tuple arg unpacked in wrapper) | Yes (if tuple holds (args, kwargs)) |
Yes ($O(1)$ memory streaming) | Processing millions of multi-argument tasks from a generator without loading all tasks into RAM. |
You must log in or register to comment.
