Python 3.4+Async programmingterm
asyncio.BoundedSemaphore
synchronization
A semaphore that never lets its counter rise above the initial value: an extra release() raises ValueError instead of silently letting one more task through.
Syntax
sem = asyncio.BoundedSemaphore(value=1)
Used correctly it behaves exactly like asyncio.Semaphore; the difference is the error: Semaphore(2) after a stray release() admits three tasks, whereas BoundedSemaphore(2) immediately reports 'released too many times'. So for 'at most N at once' it is the sensible default — a counting bug shows up at once, not a week later under load.
Examples
import asyncio
async def main():
sem = asyncio.BoundedSemaphore(1)
async with sem:
await asyncio.sleep(0.01)
try:
sem.release() # лишний release
except ValueError as e:
print(e) # → BoundedSemaphore released too many times
asyncio.run(main())
See also
Open in the full glossarydocs.python.orgReport an inaccuracy