Run multiple async functions with limited concurrency
Python port of the popular Node.js p-limit package. Uses asyncio to run async (and sync) functions with a configurable concurrency limit.
pip install plimit
or with uv:
uv add plimit
import asyncio
from plimit import p_limit
async def main():
limit = p_limit(2) # max 2 concurrent tasks
async def fetch(url):
# ... your async work
return url
results = await asyncio.gather(
limit(fetch, "https://example.com/1"),
limit(fetch, "https://example.com/2"),
limit(fetch, "https://example.com/3"),
)
print(results)
asyncio.run(main())Returns a Limiter instance.
concurrency(int) — Maximum number of async functions running at the same time. Minimum:1.reject_on_clear(bool) — WhenTrue,clear_queue()rejects pending futures withClearQueueErrorinstead of silently discarding them. Default:False.
Schedule fn(*args) to run under the concurrency limit. Returns an awaitable that resolves to the return value of fn.
fncan be an async function or a regular function.- Extra positional arguments are forwarded to
fn.
result = await limit(my_async_fn, arg1, arg2)Number of functions currently executing.
Number of functions waiting in the queue.
Get or set the concurrency limit at runtime. When increased, queued tasks start immediately up to the new limit.
limit.concurrency = 10 # increase concurrency dynamicallyDiscard pending functions that have not started yet.
- If
reject_on_clear=True, pending futures are rejected withClearQueueError. - Does not cancel functions that are already running.
Process an iterable through fn with limited concurrency. The mapper receives (item, index).
results = await limit.map([1, 2, 3], async_transform)Convenience wrapper — returns a new async function that calls fn with limited concurrency.
from plimit import limit_function
limited_fetch = limit_function(fetch, concurrency=3)
result = await limited_fetch(url)Exception raised for pending tasks when clear_queue() is called with reject_on_clear=True.
JavaScript (p-limit) |
Python (plimit) |
|---|---|
const limit = pLimit(5) |
limit = p_limit(5) |
await limit(fn, ...args) |
await limit(fn, *args) |
limit.activeCount |
limit.active_count |
limit.pendingCount |
limit.pending_count |
limit.concurrency = 10 |
limit.concurrency = 10 |
limit.clearQueue() |
limit.clear_queue() |
limit.map(iter, fn) |
await limit.map(iter, fn) |
limitFunction(fn, opts) |
limit_function(fn, concurrency=N) |
AbortError on clear |
ClearQueueError on clear |
Python 3.10+
MIT