dol.cache_keys¶
Key strategies: how cache_this turns an instance and a call into a cache key.
A key strategy (the KeyStrategy protocol) resolves a key from the method name when
the class is defined (resolve_at_definition) or, if it needs the instance, when the
cached attribute is accessed (resolve_at_runtime). The ready-made ones:
ExplicitKey: a fixed keyApplyToMethodName: a function of the method name (e.g. add an extension)InstanceProp: the value of an attribute of the instanceApplyToInstance: a function of the instanceFromMethodArgs: a function of the method’s argumentsCompositeKey: several strategies combined
cache_this accepts a strategy, or anything _resolve_key_for_cached_prop /
_resolve_key_for_cached_method can turn into one (a string, a callable, …).
The strategies are also attributes of cache_this (cache_this.ExplicitKey).
These used to live in dol.caching, which still re-exports them (i2mint/dol#70).
>>> from dol.cache_keys import ExplicitKey, ApplyToMethodName
>>> ExplicitKey('data.json').resolve_at_definition('load')
'data.json'
>>> ApplyToMethodName(lambda name: name + '.pkl').resolve_at_definition('load')
'load.pkl'
Functions
Register a class as a KeyStrategy. |
Classes
|
Apply a function to the instance to generate the key. |
|
Apply a function to the method name to generate the key. |
|
Combine multiple key strategies into a single composite key. |
|
Use an explicitly provided key value. |
|
Apply a function to method arguments to generate the key. |
|
Get a key from an instance property. |
|
Protocol defining how a key strategy should behave. |
- class dol.cache_keys.ApplyToInstance(func)[source]¶
Bases:
objectApply a function to the instance to generate the key.
- class dol.cache_keys.ApplyToMethodName(func)[source]¶
Bases:
objectApply a function to the method name to generate the key.
>>> strategy = ApplyToMethodName(lambda name: f"{name}.cache") >>> strategy.resolve_at_definition("my_method") 'my_method.cache'
- class dol.cache_keys.CompositeKey(*strategies, separator='_')[source]¶
Bases:
objectCombine multiple key strategies into a single composite key.
Useful for creating keys that depend on both instance properties and method arguments.
- class dol.cache_keys.ExplicitKey(key)[source]¶
Bases:
objectUse an explicitly provided key value.
>>> strategy = ExplicitKey("my_key") >>> strategy.resolve_at_definition("method_name") 'my_key'
- class dol.cache_keys.FromMethodArgs(func)[source]¶
Bases:
objectApply a function to method arguments to generate the key.
The function receives
(self, *args, **kwargs)and should return a cache key.
- class dol.cache_keys.InstanceProp(prop_name)[source]¶
Bases:
objectGet a key from an instance property.
- class dol.cache_keys.KeyStrategy(*args, **kwargs)[source]¶
Bases:
ProtocolProtocol defining how a key strategy should behave.