├── MANIFEST.in ├── setup.py ├── test.py ├── README.rst ├── LICENSE.txt └── pylru.py /MANIFEST.in: -------------------------------------------------------------------------------- 1 | include LICENSE.txt 2 | include test.py 3 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | setuptools.setup( 4 | name = "pylru", 5 | version = "1.2.1", 6 | py_modules=['pylru'], 7 | description = "A least recently used (LRU) cache implementation", 8 | author = "Jay Hutchinson", 9 | author_email = "jlhutch+pylru@gmail.com", 10 | url = "https://github.com/jlhutch/pylru", 11 | classifiers = [ 12 | "Programming Language :: Python :: 2.6", 13 | "Programming Language :: Python :: 2.7", 14 | "Programming Language :: Python :: 3", 15 | "Development Status :: 5 - Production/Stable", 16 | "Intended Audience :: Developers", 17 | "License :: OSI Approved :: GNU General Public License (GPL)", 18 | "Operating System :: OS Independent", 19 | "Topic :: Software Development :: Libraries :: Python Modules", 20 | ], 21 | long_description=open('README.rst').read()) 22 | 23 | 24 | -------------------------------------------------------------------------------- /test.py: -------------------------------------------------------------------------------- 1 | 2 | from pylru import * 3 | import random 4 | 5 | # This tests PyLRU by fuzzing it with random operations, then checking the 6 | # results against another, simpler, LRU cache implementation. 7 | 8 | class simplelrucache: 9 | 10 | def __init__(self, size): 11 | # Initialize the cache as empty. 12 | self.cache = [] 13 | self.size = size 14 | 15 | def __contains__(self, key): 16 | for x in self.cache: 17 | if x[0] == key: 18 | return True 19 | 20 | return False 21 | 22 | def __getitem__(self, key): 23 | for i in range(len(self.cache)): 24 | x = self.cache[i] 25 | if x[0] == key: 26 | del self.cache[i] 27 | self.cache.append(x) 28 | return x[1] 29 | 30 | raise KeyError 31 | 32 | def __setitem__(self, key, value): 33 | for i in range(len(self.cache)): 34 | x = self.cache[i] 35 | if x[0] == key: 36 | x[1] = value 37 | del self.cache[i] 38 | self.cache.append(x) 39 | return 40 | 41 | if len(self.cache) == self.size: 42 | self.cache = self.cache[1:] 43 | 44 | self.cache.append([key, value]) 45 | 46 | def __delitem__(self, key): 47 | for i in range(len(self.cache)): 48 | if self.cache[i][0] == key: 49 | del self.cache[i] 50 | return 51 | 52 | raise KeyError 53 | 54 | def resize(self, x=None): 55 | assert x > 0 56 | self.size = x 57 | if x < len(self.cache): 58 | del self.cache[:len(self.cache) - x] 59 | 60 | 61 | def test(a, b, c, d, verify): 62 | for i in range(1000): 63 | x = random.randint(0, 512) 64 | y = random.randint(0, 512) 65 | 66 | a[x] = y 67 | b[x] = y 68 | verify(c, d) 69 | 70 | for i in range(1000): 71 | x = random.randint(0, 512) 72 | if x in a: 73 | assert x in b 74 | z = a[x] 75 | z += b[x] 76 | else: 77 | assert x not in b 78 | verify(c, d) 79 | 80 | for i in range(256): 81 | x = random.randint(0, 512) 82 | if x in a: 83 | assert x in b 84 | del a[x] 85 | del b[x] 86 | else: 87 | assert x not in b 88 | verify(c, d) 89 | 90 | 91 | def testcache(): 92 | def verify(a, b): 93 | q = [] 94 | z = a.head 95 | for j in range(len(a.table)): 96 | q.append([z.key, z.value]) 97 | z = z.next 98 | 99 | assert q == b.cache[::-1] 100 | 101 | q2 = [] 102 | for x, y in q: 103 | q2.append((x, y)) 104 | 105 | assert list(a.items()) == q2 106 | assert list(zip(a.keys(), a.values())) == q2 107 | assert list(a.keys()) == list(a) 108 | 109 | a = lrucache(128) 110 | b = simplelrucache(128) 111 | verify(a, b) 112 | test(a, b, a, b, verify) 113 | 114 | a.size(71) 115 | b.resize(71) 116 | verify(a, b) 117 | test(a, b, a, b, verify) 118 | 119 | a.size(341) 120 | b.resize(341) 121 | verify(a, b) 122 | test(a, b, a, b, verify) 123 | 124 | a.size(127) 125 | b.resize(127) 126 | verify(a, b) 127 | test(a, b, a, b, verify) 128 | 129 | 130 | def wraptest(): 131 | def verify(p, x): 132 | assert p == x.store 133 | for key, value in x.cache.items(): 134 | assert x.store[key] == value 135 | 136 | tmp = list(x.items()) 137 | tmp.sort() 138 | 139 | tmp2 = list(p.items()) 140 | tmp2.sort() 141 | 142 | assert tmp == tmp2 143 | 144 | p = dict() 145 | q = dict() 146 | x = lruwrap(q, 128) 147 | 148 | test(p, x, p, x, verify) 149 | 150 | 151 | def wraptest2(): 152 | def verify(p, x): 153 | for key, value in x.store.items(): 154 | if key not in x.dirty: 155 | assert p[key] == value 156 | 157 | for key in x.dirty: 158 | assert x.cache.peek(key) == p[key] 159 | 160 | for key, value in x.cache.items(): 161 | if key not in x.dirty: 162 | assert x.store[key] == p[key] == value 163 | 164 | tmp = list(x.items()) 165 | tmp.sort() 166 | 167 | tmp2 = list(p.items()) 168 | tmp2.sort() 169 | 170 | assert tmp == tmp2 171 | 172 | p = dict() 173 | q = dict() 174 | x = lruwrap(q, 128, True) 175 | 176 | test(p, x, p, x, verify) 177 | 178 | x.sync() 179 | assert p == q 180 | 181 | def wraptest3(): 182 | def verify(p, x): 183 | for key, value in x.store.items(): 184 | if key not in x.dirty: 185 | assert p[key] == value 186 | 187 | for key in x.dirty: 188 | assert x.cache.peek(key) == p[key] 189 | 190 | for key, value in x.cache.items(): 191 | if key not in x.dirty: 192 | assert x.store[key] == p[key] == value 193 | 194 | p = dict() 195 | q = dict() 196 | with lruwrap(q, 128, True) as x: 197 | test(p, x, p, x, verify) 198 | 199 | assert p == q 200 | 201 | 202 | @lrudecorator(100) 203 | def square(x): 204 | return x*x 205 | 206 | def testDecorator(): 207 | for i in range(1000): 208 | x = random.randint(0, 200) 209 | assert square(x) == x*x 210 | 211 | 212 | if __name__ == '__main__': 213 | random.seed() 214 | 215 | for i in range(20): 216 | testcache() 217 | wraptest() 218 | wraptest2() 219 | wraptest3() 220 | testDecorator() 221 | 222 | 223 | -------------------------------------------------------------------------------- /README.rst: -------------------------------------------------------------------------------- 1 | 2 | 3 | PyLRU 4 | ===== 5 | 6 | A least recently used (LRU) cache for Python. 7 | 8 | Introduction 9 | ============ 10 | 11 | Pylru implements a true LRU cache along with several support classes. The cache is efficient and written in pure Python. It works with Python 2.6+ including the 3.x series. Basic operations (lookup, insert, delete) all run in a constant amount of time. Pylru provides a cache class with a simple dict interface. It also provides classes to wrap any object that has a dict interface with a cache. Both write-through and write-back semantics are supported. Pylru also provides classes to wrap functions in a similar way, including a function decorator. 12 | 13 | You can install pylru or you can just copy the source file pylru.py and use it directly in your own project. The rest of this file explains what the pylru module provides and how to use it. If you want to know more examine pylru.py. The code is straightforward and well commented. 14 | 15 | Installation 16 | ============ 17 | 18 | :: 19 | 20 | pip install pylru 21 | 22 | Usage 23 | ===== 24 | 25 | lrucache 26 | -------- 27 | 28 | An lrucache object has a dictionary like interface and can be used in the same way:: 29 | 30 | import pylru 31 | 32 | size = 100 # Size of the cache. The maximum number of key/value 33 | # pairs you want the cache to hold. 34 | 35 | cache = pylru.lrucache(size) 36 | # Create a cache object. 37 | 38 | value = cache[key] # Lookup a value given its key. 39 | cache[key] = value # Insert a key/value pair. 40 | del cache[key] # Delete a value given its key. 41 | # 42 | # These three operations affect the order of the cache. 43 | # Lookup and insert both move the key/value to the most 44 | # recently used position. Delete (obviously) removes a 45 | # key/value from whatever position it was in. 46 | 47 | key in cache # Test for membership. Does not affect the cache order. 48 | 49 | value = cache.peek(key) 50 | # Lookup a value given its key. Does not affect the 51 | # cache order. 52 | 53 | cache.keys() # Return an iterator over the keys in the cache 54 | cache.values() # Return an iterator over the values in the cache 55 | cache.items() # Return an iterator over the (key, value) pairs in the 56 | # cache. 57 | # 58 | # These calls have no effect on the cache order. 59 | # lrucache is scan resistant when these calls are used. 60 | # The iterators iterate over their respective elements 61 | # in the order of most recently used to least recently 62 | # used. 63 | # 64 | # WARNING - While these iterators do not affect the 65 | # cache order the lookup, insert, and delete operations 66 | # do. The result of changing the cache's order 67 | # during iteration is undefined. If you really need to 68 | # do something of the sort use list(cache.keys()), then 69 | # loop over the list elements. 70 | 71 | for key in cache: # Caches support __iter__ so you can use them directly 72 | pass # in a for loop to loop over the keys just like 73 | # cache.keys() 74 | 75 | cache.size() # Returns the size of the cache 76 | cache.size(x) # Changes the size of the cache. x MUST be greater than 77 | # zero. Returns the new size x. 78 | 79 | x = len(cache) # Returns the number of items stored in the cache. 80 | # x will be less than or equal to cache.size() 81 | 82 | cache.clear() # Remove all items from the cache. 83 | 84 | 85 | Lrucache takes an optional callback function as a second argument. Since the cache has a fixed size, some operations (such as an insertion) may cause the least recently used key/value pair to be ejected. If the optional callback function is given it will be called when this occurs. For example:: 86 | 87 | import pylru 88 | 89 | def callback(key, value): 90 | print (key, value) # A dumb callback that just prints the key/value 91 | 92 | size = 100 93 | cache = pylru.lrucache(size, callback) 94 | 95 | # Use the cache... When it gets full some pairs may be ejected due to 96 | # the fixed cache size. But, not before the callback is called to let you 97 | # know. 98 | 99 | WriteThroughCacheManager 100 | ------------------------ 101 | 102 | Often a cache is used to speed up access to some other high latency object. For example, imagine you have a backend storage object that reads/writes from/to a remote server. Let us call this object *store*. If store has a dictionary interface a cache manager class can be used to compose the store object and an lrucache. The manager object exposes a dictionary interface. The programmer can then interact with the manager object as if it were the store. The manager object takes care of communicating with the store and caching key/value pairs in the lrucache object. 103 | 104 | Two different semantics are supported, write-through (WriteThroughCacheManager class) and write-back (WriteBackCacheManager class). With write-through, lookups from the store are cached for future lookups. Insertions and deletions are updated in the cache and written through to the store immediately. Write-back works the same way, but insertions are updated only in the cache. These "dirty" key/value pair will only be updated to the underlying store when they are ejected from the cache or when a sync is performed. The WriteBackCacheManager class is discussed more below. 105 | 106 | The WriteThroughCacheManager class takes as arguments the store object you want to compose and the cache size. It then creates an LRU cache and automatically manages it:: 107 | 108 | import pylru 109 | 110 | size = 100 111 | cached = pylru.WriteThroughCacheManager(store, size) 112 | # Or 113 | cached = pylru.lruwrap(store, size) 114 | # This is a factory function that does the same thing. 115 | 116 | # Now the object *cached* can be used just like store, except caching is 117 | # automatically handled. 118 | 119 | value = cached[key] # Lookup a value given its key. 120 | cached[key] = value # Insert a key/value pair. 121 | del cached[key] # Delete a value given its key. 122 | 123 | key in cache # Test for membership. Does not affect the cache order. 124 | 125 | cached.keys() # Returns store.keys() 126 | cached.values() # Returns store.values() 127 | cached.items() # Returns store.items() 128 | # 129 | # These calls have no effect on the cache order. 130 | # The iterators iterate over their respective elements 131 | # in the order dictated by store. 132 | 133 | for key in cached: # Same as store.keys() 134 | 135 | cached.size() # Returns the size of the cache 136 | cached.size(x) # Changes the size of the cache. x MUST be greater than 137 | # zero. Returns the new size x. 138 | 139 | x = len(cached) # Returns the number of items stored in the store. 140 | 141 | cached.clear() # Remove all items from the store and cache. 142 | 143 | 144 | WriteBackCacheManager 145 | --------------------- 146 | 147 | Similar to the WriteThroughCacheManager class except write-back semantics are used to manage the cache. The programmer is responsible for one more thing as well. They MUST call sync() when they are finished. This ensures that the last of the "dirty" entries in the cache are written back. This is not too bad as WriteBackCacheManager objects can be used in with statements. More about that below:: 148 | 149 | 150 | import pylru 151 | 152 | size = 100 153 | cached = pylru.WriteBackCacheManager(store, size) 154 | # Or 155 | cached = pylru.lruwrap(store, size, True) 156 | # This is a factory function that does the same thing. 157 | 158 | value = cached[key] # Lookup a value given its key. 159 | cached[key] = value # Insert a key/value pair. 160 | del cached[key] # Delete a value given its key. 161 | 162 | key in cache # Test for membership. Does not affect the cache order. 163 | 164 | 165 | cached.keys() # Return an iterator over the keys in the cache/store 166 | cached.values() # Return an iterator over the values in the cache/store 167 | cached.items() # Return an iterator over the (key, value) pairs in the 168 | # cache/store. 169 | # 170 | # The iterators iterate over a consistent view of the 171 | # respective elements. That is, except for the order, 172 | # the elements are the same as those returned if you 173 | # first called sync() then called 174 | # store.keys()[ or values() or items()] 175 | # 176 | # These calls have no effect on the cache order. 177 | # The iterators iterate over their respective elements 178 | # in arbitrary order. 179 | # 180 | # WARNING - While these iterators do not effect the 181 | # cache order the lookup, insert, and delete operations 182 | # do. The results of changing the cache's order 183 | # during iteration is undefined. If you really need to 184 | # do something of the sort use list(cached.keys()), 185 | # then loop over the list elements. 186 | 187 | for key in cached: # Same as cached.keys() 188 | 189 | cached.size() # Returns the size of the cache 190 | cached.size(x) # Changes the size of the cache. x MUST be greater than 191 | # zero. Returns the new size x. 192 | 193 | x = len(cached) # Returns the number of items stored in the store. 194 | # 195 | # WARNING - This method calls sync() internally. If 196 | # that has adverse performance effects for your 197 | # application, you may want to avoid calling this 198 | # method frequently. 199 | 200 | cached.clear() # Remove all items from the store and cache. 201 | 202 | cached.sync() # Make the store and cache consistent. Write all 203 | # cached changes to the store that have not been 204 | # yet. 205 | 206 | cached.flush() # Calls sync() then clears the cache. 207 | 208 | 209 | To help the programmer ensure that the final sync() is called, WriteBackCacheManager objects can be used in a with statement:: 210 | 211 | with pylru.WriteBackCacheManager(store, size) as cached: 212 | # Use cached just like you would store. sync() is called automatically 213 | # for you when leaving the with statement block. 214 | 215 | 216 | FunctionCacheManager 217 | --------------------- 218 | 219 | FunctionCacheManager allows you to compose a function with an lrucache. The resulting object can be called just like the original function, but the results are cached to speed up future calls. The function must have arguments that are hashable. FunctionCacheManager takes an optional callback function as a third argument:: 220 | 221 | import pylru 222 | 223 | def square(x): 224 | return x * x 225 | 226 | size = 100 227 | cached = pylru.FunctionCacheManager(square, size) 228 | 229 | y = cached(7) 230 | 231 | # The results of cached are the same as square, but automatically cached 232 | # to speed up future calls. 233 | 234 | cached.size() # Returns the size of the cache 235 | cached.size(x) # Changes the size of the cache. x MUST be greater than 236 | # zero. Returns the new size x. 237 | 238 | cached.clear() # Remove all items from the cache. 239 | 240 | 241 | 242 | lrudecorator 243 | ------------ 244 | 245 | PyLRU also provides a function decorator. This is basically the same functionality as FunctionCacheManager, but in the form of a decorator. The decorator takes an optional callback function as a second argument:: 246 | 247 | from pylru import lrudecorator 248 | 249 | @lrudecorator(100) 250 | def square(x): 251 | return x * x 252 | 253 | # The results of the square function are cached to speed up future calls. 254 | 255 | square.size() # Returns the size of the cache 256 | square.size(x) # Changes the size of the cache. x MUST be greater than 257 | # zero. Returns the new size x. 258 | 259 | square.clear() # Remove all items from the cache. 260 | -------------------------------------------------------------------------------- /LICENSE.txt: -------------------------------------------------------------------------------- 1 | GNU GENERAL PUBLIC LICENSE 2 | Version 2, June 1991 3 | 4 | Copyright (C) 1989, 1991 Free Software Foundation, Inc., 5 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA 6 | Everyone is permitted to copy and distribute verbatim copies 7 | of this license document, but changing it is not allowed. 8 | 9 | Preamble 10 | 11 | The licenses for most software are designed to take away your 12 | freedom to share and change it. By contrast, the GNU General Public 13 | License is intended to guarantee your freedom to share and change free 14 | software--to make sure the software is free for all its users. This 15 | General Public License applies to most of the Free Software 16 | Foundation's software and to any other program whose authors commit to 17 | using it. (Some other Free Software Foundation software is covered by 18 | the GNU Lesser General Public License instead.) You can apply it to 19 | your programs, too. 20 | 21 | When we speak of free software, we are referring to freedom, not 22 | price. Our General Public Licenses are designed to make sure that you 23 | have the freedom to distribute copies of free software (and charge for 24 | this service if you wish), that you receive source code or can get it 25 | if you want it, that you can change the software or use pieces of it 26 | in new free programs; and that you know you can do these things. 27 | 28 | To protect your rights, we need to make restrictions that forbid 29 | anyone to deny you these rights or to ask you to surrender the rights. 30 | These restrictions translate to certain responsibilities for you if you 31 | distribute copies of the software, or if you modify it. 32 | 33 | For example, if you distribute copies of such a program, whether 34 | gratis or for a fee, you must give the recipients all the rights that 35 | you have. You must make sure that they, too, receive or can get the 36 | source code. And you must show them these terms so they know their 37 | rights. 38 | 39 | We protect your rights with two steps: (1) copyright the software, and 40 | (2) offer you this license which gives you legal permission to copy, 41 | distribute and/or modify the software. 42 | 43 | Also, for each author's protection and ours, we want to make certain 44 | that everyone understands that there is no warranty for this free 45 | software. If the software is modified by someone else and passed on, we 46 | want its recipients to know that what they have is not the original, so 47 | that any problems introduced by others will not reflect on the original 48 | authors' reputations. 49 | 50 | Finally, any free program is threatened constantly by software 51 | patents. We wish to avoid the danger that redistributors of a free 52 | program will individually obtain patent licenses, in effect making the 53 | program proprietary. To prevent this, we have made it clear that any 54 | patent must be licensed for everyone's free use or not licensed at all. 55 | 56 | The precise terms and conditions for copying, distribution and 57 | modification follow. 58 | 59 | GNU GENERAL PUBLIC LICENSE 60 | TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION 61 | 62 | 0. This License applies to any program or other work which contains 63 | a notice placed by the copyright holder saying it may be distributed 64 | under the terms of this General Public License. The "Program", below, 65 | refers to any such program or work, and a "work based on the Program" 66 | means either the Program or any derivative work under copyright law: 67 | that is to say, a work containing the Program or a portion of it, 68 | either verbatim or with modifications and/or translated into another 69 | language. (Hereinafter, translation is included without limitation in 70 | the term "modification".) Each licensee is addressed as "you". 71 | 72 | Activities other than copying, distribution and modification are not 73 | covered by this License; they are outside its scope. The act of 74 | running the Program is not restricted, and the output from the Program 75 | is covered only if its contents constitute a work based on the 76 | Program (independent of having been made by running the Program). 77 | Whether that is true depends on what the Program does. 78 | 79 | 1. You may copy and distribute verbatim copies of the Program's 80 | source code as you receive it, in any medium, provided that you 81 | conspicuously and appropriately publish on each copy an appropriate 82 | copyright notice and disclaimer of warranty; keep intact all the 83 | notices that refer to this License and to the absence of any warranty; 84 | and give any other recipients of the Program a copy of this License 85 | along with the Program. 86 | 87 | You may charge a fee for the physical act of transferring a copy, and 88 | you may at your option offer warranty protection in exchange for a fee. 89 | 90 | 2. You may modify your copy or copies of the Program or any portion 91 | of it, thus forming a work based on the Program, and copy and 92 | distribute such modifications or work under the terms of Section 1 93 | above, provided that you also meet all of these conditions: 94 | 95 | a) You must cause the modified files to carry prominent notices 96 | stating that you changed the files and the date of any change. 97 | 98 | b) You must cause any work that you distribute or publish, that in 99 | whole or in part contains or is derived from the Program or any 100 | part thereof, to be licensed as a whole at no charge to all third 101 | parties under the terms of this License. 102 | 103 | c) If the modified program normally reads commands interactively 104 | when run, you must cause it, when started running for such 105 | interactive use in the most ordinary way, to print or display an 106 | announcement including an appropriate copyright notice and a 107 | notice that there is no warranty (or else, saying that you provide 108 | a warranty) and that users may redistribute the program under 109 | these conditions, and telling the user how to view a copy of this 110 | License. (Exception: if the Program itself is interactive but 111 | does not normally print such an announcement, your work based on 112 | the Program is not required to print an announcement.) 113 | 114 | These requirements apply to the modified work as a whole. If 115 | identifiable sections of that work are not derived from the Program, 116 | and can be reasonably considered independent and separate works in 117 | themselves, then this License, and its terms, do not apply to those 118 | sections when you distribute them as separate works. But when you 119 | distribute the same sections as part of a whole which is a work based 120 | on the Program, the distribution of the whole must be on the terms of 121 | this License, whose permissions for other licensees extend to the 122 | entire whole, and thus to each and every part regardless of who wrote it. 123 | 124 | Thus, it is not the intent of this section to claim rights or contest 125 | your rights to work written entirely by you; rather, the intent is to 126 | exercise the right to control the distribution of derivative or 127 | collective works based on the Program. 128 | 129 | In addition, mere aggregation of another work not based on the Program 130 | with the Program (or with a work based on the Program) on a volume of 131 | a storage or distribution medium does not bring the other work under 132 | the scope of this License. 133 | 134 | 3. You may copy and distribute the Program (or a work based on it, 135 | under Section 2) in object code or executable form under the terms of 136 | Sections 1 and 2 above provided that you also do one of the following: 137 | 138 | a) Accompany it with the complete corresponding machine-readable 139 | source code, which must be distributed under the terms of Sections 140 | 1 and 2 above on a medium customarily used for software interchange; or, 141 | 142 | b) Accompany it with a written offer, valid for at least three 143 | years, to give any third party, for a charge no more than your 144 | cost of physically performing source distribution, a complete 145 | machine-readable copy of the corresponding source code, to be 146 | distributed under the terms of Sections 1 and 2 above on a medium 147 | customarily used for software interchange; or, 148 | 149 | c) Accompany it with the information you received as to the offer 150 | to distribute corresponding source code. (This alternative is 151 | allowed only for noncommercial distribution and only if you 152 | received the program in object code or executable form with such 153 | an offer, in accord with Subsection b above.) 154 | 155 | The source code for a work means the preferred form of the work for 156 | making modifications to it. For an executable work, complete source 157 | code means all the source code for all modules it contains, plus any 158 | associated interface definition files, plus the scripts used to 159 | control compilation and installation of the executable. However, as a 160 | special exception, the source code distributed need not include 161 | anything that is normally distributed (in either source or binary 162 | form) with the major components (compiler, kernel, and so on) of the 163 | operating system on which the executable runs, unless that component 164 | itself accompanies the executable. 165 | 166 | If distribution of executable or object code is made by offering 167 | access to copy from a designated place, then offering equivalent 168 | access to copy the source code from the same place counts as 169 | distribution of the source code, even though third parties are not 170 | compelled to copy the source along with the object code. 171 | 172 | 4. You may not copy, modify, sublicense, or distribute the Program 173 | except as expressly provided under this License. Any attempt 174 | otherwise to copy, modify, sublicense or distribute the Program is 175 | void, and will automatically terminate your rights under this License. 176 | However, parties who have received copies, or rights, from you under 177 | this License will not have their licenses terminated so long as such 178 | parties remain in full compliance. 179 | 180 | 5. You are not required to accept this License, since you have not 181 | signed it. However, nothing else grants you permission to modify or 182 | distribute the Program or its derivative works. These actions are 183 | prohibited by law if you do not accept this License. Therefore, by 184 | modifying or distributing the Program (or any work based on the 185 | Program), you indicate your acceptance of this License to do so, and 186 | all its terms and conditions for copying, distributing or modifying 187 | the Program or works based on it. 188 | 189 | 6. Each time you redistribute the Program (or any work based on the 190 | Program), the recipient automatically receives a license from the 191 | original licensor to copy, distribute or modify the Program subject to 192 | these terms and conditions. You may not impose any further 193 | restrictions on the recipients' exercise of the rights granted herein. 194 | You are not responsible for enforcing compliance by third parties to 195 | this License. 196 | 197 | 7. If, as a consequence of a court judgment or allegation of patent 198 | infringement or for any other reason (not limited to patent issues), 199 | conditions are imposed on you (whether by court order, agreement or 200 | otherwise) that contradict the conditions of this License, they do not 201 | excuse you from the conditions of this License. If you cannot 202 | distribute so as to satisfy simultaneously your obligations under this 203 | License and any other pertinent obligations, then as a consequence you 204 | may not distribute the Program at all. For example, if a patent 205 | license would not permit royalty-free redistribution of the Program by 206 | all those who receive copies directly or indirectly through you, then 207 | the only way you could satisfy both it and this License would be to 208 | refrain entirely from distribution of the Program. 209 | 210 | If any portion of this section is held invalid or unenforceable under 211 | any particular circumstance, the balance of the section is intended to 212 | apply and the section as a whole is intended to apply in other 213 | circumstances. 214 | 215 | It is not the purpose of this section to induce you to infringe any 216 | patents or other property right claims or to contest validity of any 217 | such claims; this section has the sole purpose of protecting the 218 | integrity of the free software distribution system, which is 219 | implemented by public license practices. Many people have made 220 | generous contributions to the wide range of software distributed 221 | through that system in reliance on consistent application of that 222 | system; it is up to the author/donor to decide if he or she is willing 223 | to distribute software through any other system and a licensee cannot 224 | impose that choice. 225 | 226 | This section is intended to make thoroughly clear what is believed to 227 | be a consequence of the rest of this License. 228 | 229 | 8. If the distribution and/or use of the Program is restricted in 230 | certain countries either by patents or by copyrighted interfaces, the 231 | original copyright holder who places the Program under this License 232 | may add an explicit geographical distribution limitation excluding 233 | those countries, so that distribution is permitted only in or among 234 | countries not thus excluded. In such case, this License incorporates 235 | the limitation as if written in the body of this License. 236 | 237 | 9. The Free Software Foundation may publish revised and/or new versions 238 | of the General Public License from time to time. Such new versions will 239 | be similar in spirit to the present version, but may differ in detail to 240 | address new problems or concerns. 241 | 242 | Each version is given a distinguishing version number. If the Program 243 | specifies a version number of this License which applies to it and "any 244 | later version", you have the option of following the terms and conditions 245 | either of that version or of any later version published by the Free 246 | Software Foundation. If the Program does not specify a version number of 247 | this License, you may choose any version ever published by the Free Software 248 | Foundation. 249 | 250 | 10. If you wish to incorporate parts of the Program into other free 251 | programs whose distribution conditions are different, write to the author 252 | to ask for permission. For software which is copyrighted by the Free 253 | Software Foundation, write to the Free Software Foundation; we sometimes 254 | make exceptions for this. Our decision will be guided by the two goals 255 | of preserving the free status of all derivatives of our free software and 256 | of promoting the sharing and reuse of software generally. 257 | 258 | NO WARRANTY 259 | 260 | 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY 261 | FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN 262 | OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES 263 | PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED 264 | OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF 265 | MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS 266 | TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE 267 | PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, 268 | REPAIR OR CORRECTION. 269 | 270 | 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING 271 | WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR 272 | REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, 273 | INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING 274 | OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED 275 | TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY 276 | YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER 277 | PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE 278 | POSSIBILITY OF SUCH DAMAGES. 279 | 280 | END OF TERMS AND CONDITIONS 281 | 282 | How to Apply These Terms to Your New Programs 283 | 284 | If you develop a new program, and you want it to be of the greatest 285 | possible use to the public, the best way to achieve this is to make it 286 | free software which everyone can redistribute and change under these terms. 287 | 288 | To do so, attach the following notices to the program. It is safest 289 | to attach them to the start of each source file to most effectively 290 | convey the exclusion of warranty; and each file should have at least 291 | the "copyright" line and a pointer to where the full notice is found. 292 | 293 | 294 | Copyright (C) 295 | 296 | This program is free software; you can redistribute it and/or modify 297 | it under the terms of the GNU General Public License as published by 298 | the Free Software Foundation; either version 2 of the License, or 299 | (at your option) any later version. 300 | 301 | This program is distributed in the hope that it will be useful, 302 | but WITHOUT ANY WARRANTY; without even the implied warranty of 303 | MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 304 | GNU General Public License for more details. 305 | 306 | You should have received a copy of the GNU General Public License along 307 | with this program; if not, write to the Free Software Foundation, Inc., 308 | 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 309 | 310 | Also add information on how to contact you by electronic and paper mail. 311 | 312 | If the program is interactive, make it output a short notice like this 313 | when it starts in an interactive mode: 314 | 315 | Gnomovision version 69, Copyright (C) year name of author 316 | Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. 317 | This is free software, and you are welcome to redistribute it 318 | under certain conditions; type `show c' for details. 319 | 320 | The hypothetical commands `show w' and `show c' should show the appropriate 321 | parts of the General Public License. Of course, the commands you use may 322 | be called something other than `show w' and `show c'; they could even be 323 | mouse-clicks or menu items--whatever suits your program. 324 | 325 | You should also get your employer (if you work as a programmer) or your 326 | school, if any, to sign a "copyright disclaimer" for the program, if 327 | necessary. Here is a sample; alter the names: 328 | 329 | Yoyodyne, Inc., hereby disclaims all copyright interest in the program 330 | `Gnomovision' (which makes passes at compilers) written by James Hacker. 331 | 332 | , 1 April 1989 333 | Ty Coon, President of Vice 334 | 335 | This General Public License does not permit incorporating your program into 336 | proprietary programs. If your program is a subroutine library, you may 337 | consider it more useful to permit linking proprietary applications with the 338 | library. If this is what you want to do, use the GNU Lesser General 339 | Public License instead of this License. 340 | -------------------------------------------------------------------------------- /pylru.py: -------------------------------------------------------------------------------- 1 | 2 | # Cache implementaion with a Least Recently Used (LRU) replacement policy and 3 | # a basic dictionary interface. 4 | 5 | # Copyright (C) 2006-2022 Jay Hutchinson 6 | 7 | # This program is free software; you can redistribute it and/or modify it 8 | # under the terms of the GNU General Public License as published by the Free 9 | # Software Foundation; either version 2 of the License, or (at your option) 10 | # any later version. 11 | 12 | # This program is distributed in the hope that it will be useful, but WITHOUT 13 | # ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or 14 | # FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for 15 | # more details. 16 | 17 | # You should have received a copy of the GNU General Public License along 18 | # with this program; if not, write to the Free Software Foundation, Inc., 51 19 | # Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. 20 | 21 | 22 | 23 | # The cache is implemented using a combination of a python dictionary (hash 24 | # table) and a circular doubly linked list. Items in the cache are stored in 25 | # nodes. These nodes make up the linked list. The list is used to efficiently 26 | # maintain the order that the items have been used in. The front or head of 27 | # the list contains the most recently used item, the tail of the list 28 | # contains the least recently used item. When an item is used it can easily 29 | # (in a constant amount of time) be moved to the front of the list, thus 30 | # updating its position in the ordering. These nodes are also placed in the 31 | # hash table under their associated key. The hash table allows efficient 32 | # lookup of values by key. 33 | 34 | import sys 35 | if sys.version_info < (3, 3): 36 | from collections import Mapping 37 | else: 38 | from collections.abc import Mapping 39 | 40 | # Class for the node objects. 41 | class _dlnode(object): 42 | __slots__ = ('empty', 'next', 'prev', 'key', 'value') 43 | 44 | def __init__(self): 45 | self.empty = True 46 | 47 | 48 | class lrucache(object): 49 | def __init__(self, size, callback=None): 50 | self.callback = callback 51 | 52 | # Create an empty hash table. 53 | self.table = {} 54 | 55 | # Initialize the doubly linked list with one empty node. This is an 56 | # invariant. The cache size must always be greater than zero. Each 57 | # node has a 'prev' and 'next' variable to hold the node that comes 58 | # before it and after it respectively. Initially the two variables 59 | # each point to the head node itself, creating a circular doubly 60 | # linked list of size one. 61 | self.head = _dlnode() 62 | self.head.next = self.head 63 | self.head.prev = self.head 64 | 65 | self.listSize = 1 66 | 67 | # Now adjust the list to the desired size. 68 | self.size(size) 69 | 70 | def __len__(self): 71 | return len(self.table) 72 | 73 | def clear(self): 74 | for node in self.dli(): 75 | node.empty = True 76 | node.key = None 77 | node.value = None 78 | 79 | self.table.clear() 80 | 81 | def __contains__(self, key): 82 | return key in self.table 83 | 84 | # Looks up a value in the cache without affecting the cache's order. 85 | def peek(self, key): 86 | node = self.table[key] 87 | return node.value 88 | 89 | def __getitem__(self, key): 90 | node = self.table[key] 91 | 92 | # Update the list ordering. Move this node so that it directly 93 | # proceeds the head node. Then set the 'head' variable to it. This 94 | # makes it the new head of the list. 95 | self.mtf(node) 96 | self.head = node 97 | 98 | return node.value 99 | 100 | def get(self, key, default=None): 101 | if key not in self.table: 102 | return default 103 | 104 | return self[key] 105 | 106 | def __setitem__(self, key, value): 107 | # If any value is stored under 'key' in the cache already, then replace 108 | # that value with the new one. 109 | if key in self.table: 110 | node = self.table[key] 111 | 112 | # Replace the value. 113 | node.value = value 114 | 115 | # Update the list ordering. 116 | self.mtf(node) 117 | self.head = node 118 | 119 | return 120 | 121 | # Ok, no value is currently stored under 'key' in the cache. We need 122 | # to choose a node to place the new item in. There are two cases. If 123 | # the cache is full some item will have to be pushed out of the 124 | # cache. We want to choose the node with the least recently used 125 | # item. This is the node at the tail of the list. If the cache is not 126 | # full we want to choose a node that is empty. Because of the way the 127 | # list is managed, the empty nodes are always together at the tail 128 | # end of the list. Thus, in either case, by chooseing the node at the 129 | # tail of the list our conditions are satisfied. 130 | 131 | # Since the list is circular, the tail node directly preceeds the 132 | # 'head' node. 133 | node = self.head.prev 134 | 135 | # If the node already contains something we need to remove the old 136 | # key from the dictionary. 137 | if not node.empty: 138 | if self.callback is not None: 139 | self.callback(node.key, node.value) 140 | del self.table[node.key] 141 | 142 | # Place the new key and value in the node 143 | node.empty = False 144 | node.key = key 145 | node.value = value 146 | 147 | # Add the node to the dictionary under the new key. 148 | self.table[key] = node 149 | 150 | # We need to move the node to the head of the list. The node is the 151 | # tail node, so it directly preceeds the head node due to the list 152 | # being circular. Therefore, the ordering is already correct, we just 153 | # need to adjust the 'head' variable. 154 | self.head = node 155 | 156 | def __delitem__(self, key): 157 | # Lookup the node, remove it from the hash table, and mark it as empty. 158 | node = self.table[key] 159 | del self.table[key] 160 | node.empty = True 161 | 162 | # Not strictly necessary. 163 | node.key = None 164 | node.value = None 165 | 166 | # Because this node is now empty we want to reuse it before any 167 | # non-empty node. To do that we want to move it to the tail of the 168 | # list. We move it so that it directly preceeds the 'head' node. This 169 | # makes it the tail node. The 'head' is then adjusted. This 170 | # adjustment ensures correctness even for the case where the 'node' 171 | # is the 'head' node. 172 | self.mtf(node) 173 | self.head = node.next 174 | 175 | def update(self, *args, **kwargs): 176 | if len(args) > 0: 177 | other = args[0] 178 | if isinstance(other, Mapping): 179 | for key in other: 180 | self[key] = other[key] 181 | elif hasattr(other, "keys"): 182 | for key in other.keys(): 183 | self[key] = other[key] 184 | else: 185 | for key, value in other: 186 | self[key] = value 187 | 188 | for key, value in kwargs.items(): 189 | self[key] = value 190 | 191 | __defaultObj = object() 192 | def pop(self, key, default=__defaultObj): 193 | if key in self.table: 194 | value = self.peek(key) 195 | del self[key] 196 | return value 197 | 198 | if default is self.__defaultObj: 199 | raise KeyError 200 | 201 | return default 202 | 203 | def popitem(self): 204 | # Make sure the cache isn't empty. 205 | if len(self) < 1: 206 | raise KeyError 207 | 208 | # Grab the head node 209 | node = self.head 210 | 211 | # Save the key and value so that we can return them. 212 | key = node.key 213 | value = node.value 214 | 215 | # Remove the key from the hash table and mark the node as empty. 216 | del self.table[key] 217 | node.empty = True 218 | 219 | # Not strictly necessary. 220 | node.key = None 221 | node.value = None 222 | 223 | # Because this node is now empty we want to reuse it before any 224 | # non-empty node. To do that we want to move it to the tail of the 225 | # list. This node is the head node. Due to the list being circular, 226 | # the ordering is already correct, we just need to adjust the 'head' 227 | # variable. 228 | self.head = node.next 229 | 230 | return key, value 231 | 232 | def setdefault(self, key, default=None): 233 | if key in self.table: 234 | return self[key] 235 | 236 | self[key] = default 237 | return default 238 | 239 | def __iter__(self): 240 | # Return an iterator that returns the keys in the cache in order from 241 | # the most recently to least recently used. Does not modify the cache's 242 | # order. 243 | for node in self.dli(): 244 | yield node.key 245 | 246 | def items(self): 247 | # Return an iterator that returns the (key, value) pairs in the cache 248 | # in order from the most recently to least recently used. Does not 249 | # modify the cache's order. 250 | for node in self.dli(): 251 | yield (node.key, node.value) 252 | 253 | def keys(self): 254 | # Return an iterator that returns the keys in the cache in order from 255 | # the most recently to least recently used. Does not modify the cache's 256 | # order. 257 | for node in self.dli(): 258 | yield node.key 259 | 260 | def values(self): 261 | # Return an iterator that returns the values in the cache in order 262 | # from the most recently to least recently used. Does not modify the 263 | # cache's order. 264 | for node in self.dli(): 265 | yield node.value 266 | 267 | def size(self, size=None): 268 | if size is not None: 269 | assert size > 0 270 | if size > self.listSize: 271 | self.addTailNode(size - self.listSize) 272 | elif size < self.listSize: 273 | self.removeTailNode(self.listSize - size) 274 | 275 | return self.listSize 276 | 277 | # Increases the size of the cache by inserting n empty nodes at the tail 278 | # of the list. 279 | def addTailNode(self, n): 280 | for i in range(n): 281 | node = _dlnode() 282 | node.next = self.head 283 | node.prev = self.head.prev 284 | 285 | self.head.prev.next = node 286 | self.head.prev = node 287 | 288 | self.listSize += n 289 | 290 | # Decreases the size of the cache by removing n nodes from the tail of the 291 | # list. 292 | def removeTailNode(self, n): 293 | assert self.listSize > n 294 | for i in range(n): 295 | node = self.head.prev 296 | if not node.empty: 297 | if self.callback is not None: 298 | self.callback(node.key, node.value) 299 | del self.table[node.key] 300 | 301 | # Splice the tail node out of the list 302 | self.head.prev = node.prev 303 | node.prev.next = self.head 304 | 305 | # The next four lines are not strictly necessary. 306 | node.prev = None 307 | node.next = None 308 | node.key = None 309 | node.value = None 310 | 311 | self.listSize -= n 312 | 313 | # This method adjusts the ordering of the doubly linked list so that 314 | # 'node' directly precedes the 'head' node. Because of the order of 315 | # operations, if 'node' already directly precedes the 'head' node, or if 316 | # 'node' is the 'head' node, the order of the list will be unchanged. 317 | def mtf(self, node): 318 | node.prev.next = node.next 319 | node.next.prev = node.prev 320 | 321 | node.prev = self.head.prev 322 | node.next = self.head.prev.next 323 | 324 | node.next.prev = node 325 | node.prev.next = node 326 | 327 | # This method returns an iterator that iterates over the non-empty nodes 328 | # in the doubly linked list in order from the most recently to the least 329 | # recently used. 330 | def dli(self): 331 | node = self.head 332 | for i in range(len(self.table)): 333 | yield node 334 | node = node.next 335 | 336 | # The methods __getstate__() and __setstate__() are used to correctly 337 | # support the copy and pickle modules from the standard library. In 338 | # particular, the doubly linked list trips up the introspection machinery 339 | # used by copy/pickle. 340 | def __getstate__(self): 341 | # Copy the instance attributes. 342 | d = self.__dict__.copy() 343 | 344 | # Remove those that we need to do by hand. 345 | del d['table'] 346 | del d['head'] 347 | 348 | # Package up the key/value pairs from the doubly linked list into a 349 | # normal list that can be copied/pickled correctly. We put the 350 | # key/value pairs into the list in order, as returned by dli(), from 351 | # most recently to least recently used, so that the copy can be 352 | # restored with the same ordering. 353 | elements = [(node.key, node.value) for node in self.dli()] 354 | return (d, elements) 355 | 356 | def __setstate__(self, state): 357 | d = state[0] 358 | elements = state[1] 359 | 360 | # Restore the instance attributes, except for the table and head. 361 | self.__dict__.update(d) 362 | 363 | # Rebuild the table and doubly linked list from the simple list of 364 | # key/value pairs in 'elements'. 365 | 366 | # The listSize is the size of the original cache. We want this cache 367 | # to have the same size, but we need to reset it temporarily to set up 368 | # table and head correctly, so save a copy of the size. 369 | size = self.listSize 370 | 371 | # Setup a table and double linked list. This is identical to the way 372 | # __init__() does it. 373 | self.table = {} 374 | 375 | self.head = _dlnode() 376 | self.head.next = self.head 377 | self.head.prev = self.head 378 | 379 | self.listSize = 1 380 | 381 | # Now adjust the list to the desired size. 382 | self.size(size) 383 | 384 | # Fill the cache with the keys/values. Because inserted items are 385 | # moved to the top of the doubly linked list, we insert the key/value 386 | # pairs in reverse order. This ensures that the order of the doubly 387 | # linked list is identical to the original cache. 388 | for key, value in reversed(elements): 389 | self[key] = value 390 | 391 | 392 | class WriteThroughCacheManager(object): 393 | def __init__(self, store, size): 394 | self.store = store 395 | self.cache = lrucache(size) 396 | 397 | def __len__(self): 398 | return len(self.store) 399 | 400 | # Returns/sets the size of the managed cache. 401 | def size(self, size=None): 402 | return self.cache.size(size) 403 | 404 | def clear(self): 405 | self.cache.clear() 406 | self.store.clear() 407 | 408 | def __contains__(self, key): 409 | # Check the cache first. If it is there we can return quickly. 410 | if key in self.cache: 411 | return True 412 | 413 | # Not in the cache. Might be in the underlying store. 414 | if key in self.store: 415 | return True 416 | 417 | return False 418 | 419 | def __getitem__(self, key): 420 | # Try the cache first. If successful we can just return the value. 421 | if key in self.cache: 422 | return self.cache[key] 423 | 424 | # It wasn't in the cache. Look it up in the store, add the entry to 425 | # the cache, and return the value. 426 | value = self.store[key] 427 | self.cache[key] = value 428 | return value 429 | 430 | def get(self, key, default=None): 431 | try: 432 | return self[key] 433 | except KeyError: 434 | return default 435 | 436 | def __setitem__(self, key, value): 437 | # Add the key/value pair to the cache and store. 438 | self.cache[key] = value 439 | self.store[key] = value 440 | 441 | def __delitem__(self, key): 442 | # With write-through behavior the cache and store should be consistent. 443 | # Delete it from the store. 444 | del self.store[key] 445 | 446 | # It might also be in the cache, try to delete it. If it is not, we 447 | # will catch KeyError and ignore it. 448 | try: 449 | del self.cache[key] 450 | except KeyError: 451 | pass 452 | 453 | def __iter__(self): 454 | return self.keys() 455 | 456 | def keys(self): 457 | return self.store.keys() 458 | 459 | def values(self): 460 | return self.store.values() 461 | 462 | def items(self): 463 | return self.store.items() 464 | 465 | 466 | class WriteBackCacheManager(object): 467 | def __init__(self, store, size): 468 | self.store = store 469 | 470 | # Create a set to hold the dirty keys. 471 | self.dirty = set() 472 | 473 | # Define a callback function to be called by the cache when a 474 | # key/value pair is about to be ejected. This callback will check to 475 | # see if the key is in the dirty set. If so, then it will update the 476 | # store object and remove the key from the dirty set. 477 | def callback(key, value): 478 | if key in self.dirty: 479 | self.store[key] = value 480 | self.dirty.remove(key) 481 | 482 | # Create a cache and give it the callback function. 483 | self.cache = lrucache(size, callback) 484 | 485 | # Returns/sets the size of the managed cache. 486 | def size(self, size=None): 487 | return self.cache.size(size) 488 | 489 | def len(self): 490 | self.sync() 491 | return len(self.store) 492 | 493 | def clear(self): 494 | self.cache.clear() 495 | self.dirty.clear() 496 | self.store.clear() 497 | 498 | def __contains__(self, key): 499 | # Check the cache first, since if it is there we can return quickly. 500 | if key in self.cache: 501 | return True 502 | 503 | # Not in the cache. Might be in the underlying store. 504 | if key in self.store: 505 | return True 506 | 507 | return False 508 | 509 | def __getitem__(self, key): 510 | # Try the cache first. If successful we can just return the value. 511 | if key in self.cache: 512 | return self.cache[key] 513 | 514 | # It wasn't in the cache. Look it up in the store, add the entry to 515 | # the cache, and return the value. 516 | value = self.store[key] 517 | self.cache[key] = value 518 | return value 519 | 520 | def get(self, key, default=None): 521 | try: 522 | return self[key] 523 | except KeyError: 524 | return default 525 | 526 | def __setitem__(self, key, value): 527 | # Add the key/value pair to the cache. 528 | self.cache[key] = value 529 | self.dirty.add(key) 530 | 531 | def __delitem__(self, key): 532 | found = False 533 | try: 534 | del self.cache[key] 535 | found = True 536 | self.dirty.remove(key) 537 | except KeyError: 538 | pass 539 | 540 | try: 541 | del self.store[key] 542 | found = True 543 | except KeyError: 544 | pass 545 | 546 | if not found: # If not found in cache or store, raise error. 547 | raise KeyError 548 | 549 | def __iter__(self): 550 | return self.keys() 551 | 552 | def keys(self): 553 | for key in self.store.keys(): 554 | if key not in self.dirty: 555 | yield key 556 | 557 | for key in self.dirty: 558 | yield key 559 | 560 | def values(self): 561 | for key, value in self.items(): 562 | yield value 563 | 564 | def items(self): 565 | for key, value in self.store.items(): 566 | if key not in self.dirty: 567 | yield (key, value) 568 | 569 | for key in self.dirty: 570 | value = self.cache.peek(key) 571 | yield (key, value) 572 | 573 | def sync(self): 574 | # For each dirty key, peek at its value in the cache and update the 575 | # store. Doesn't change the cache's order. 576 | for key in self.dirty: 577 | self.store[key] = self.cache.peek(key) 578 | # There are no dirty keys now. 579 | self.dirty.clear() 580 | 581 | def flush(self): 582 | self.sync() 583 | self.cache.clear() 584 | 585 | def __enter__(self): 586 | return self 587 | 588 | def __exit__(self, exc_type, exc_val, exc_tb): 589 | self.sync() 590 | return False 591 | 592 | 593 | class FunctionCacheManager(object): 594 | def __init__(self, func, size, callback=None): 595 | self.func = func 596 | self.cache = lrucache(size, callback) 597 | 598 | def size(self, size=None): 599 | return self.cache.size(size) 600 | 601 | def clear(self): 602 | self.cache.clear() 603 | 604 | def __call__(self, *args, **kwargs): 605 | kwtuple = tuple((key, kwargs[key]) for key in sorted(kwargs.keys())) 606 | key = (args, kwtuple) 607 | try: 608 | return self.cache[key] 609 | except KeyError: 610 | pass 611 | 612 | value = self.func(*args, **kwargs) 613 | self.cache[key] = value 614 | return value 615 | 616 | 617 | def lruwrap(store, size, writeback=False): 618 | if writeback: 619 | return WriteBackCacheManager(store, size) 620 | else: 621 | return WriteThroughCacheManager(store, size) 622 | 623 | import functools 624 | 625 | class lrudecorator(object): 626 | def __init__(self, size, callback=None): 627 | self.cache = lrucache(size, callback) 628 | 629 | def __call__(self, func): 630 | def wrapper(*args, **kwargs): 631 | kwtuple = tuple((key, kwargs[key]) for key in sorted(kwargs.keys())) 632 | key = (args, kwtuple) 633 | try: 634 | return self.cache[key] 635 | except KeyError: 636 | pass 637 | 638 | value = func(*args, **kwargs) 639 | self.cache[key] = value 640 | return value 641 | 642 | wrapper.cache = self.cache 643 | wrapper.size = self.cache.size 644 | wrapper.clear = self.cache.clear 645 | return functools.update_wrapper(wrapper, func) 646 | --------------------------------------------------------------------------------