picos.caching

Caching helpers.

Classes

class picos.caching.cached_property(fget=None, fset=None, fdel=None, doc=None)[source]

Bases: property

A read-only property whose result is cached.

__init__(fget=None, fset=None, fdel=None, doc=None)[source]
deleter(fdel)[source]
getter(fget)[source]
setter(fset)[source]
class picos.caching.cached_selfinverse_property(fget=None, fset=None, fdel=None, doc=None)[source]

Bases: picos.caching.cached_property

A read-only, self-inverse property whose result is cached.

Functions

picos.caching.borrow_cache(target, source, names)[source]

Copy cached values from one object to another.

Parameters
  • target – The object to populate the cache of.

  • source – The object to take cached values from.

  • names – Names of cached properties or functions to borrow.

picos.caching.cached_selfinverse_unary_operator(operator)[source]

Make a self-inverse unary operator method cache its result.

This is supposed to be used for property-like special methods such as __neg__ where cached_property can’t be used.

Warning

The result returned by the wrapped operator must be a fresh object as it will be modified.

picos.caching.cached_unary_operator(operator)[source]

Make a unary operator method cache its result.

This is supposed to be used for property-like special methods such as __neg__ where cached_property can’t be used.

picos.caching.empty_cache(obj)[source]

Clear all cached values of an object.

picos.caching.unlocked_cached_properties(obj)[source]

Unlock the setters of cached instance attributes.

Normally, cached attributes are read-only properties. When the user first reads them, the cache is populated with the value returned to the user, and successive reads will return the cached value.

The user is allowed to empty the cache by using del on the variable, but they may not assign a value to it. This context allows the programmer to manually populate the cache by assigning a value to the property.

Example

>>> from picos.caching import cached_property, unlocked_cached_properties
>>> class A:
...     @cached_property
...     def p(self):
...         return 1
...
>>> a = A()
>>> try:
...     a.p = 2
... except AttributeError:
...     print("Not possible.")
...
Not possible.
>>> with unlocked_cached_properties(a):
...     a.p = 2  # Populate the cache of a.p.
...
>>> a.p
2

Objects

picos.caching.CACHED_PREFIX

The prefix used for storing cached values.

Default value
'_cached_'
picos.caching.CACHED_PROP_UNLOCKED_TOKEN

An attribute name whose presence unlocks the setter of cached properties.

Default value
'_CACHED_PROPERTIES_ARE_UNLOCKED'