Book a Demo!
CoCalc Logo Icon
StoreFeaturesDocsShareSupportNewsAboutPoliciesSign UpSign In
sagemath
GitHub Repository: sagemath/sagelib
Path: blob/master/sage/misc/cache.py
4036 views
1
"""
2
A weakref cache factory
3
"""
4
5
#*****************************************************************************
6
# Copyright (C) 2005 William Stein <[email protected]>
7
#
8
# Distributed under the terms of the GNU General Public License (GPL)
9
#
10
# http://www.gnu.org/licenses/
11
#*****************************************************************************
12
13
import weakref
14
15
class Cache:
16
"""
17
A weakref cache for arbitrary objects via an arbitrary function.
18
"""
19
def __init__(self, factory_function): #, canonical_params_function=None):
20
"""
21
INPUT:
22
factory_function -- a function that returns objects (which this
23
class will weakref cache)
24
"""
25
self.cache = {}
26
self.factory = factory_function
27
#self.canonical_params_function = canonical_params_function
28
29
def key(self, *args, **kwds):
30
"""
31
Return the key associated to the given args. Note that
32
the values must be hashable.
33
"""
34
return (tuple(args), tuple(kwds.items()))
35
36
def __call__(self, *args, **kwds):
37
"""
38
Return the object from the cache defined by the arguments,
39
or make it using the factoring function if it doesn't exist.
40
"""
41
#if self.canonical_params_function != None:
42
# args = self.canonical_params_function(*args, **kwds)
43
# kwds = {}
44
45
key = self.key(*args, **kwds)
46
try:
47
x = self.cache[key]()
48
if not (x is None):
49
return x
50
except KeyError:
51
pass
52
x = self.factory(*args, **kwds)
53
self.cache[key] = weakref.ref(x)
54
return x
55
56
def has_object(self, *args, **kwds):
57
"""
58
Returns true if cache has object defined by the
59
given args.
60
"""
61
key = self.key(args, kwds)
62
try:
63
return not (self.cache[key]() is None)
64
except KeyError:
65
return False
66
67
def __setitem__(self, key, x):
68
"""
69
Make a weakref to x with given key.
70
"""
71
self.cache[key] = weakref.ref(x)
72
73
def format_names(self, names, n=1):
74
"""
75
Many objects have a names argument. This function formats it,
76
i.e., if it is a list it turns it into a tuple, and if it
77
is a string and the number of names needed is bigger than 1,
78
it makes each letter of the string an element of a tuple.
79
"""
80
if isinstance(names, list) or (isinstance(names, str) and n > 1):
81
return tuple(names)
82
return names
83
84
85
86
87