betty.concurrent module

Provide utilities for concurrent programming.

class betty.concurrent.Ledger

Bases: object

Lazily create locks by keeping a ledger.

The ledger lock is released once a transaction lock is acquired.

This is thread-safe, which means you can safely use this between different threads.

__init__(ledger_lock: Lock)
ledger(transaction_id: Hashable) Lock

Ledger a new lock for the given transaction ID.

class betty.concurrent.Lock

Bases: ABC

Provide an asynchronous lock.

abstractmethod async acquire(*, wait: bool = True) bool

Acquire the lock.

abstractmethod async release() None

Release the lock.

final class betty.concurrent.RateLimiter

Bases: object

Rate-limit operations.

This class implements the Token Bucket algorithm.

This is thread-safe, which means you can safely use this between different threads.

__init__(maximum: int, period: int = 1, /)
async is_available() bool

Whether an operation may be performed (again).

async wait() None

Wait until an operation may be performed (again).

final class betty.concurrent.ThreadSafeLock

Bases: Lock

An asynchronous thread-safe lock.

This is thread-safe, which means you can safely use this between different threads.

__init__(lock: lock | None = None, /)
async acquire(*, wait: bool = True) bool

Acquire the lock.

property lock: lock

The underlying, synchronous lock.

async release() None

Release the lock.

async betty.concurrent.backoff() AsyncIterator[int]

Implement exponential backoff.

The returned iterator sleeps after every iteration, increasing the duration with every iteration, up to a limit.

Usage:

async for iteration in backoff():
  if success:
     return  # Or break.