Memoize

Implementation of the Memoize Software Design Pattern.

Memoize is implemented using an Object Pool which is queried by a key which is the result of computing a hash given runtime arguments.

class software_patterns.memoize.ObjectsPool(callback: Callable[[...], ObjectType], hash_callback: Optional[Callable[[...], Union[int, str]]] = None)[source]

Cache objects and allow to query (the pool) using runtime arguments.

Instances of the ObjectsPool class implement the Object Pool Software Design Creational Pattern.

Whenever an object is requested, it is checked whether it exists in the pool by using the runtimetime arguments to query a python dictionary. If it exists, a reference is returned, otherwise a new object is constructed (given the provided callback) and its reference is returned.

Example

>>> from software_patterns import ObjectsPool
>>> class ClientClass:
...  def __init__(self, a: int, b: int):
...   pass
>>> object_pool = ObjectsPool[ClientClass](ClientClass)
>>> obj1 = object_pool.get_object(1, 2)
>>> obj2 = object_pool.get_object(1, 3)
>>> obj3 = object_pool.get_object(1, 2)
>>> id(obj1) == id(obj3)
True
>>> len(object_pool._objects)
2
Parameters
  • callback (Callable[..., ObjectType]) – constructs objects given arguments

  • hash_callback (Optional[RuntimeBuildHashCallable], optional) – option to overide the default hash key computer. Defaults to None.

Returns

[description]

Return type

[type]

get_object(*args: Any, **kwargs: Any) ObjectType[source]

Request an object from the pool.

Get or create an object given the input arguments, which are used to create a unique hash key. The key is used to query a python dictionary and determine whether the object request refers to a cached object.

Returns

the reference to the object that corresponds to the input arguments, regardless of whether it was found in the pool or not

Return type

object (ObjectType)