caching.CachedType

A class that automatically caches its instances

Sometimes you define classes whose instances hold absolutely no state on them, and are completey determined by the arguments passed to them. In these cases using caching.CachedType as a metaclass would cache class instances, preventing more than one of them from being created:

>>> from python_toolbox import caching
>>>
>>> class A(metaclass=caching.CachedType):
...      def __init__(self, a=1, b=2):
...          self.a = a
...          self.b = b

Now every time you create an instance, it’ll be cached:

>>> my_instance = A(b=3)

And the next time you’ll create an instance with the same arguments:

>>> another_instance = A(b=3)

No instance will be actually created; the same instance from before will be used:

>>> assert another_instance is my_instance

Table Of Contents

Previous topic

caching.cache()

Next topic

caching.CachedProperty

This Page