ObjectPool API Documentation

class Reusable[source]

Bases: ABC

Abstract base class for reusable objects.

This class defines a standard interface for objects that can be managed by an object pool. Subclasses must implement the use and reset methods to define the behavior for using and resetting the object.

Responsibilities: - use: Defines the primary action or functionality of the reusable object. - reset: Resets the state of the object, preparing it for reuse.

Classes inheriting from Reusable should encapsulate reusable resources or functionalities that can be pooled, such as database connections, threads, or UI components.

abstractmethod use()[source]

Perform the primary action of the reusable object.

This method must be implemented by subclasses to define the main functionality of the object when it is borrowed from the pool.

abstractmethod reset()[source]

Reset the reusable object to its initial state.

This method must be implemented by subclasses to clear or reset the object’s state, preparing it for reuse when returned to the pool.

class ConcreteReusable(id_)[source]

Bases: Reusable

Concrete implementation of the Reusable interface.

This class represents a reusable object with an identifier and state.

Parameters:

id_ (str)

__init__(id_)[source]

Initialize a reusable object with a unique identifier.

Parameters:
  • id – A unique identifier for the reusable object.

  • id_ (str)

use()[source]

Perform the primary action of the reusable object.

Raises:

RuntimeError – If the object is already in use.

reset()[source]

Reset the reusable object to its initial state.

Resets the in_use state to False.

class ObjectPool[source]

Bases: Generic[T]

Generic Object Pool for managing reusable objects.

Manages a pool of reusable objects, allowing objects to be borrowed, returned, and reused. Ensures FIFO behavior for returning and borrowing.

__init__()[source]

Initialize an empty object pool.

add_object(obj)[source]

Add a reusable object to the pool.

Parameters:

obj (TypeVar(T, bound= Reusable)) – The reusable object to add.

Raises:

ValueError – If the object is None or already in the pool.

borrow_object()[source]

Borrow an object from the pool.

Return type:

TypeVar(T, bound= Reusable)

Returns:

A reusable object from the pool.

Raises:

RuntimeError – If the pool is empty.

return_object(obj)[source]

Return a reusable object to the pool.

Parameters:

obj (TypeVar(T, bound= Reusable)) – The reusable object to return.

Raises:

ValueError – If the object is None or already in the pool.

get_size()[source]

Get the current size of the pool.

Return type:

int

Returns:

The number of reusable objects in the pool.