Reference¶
Frequency tracking and throttling utilities.
- class Base(bucket=None)¶
An abstract base for all classes implementing frequency check mechanisms.
- Parameters
bucket (list) – Used to track state.
- property bucket¶
Storage tracking values.
Warning
This object is solely internally managed. Changes to it may lead to unexpected behavior.
- count(key=None)¶
Get the number of values adhering to the key.
- Parameters
key (func) – Only count items abiding to this.
- left(limit, **kwargs)¶
Get the number of space left according to the limit.
- check(delay, limit, value, key=None, bypass=False, excess=None, rate=1)¶
Check if the valve is open and track the value accordingly.
- Parameters
delay (float) – Wait for this many seconds before discarding.
limit (int) – Only track the value if the current size is less than this.
value (any) – Something to track, adapt it to your
key
needs.key (func) – Only account for values adhering to this.
bypass (bool) – Track the value regardless of whether it exceeds limit.
excess (int) – Amount of extra values allowed for tracking.
rate (float) – Multiplied against the delay after any modifications to it.
Note
Using
excess
will not affect the result, but will reduce the delay after which extra values are discarded. The formula for the rate-affecting delay is(left + excess) / limit
.
- class Valve(*args, loop=None, **kwargs)¶
Bases:
Base
Can only have
limit
ofkey
’d values everyrate
seconds.- Parameters
loop (asyncio.AbstractEventLoop) – Signal the use of
asyncio
instead ofthreading
.
- class Static(*args, time=<built-in function monotonic>, **kwargs)¶
Bases:
Base
Works like
Valve
, except it doesn’t use any concurrent utilities.- Parameters
time (func) – Used for calculating expiry timestamps.
Note
Insourcing time calculations results to
check()
being almost 3x slower.
- wrap(*args, strict=False, apply=None, valve=None, **kwargs)¶
Decorator for controlling execution.
- Parameters
strict (bool) – Account for arguments when deciding whether to throttle. Similar to
functools.lru_cache()
returning the same result for the same arguments.apply (func) – Takes the arbitrary amount of positional and keyword arguments passed and returns a single value used for state tracking.
valve (Base) – Used for deciding whether to prevent execution.
Additional arguments will be used as defaults for
check()
.