diff options
Diffstat (limited to 'third_party/python/pylru')
-rw-r--r-- | third_party/python/pylru/LICENSE.txt | 339 | ||||
-rw-r--r-- | third_party/python/pylru/PKG-INFO | 263 | ||||
-rw-r--r-- | third_party/python/pylru/README.txt | 245 | ||||
-rw-r--r-- | third_party/python/pylru/pylru.py | 556 | ||||
-rw-r--r-- | third_party/python/pylru/setup.py | 23 | ||||
-rw-r--r-- | third_party/python/pylru/test.py | 238 |
6 files changed, 1664 insertions, 0 deletions
diff --git a/third_party/python/pylru/LICENSE.txt b/third_party/python/pylru/LICENSE.txt new file mode 100644 index 0000000000..d159169d10 --- /dev/null +++ b/third_party/python/pylru/LICENSE.txt @@ -0,0 +1,339 @@ + GNU GENERAL PUBLIC LICENSE + Version 2, June 1991 + + Copyright (C) 1989, 1991 Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA + Everyone is permitted to copy and distribute verbatim copies + of this license document, but changing it is not allowed. + + Preamble + + The licenses for most software are designed to take away your +freedom to share and change it. By contrast, the GNU General Public +License is intended to guarantee your freedom to share and change free +software--to make sure the software is free for all its users. This +General Public License applies to most of the Free Software +Foundation's software and to any other program whose authors commit to +using it. (Some other Free Software Foundation software is covered by +the GNU Lesser General Public License instead.) You can apply it to +your programs, too. + + When we speak of free software, we are referring to freedom, not +price. Our General Public Licenses are designed to make sure that you +have the freedom to distribute copies of free software (and charge for +this service if you wish), that you receive source code or can get it +if you want it, that you can change the software or use pieces of it +in new free programs; and that you know you can do these things. + + To protect your rights, we need to make restrictions that forbid +anyone to deny you these rights or to ask you to surrender the rights. +These restrictions translate to certain responsibilities for you if you +distribute copies of the software, or if you modify it. + + For example, if you distribute copies of such a program, whether +gratis or for a fee, you must give the recipients all the rights that +you have. You must make sure that they, too, receive or can get the +source code. And you must show them these terms so they know their +rights. + + We protect your rights with two steps: (1) copyright the software, and +(2) offer you this license which gives you legal permission to copy, +distribute and/or modify the software. + + Also, for each author's protection and ours, we want to make certain +that everyone understands that there is no warranty for this free +software. If the software is modified by someone else and passed on, we +want its recipients to know that what they have is not the original, so +that any problems introduced by others will not reflect on the original +authors' reputations. + + Finally, any free program is threatened constantly by software +patents. We wish to avoid the danger that redistributors of a free +program will individually obtain patent licenses, in effect making the +program proprietary. To prevent this, we have made it clear that any +patent must be licensed for everyone's free use or not licensed at all. + + The precise terms and conditions for copying, distribution and +modification follow. + + GNU GENERAL PUBLIC LICENSE + TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION + + 0. This License applies to any program or other work which contains +a notice placed by the copyright holder saying it may be distributed +under the terms of this General Public License. The "Program", below, +refers to any such program or work, and a "work based on the Program" +means either the Program or any derivative work under copyright law: +that is to say, a work containing the Program or a portion of it, +either verbatim or with modifications and/or translated into another +language. (Hereinafter, translation is included without limitation in +the term "modification".) Each licensee is addressed as "you". + +Activities other than copying, distribution and modification are not +covered by this License; they are outside its scope. The act of +running the Program is not restricted, and the output from the Program +is covered only if its contents constitute a work based on the +Program (independent of having been made by running the Program). +Whether that is true depends on what the Program does. + + 1. You may copy and distribute verbatim copies of the Program's +source code as you receive it, in any medium, provided that you +conspicuously and appropriately publish on each copy an appropriate +copyright notice and disclaimer of warranty; keep intact all the +notices that refer to this License and to the absence of any warranty; +and give any other recipients of the Program a copy of this License +along with the Program. + +You may charge a fee for the physical act of transferring a copy, and +you may at your option offer warranty protection in exchange for a fee. + + 2. You may modify your copy or copies of the Program or any portion +of it, thus forming a work based on the Program, and copy and +distribute such modifications or work under the terms of Section 1 +above, provided that you also meet all of these conditions: + + a) You must cause the modified files to carry prominent notices + stating that you changed the files and the date of any change. + + b) You must cause any work that you distribute or publish, that in + whole or in part contains or is derived from the Program or any + part thereof, to be licensed as a whole at no charge to all third + parties under the terms of this License. + + c) If the modified program normally reads commands interactively + when run, you must cause it, when started running for such + interactive use in the most ordinary way, to print or display an + announcement including an appropriate copyright notice and a + notice that there is no warranty (or else, saying that you provide + a warranty) and that users may redistribute the program under + these conditions, and telling the user how to view a copy of this + License. (Exception: if the Program itself is interactive but + does not normally print such an announcement, your work based on + the Program is not required to print an announcement.) + +These requirements apply to the modified work as a whole. If +identifiable sections of that work are not derived from the Program, +and can be reasonably considered independent and separate works in +themselves, then this License, and its terms, do not apply to those +sections when you distribute them as separate works. But when you +distribute the same sections as part of a whole which is a work based +on the Program, the distribution of the whole must be on the terms of +this License, whose permissions for other licensees extend to the +entire whole, and thus to each and every part regardless of who wrote it. + +Thus, it is not the intent of this section to claim rights or contest +your rights to work written entirely by you; rather, the intent is to +exercise the right to control the distribution of derivative or +collective works based on the Program. + +In addition, mere aggregation of another work not based on the Program +with the Program (or with a work based on the Program) on a volume of +a storage or distribution medium does not bring the other work under +the scope of this License. + + 3. You may copy and distribute the Program (or a work based on it, +under Section 2) in object code or executable form under the terms of +Sections 1 and 2 above provided that you also do one of the following: + + a) Accompany it with the complete corresponding machine-readable + source code, which must be distributed under the terms of Sections + 1 and 2 above on a medium customarily used for software interchange; or, + + b) Accompany it with a written offer, valid for at least three + years, to give any third party, for a charge no more than your + cost of physically performing source distribution, a complete + machine-readable copy of the corresponding source code, to be + distributed under the terms of Sections 1 and 2 above on a medium + customarily used for software interchange; or, + + c) Accompany it with the information you received as to the offer + to distribute corresponding source code. (This alternative is + allowed only for noncommercial distribution and only if you + received the program in object code or executable form with such + an offer, in accord with Subsection b above.) + +The source code for a work means the preferred form of the work for +making modifications to it. For an executable work, complete source +code means all the source code for all modules it contains, plus any +associated interface definition files, plus the scripts used to +control compilation and installation of the executable. However, as a +special exception, the source code distributed need not include +anything that is normally distributed (in either source or binary +form) with the major components (compiler, kernel, and so on) of the +operating system on which the executable runs, unless that component +itself accompanies the executable. + +If distribution of executable or object code is made by offering +access to copy from a designated place, then offering equivalent +access to copy the source code from the same place counts as +distribution of the source code, even though third parties are not +compelled to copy the source along with the object code. + + 4. You may not copy, modify, sublicense, or distribute the Program +except as expressly provided under this License. Any attempt +otherwise to copy, modify, sublicense or distribute the Program is +void, and will automatically terminate your rights under this License. +However, parties who have received copies, or rights, from you under +this License will not have their licenses terminated so long as such +parties remain in full compliance. + + 5. You are not required to accept this License, since you have not +signed it. However, nothing else grants you permission to modify or +distribute the Program or its derivative works. These actions are +prohibited by law if you do not accept this License. Therefore, by +modifying or distributing the Program (or any work based on the +Program), you indicate your acceptance of this License to do so, and +all its terms and conditions for copying, distributing or modifying +the Program or works based on it. + + 6. Each time you redistribute the Program (or any work based on the +Program), the recipient automatically receives a license from the +original licensor to copy, distribute or modify the Program subject to +these terms and conditions. You may not impose any further +restrictions on the recipients' exercise of the rights granted herein. +You are not responsible for enforcing compliance by third parties to +this License. + + 7. If, as a consequence of a court judgment or allegation of patent +infringement or for any other reason (not limited to patent issues), +conditions are imposed on you (whether by court order, agreement or +otherwise) that contradict the conditions of this License, they do not +excuse you from the conditions of this License. If you cannot +distribute so as to satisfy simultaneously your obligations under this +License and any other pertinent obligations, then as a consequence you +may not distribute the Program at all. For example, if a patent +license would not permit royalty-free redistribution of the Program by +all those who receive copies directly or indirectly through you, then +the only way you could satisfy both it and this License would be to +refrain entirely from distribution of the Program. + +If any portion of this section is held invalid or unenforceable under +any particular circumstance, the balance of the section is intended to +apply and the section as a whole is intended to apply in other +circumstances. + +It is not the purpose of this section to induce you to infringe any +patents or other property right claims or to contest validity of any +such claims; this section has the sole purpose of protecting the +integrity of the free software distribution system, which is +implemented by public license practices. Many people have made +generous contributions to the wide range of software distributed +through that system in reliance on consistent application of that +system; it is up to the author/donor to decide if he or she is willing +to distribute software through any other system and a licensee cannot +impose that choice. + +This section is intended to make thoroughly clear what is believed to +be a consequence of the rest of this License. + + 8. If the distribution and/or use of the Program is restricted in +certain countries either by patents or by copyrighted interfaces, the +original copyright holder who places the Program under this License +may add an explicit geographical distribution limitation excluding +those countries, so that distribution is permitted only in or among +countries not thus excluded. In such case, this License incorporates +the limitation as if written in the body of this License. + + 9. The Free Software Foundation may publish revised and/or new versions +of the General Public License from time to time. Such new versions will +be similar in spirit to the present version, but may differ in detail to +address new problems or concerns. + +Each version is given a distinguishing version number. If the Program +specifies a version number of this License which applies to it and "any +later version", you have the option of following the terms and conditions +either of that version or of any later version published by the Free +Software Foundation. If the Program does not specify a version number of +this License, you may choose any version ever published by the Free Software +Foundation. + + 10. If you wish to incorporate parts of the Program into other free +programs whose distribution conditions are different, write to the author +to ask for permission. For software which is copyrighted by the Free +Software Foundation, write to the Free Software Foundation; we sometimes +make exceptions for this. Our decision will be guided by the two goals +of preserving the free status of all derivatives of our free software and +of promoting the sharing and reuse of software generally. + + NO WARRANTY + + 11. BECAUSE THE PROGRAM IS LICENSED FREE OF CHARGE, THERE IS NO WARRANTY +FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE LAW. EXCEPT WHEN +OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR OTHER PARTIES +PROVIDE THE PROGRAM "AS IS" WITHOUT WARRANTY OF ANY KIND, EITHER EXPRESSED +OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF +MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE ENTIRE RISK AS +TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU. SHOULD THE +PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY SERVICING, +REPAIR OR CORRECTION. + + 12. IN NO EVENT UNLESS REQUIRED BY APPLICABLE LAW OR AGREED TO IN WRITING +WILL ANY COPYRIGHT HOLDER, OR ANY OTHER PARTY WHO MAY MODIFY AND/OR +REDISTRIBUTE THE PROGRAM AS PERMITTED ABOVE, BE LIABLE TO YOU FOR DAMAGES, +INCLUDING ANY GENERAL, SPECIAL, INCIDENTAL OR CONSEQUENTIAL DAMAGES ARISING +OUT OF THE USE OR INABILITY TO USE THE PROGRAM (INCLUDING BUT NOT LIMITED +TO LOSS OF DATA OR DATA BEING RENDERED INACCURATE OR LOSSES SUSTAINED BY +YOU OR THIRD PARTIES OR A FAILURE OF THE PROGRAM TO OPERATE WITH ANY OTHER +PROGRAMS), EVEN IF SUCH HOLDER OR OTHER PARTY HAS BEEN ADVISED OF THE +POSSIBILITY OF SUCH DAMAGES. + + END OF TERMS AND CONDITIONS + + How to Apply These Terms to Your New Programs + + If you develop a new program, and you want it to be of the greatest +possible use to the public, the best way to achieve this is to make it +free software which everyone can redistribute and change under these terms. + + To do so, attach the following notices to the program. It is safest +to attach them to the start of each source file to most effectively +convey the exclusion of warranty; and each file should have at least +the "copyright" line and a pointer to where the full notice is found. + + <one line to give the program's name and a brief idea of what it does.> + Copyright (C) <year> <name of author> + + This program is free software; you can redistribute it and/or modify + it under the terms of the GNU General Public License as published by + the Free Software Foundation; either version 2 of the License, or + (at your option) any later version. + + This program is distributed in the hope that it will be useful, + but WITHOUT ANY WARRANTY; without even the implied warranty of + MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the + GNU General Public License for more details. + + You should have received a copy of the GNU General Public License along + with this program; if not, write to the Free Software Foundation, Inc., + 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + +Also add information on how to contact you by electronic and paper mail. + +If the program is interactive, make it output a short notice like this +when it starts in an interactive mode: + + Gnomovision version 69, Copyright (C) year name of author + Gnomovision comes with ABSOLUTELY NO WARRANTY; for details type `show w'. + This is free software, and you are welcome to redistribute it + under certain conditions; type `show c' for details. + +The hypothetical commands `show w' and `show c' should show the appropriate +parts of the General Public License. Of course, the commands you use may +be called something other than `show w' and `show c'; they could even be +mouse-clicks or menu items--whatever suits your program. + +You should also get your employer (if you work as a programmer) or your +school, if any, to sign a "copyright disclaimer" for the program, if +necessary. Here is a sample; alter the names: + + Yoyodyne, Inc., hereby disclaims all copyright interest in the program + `Gnomovision' (which makes passes at compilers) written by James Hacker. + + <signature of Ty Coon>, 1 April 1989 + Ty Coon, President of Vice + +This General Public License does not permit incorporating your program into +proprietary programs. If your program is a subroutine library, you may +consider it more useful to permit linking proprietary applications with the +library. If this is what you want to do, use the GNU Lesser General +Public License instead of this License. diff --git a/third_party/python/pylru/PKG-INFO b/third_party/python/pylru/PKG-INFO new file mode 100644 index 0000000000..d0e146d616 --- /dev/null +++ b/third_party/python/pylru/PKG-INFO @@ -0,0 +1,263 @@ +Metadata-Version: 1.1 +Name: pylru +Version: 1.0.9 +Summary: A least recently used (LRU) cache implementation +Home-page: https://github.com/jlhutch/pylru +Author: Jay Hutchinson +Author-email: jlhutch+pylru@gmail.com +License: UNKNOWN +Description: + + PyLRU + ===== + + A least recently used (LRU) cache for Python. + + Introduction + ============ + + 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. + + 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. + + Usage + ===== + + lrucache + -------- + + An lrucache object has a dictionary like interface and can be used in the same way:: + + import pylru + + size = 100 # Size of the cache. The maximum number of key/value + # pairs you want the cache to hold. + + cache = pylru.lrucache(size) + # Create a cache object. + + value = cache[key] # Lookup a value given its key. + cache[key] = value # Insert a key/value pair. + del cache[key] # Delete a value given its key. + # + # These three operations affect the order of the cache. + # Lookup and insert both move the key/value to the most + # recently used position. Delete (obviously) removes a + # key/value from whatever position it was in. + + key in cache # Test for membership. Does not affect the cache order. + + value = cache.peek(key) + # Lookup a value given its key. Does not affect the + # cache order. + + cache.keys() # Return an iterator over the keys in the cache + cache.values() # Return an iterator over the values in the cache + cache.items() # Return an iterator over the (key, value) pairs in the + # cache. + # + # These calls have no effect on the cache order. + # lrucache is scan resistant when these calls are used. + # The iterators iterate over their respective elements + # in the order of most recently used to least recently + # used. + # + # WARNING - While these iterators do not affect the + # cache order the lookup, insert, and delete operations + # do. The result of changing the cache's order + # during iteration is undefined. If you really need to + # do something of the sort use list(cache.keys()), then + # loop over the list elements. + + for key in cache: # Caches support __iter__ so you can use them directly + pass # in a for loop to loop over the keys just like + # cache.keys() + + cache.size() # Returns the size of the cache + cache.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + x = len(cache) # Returns the number of items stored in the cache. + # x will be less than or equal to cache.size() + + cache.clear() # Remove all items from the cache. + + + 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:: + + import pylru + + def callback(key, value): + print (key, value) # A dumb callback that just prints the key/value + + size = 100 + cache = pylru.lrucache(size, callback) + + # Use the cache... When it gets full some pairs may be ejected due to + # the fixed cache size. But, not before the callback is called to let you + # know. + + WriteThroughCacheManager + ------------------------ + + 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. + + 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. + + 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:: + + import pylru + + size = 100 + cached = pylru.WriteThroughCacheManager(store, size) + # Or + cached = pylru.lruwrap(store, size) + # This is a factory function that does the same thing. + + # Now the object *cached* can be used just like store, except caching is + # automatically handled. + + value = cached[key] # Lookup a value given its key. + cached[key] = value # Insert a key/value pair. + del cached[key] # Delete a value given its key. + + key in cache # Test for membership. Does not affect the cache order. + + cached.keys() # Returns store.keys() + cached.values() # Returns store.values() + cached.items() # Returns store.items() + # + # These calls have no effect on the cache order. + # The iterators iterate over their respective elements + # in the order dictated by store. + + for key in cached: # Same as store.keys() + + cached.size() # Returns the size of the cache + cached.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + x = len(cached) # Returns the number of items stored in the store. + + cached.clear() # Remove all items from the store and cache. + + + WriteBackCacheManager + --------------------- + + 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:: + + + import pylru + + size = 100 + cached = pylru.WriteBackCacheManager(store, size) + # Or + cached = pylru.lruwrap(store, size, True) + # This is a factory function that does the same thing. + + value = cached[key] # Lookup a value given its key. + cached[key] = value # Insert a key/value pair. + del cached[key] # Delete a value given its key. + + key in cache # Test for membership. Does not affect the cache order. + + + cached.keys() # Return an iterator over the keys in the cache/store + cached.values() # Return an iterator over the values in the cache/store + cached.items() # Return an iterator over the (key, value) pairs in the + # cache/store. + # + # The iterators iterate over a consistent view of the + # respective elements. That is, except for the order, + # the elements are the same as those returned if you + # first called sync() then called + # store.keys()[ or values() or items()] + # + # These calls have no effect on the cache order. + # The iterators iterate over their respective elements + # in arbitrary order. + # + # WARNING - While these iterators do not effect the + # cache order the lookup, insert, and delete operations + # do. The results of changing the cache's order + # during iteration is undefined. If you really need to + # do something of the sort use list(cached.keys()), + # then loop over the list elements. + + for key in cached: # Same as cached.keys() + + cached.size() # Returns the size of the cache + cached.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + cached.clear() # Remove all items from the store and cache. + + cached.sync() # Make the store and cache consistent. Write all + # cached changes to the store that have not been + # yet. + + cached.flush() # Calls sync() then clears the cache. + + + To help the programmer ensure that the final sync() is called, WriteBackCacheManager objects can be used in a with statement:: + + with pylru.WriteBackCacheManager(store, size) as cached: + # Use cached just like you would store. sync() is called automatically + # for you when leaving the with statement block. + + + FunctionCacheManager + --------------------- + + 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 fuction must have arguments that are hashable:: + + import pylru + + def square(x): + return x * x + + size = 100 + cached = pylru.FunctionCacheManager(square, size) + + y = cached(7) + + # The results of cached are the same as square, but automatically cached + # to speed up future calls. + + cached.size() # Returns the size of the cache + cached.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + cached.clear() # Remove all items from the cache. + + + + lrudecorator + ------------ + + PyLRU also provides a function decorator. This is basically the same functionality as FunctionCacheManager, but in the form of a decorator:: + + from pylru import lrudecorator + + @lrudecorator(100) + def square(x): + return x * x + + # The results of the square function are cached to speed up future calls. + + square.size() # Returns the size of the cache + square.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + square.clear() # Remove all items from the cache. + +Platform: UNKNOWN +Classifier: Programming Language :: Python :: 2.6 +Classifier: Programming Language :: Python :: 2.7 +Classifier: Programming Language :: Python :: 3 +Classifier: Development Status :: 5 - Production/Stable +Classifier: Intended Audience :: Developers +Classifier: License :: OSI Approved :: GNU General Public License (GPL) +Classifier: Operating System :: OS Independent +Classifier: Topic :: Software Development :: Libraries :: Python Modules diff --git a/third_party/python/pylru/README.txt b/third_party/python/pylru/README.txt new file mode 100644 index 0000000000..f37c9ccdca --- /dev/null +++ b/third_party/python/pylru/README.txt @@ -0,0 +1,245 @@ + + +PyLRU +===== + +A least recently used (LRU) cache for Python. + +Introduction +============ + +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. + +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. + +Usage +===== + +lrucache +-------- + +An lrucache object has a dictionary like interface and can be used in the same way:: + + import pylru + + size = 100 # Size of the cache. The maximum number of key/value + # pairs you want the cache to hold. + + cache = pylru.lrucache(size) + # Create a cache object. + + value = cache[key] # Lookup a value given its key. + cache[key] = value # Insert a key/value pair. + del cache[key] # Delete a value given its key. + # + # These three operations affect the order of the cache. + # Lookup and insert both move the key/value to the most + # recently used position. Delete (obviously) removes a + # key/value from whatever position it was in. + + key in cache # Test for membership. Does not affect the cache order. + + value = cache.peek(key) + # Lookup a value given its key. Does not affect the + # cache order. + + cache.keys() # Return an iterator over the keys in the cache + cache.values() # Return an iterator over the values in the cache + cache.items() # Return an iterator over the (key, value) pairs in the + # cache. + # + # These calls have no effect on the cache order. + # lrucache is scan resistant when these calls are used. + # The iterators iterate over their respective elements + # in the order of most recently used to least recently + # used. + # + # WARNING - While these iterators do not affect the + # cache order the lookup, insert, and delete operations + # do. The result of changing the cache's order + # during iteration is undefined. If you really need to + # do something of the sort use list(cache.keys()), then + # loop over the list elements. + + for key in cache: # Caches support __iter__ so you can use them directly + pass # in a for loop to loop over the keys just like + # cache.keys() + + cache.size() # Returns the size of the cache + cache.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + x = len(cache) # Returns the number of items stored in the cache. + # x will be less than or equal to cache.size() + + cache.clear() # Remove all items from the cache. + + +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:: + + import pylru + + def callback(key, value): + print (key, value) # A dumb callback that just prints the key/value + + size = 100 + cache = pylru.lrucache(size, callback) + + # Use the cache... When it gets full some pairs may be ejected due to + # the fixed cache size. But, not before the callback is called to let you + # know. + +WriteThroughCacheManager +------------------------ + +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. + +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. + +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:: + + import pylru + + size = 100 + cached = pylru.WriteThroughCacheManager(store, size) + # Or + cached = pylru.lruwrap(store, size) + # This is a factory function that does the same thing. + + # Now the object *cached* can be used just like store, except caching is + # automatically handled. + + value = cached[key] # Lookup a value given its key. + cached[key] = value # Insert a key/value pair. + del cached[key] # Delete a value given its key. + + key in cache # Test for membership. Does not affect the cache order. + + cached.keys() # Returns store.keys() + cached.values() # Returns store.values() + cached.items() # Returns store.items() + # + # These calls have no effect on the cache order. + # The iterators iterate over their respective elements + # in the order dictated by store. + + for key in cached: # Same as store.keys() + + cached.size() # Returns the size of the cache + cached.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + x = len(cached) # Returns the number of items stored in the store. + + cached.clear() # Remove all items from the store and cache. + + +WriteBackCacheManager +--------------------- + +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:: + + + import pylru + + size = 100 + cached = pylru.WriteBackCacheManager(store, size) + # Or + cached = pylru.lruwrap(store, size, True) + # This is a factory function that does the same thing. + + value = cached[key] # Lookup a value given its key. + cached[key] = value # Insert a key/value pair. + del cached[key] # Delete a value given its key. + + key in cache # Test for membership. Does not affect the cache order. + + + cached.keys() # Return an iterator over the keys in the cache/store + cached.values() # Return an iterator over the values in the cache/store + cached.items() # Return an iterator over the (key, value) pairs in the + # cache/store. + # + # The iterators iterate over a consistent view of the + # respective elements. That is, except for the order, + # the elements are the same as those returned if you + # first called sync() then called + # store.keys()[ or values() or items()] + # + # These calls have no effect on the cache order. + # The iterators iterate over their respective elements + # in arbitrary order. + # + # WARNING - While these iterators do not effect the + # cache order the lookup, insert, and delete operations + # do. The results of changing the cache's order + # during iteration is undefined. If you really need to + # do something of the sort use list(cached.keys()), + # then loop over the list elements. + + for key in cached: # Same as cached.keys() + + cached.size() # Returns the size of the cache + cached.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + cached.clear() # Remove all items from the store and cache. + + cached.sync() # Make the store and cache consistent. Write all + # cached changes to the store that have not been + # yet. + + cached.flush() # Calls sync() then clears the cache. + + +To help the programmer ensure that the final sync() is called, WriteBackCacheManager objects can be used in a with statement:: + + with pylru.WriteBackCacheManager(store, size) as cached: + # Use cached just like you would store. sync() is called automatically + # for you when leaving the with statement block. + + +FunctionCacheManager +--------------------- + +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 fuction must have arguments that are hashable:: + + import pylru + + def square(x): + return x * x + + size = 100 + cached = pylru.FunctionCacheManager(square, size) + + y = cached(7) + + # The results of cached are the same as square, but automatically cached + # to speed up future calls. + + cached.size() # Returns the size of the cache + cached.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + cached.clear() # Remove all items from the cache. + + + +lrudecorator +------------ + +PyLRU also provides a function decorator. This is basically the same functionality as FunctionCacheManager, but in the form of a decorator:: + + from pylru import lrudecorator + + @lrudecorator(100) + def square(x): + return x * x + + # The results of the square function are cached to speed up future calls. + + square.size() # Returns the size of the cache + square.size(x) # Changes the size of the cache. x MUST be greater than + # zero. Returns the new size x. + + square.clear() # Remove all items from the cache. diff --git a/third_party/python/pylru/pylru.py b/third_party/python/pylru/pylru.py new file mode 100644 index 0000000000..e69cadb76c --- /dev/null +++ b/third_party/python/pylru/pylru.py @@ -0,0 +1,556 @@ + +# Cache implementaion with a Least Recently Used (LRU) replacement policy and +# a basic dictionary interface. + +# Copyright (C) 2006, 2009, 2010, 2011 Jay Hutchinson + +# This program is free software; you can redistribute it and/or modify it +# under the terms of the GNU General Public License as published by the Free +# Software Foundation; either version 2 of the License, or (at your option) +# any later version. + +# This program is distributed in the hope that it will be useful, but WITHOUT +# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or +# FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for +# more details. + +# You should have received a copy of the GNU General Public License along +# with this program; if not, write to the Free Software Foundation, Inc., 51 +# Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA. + + + +# The cache is implemented using a combination of a python dictionary (hash +# table) and a circular doubly linked list. Items in the cache are stored in +# nodes. These nodes make up the linked list. The list is used to efficiently +# maintain the order that the items have been used in. The front or head of +# the list contains the most recently used item, the tail of the list +# contains the least recently used item. When an item is used it can easily +# (in a constant amount of time) be moved to the front of the list, thus +# updating its position in the ordering. These nodes are also placed in the +# hash table under their associated key. The hash table allows efficient +# lookup of values by key. + +# Class for the node objects. +class _dlnode(object): + def __init__(self): + self.empty = True + + +class lrucache(object): + + def __init__(self, size, callback=None): + + self.callback = callback + + # Create an empty hash table. + self.table = {} + + # Initialize the doubly linked list with one empty node. This is an + # invariant. The cache size must always be greater than zero. Each + # node has a 'prev' and 'next' variable to hold the node that comes + # before it and after it respectively. Initially the two variables + # each point to the head node itself, creating a circular doubly + # linked list of size one. Then the size() method is used to adjust + # the list to the desired size. + + self.head = _dlnode() + self.head.next = self.head + self.head.prev = self.head + + self.listSize = 1 + + # Adjust the size + self.size(size) + + + def __len__(self): + return len(self.table) + + def clear(self): + for node in self.dli(): + node.empty = True + node.key = None + node.value = None + + self.table.clear() + + + def __contains__(self, key): + return key in self.table + + # Looks up a value in the cache without affecting cache order. + def peek(self, key): + # Look up the node + node = self.table[key] + return node.value + + + def __getitem__(self, key): + # Look up the node + node = self.table[key] + + # Update the list ordering. Move this node so that is directly + # proceeds the head node. Then set the 'head' variable to it. This + # makes it the new head of the list. + self.mtf(node) + self.head = node + + # Return the value. + return node.value + + def get(self, key, default=None): + """Get an item - return default (None) if not present""" + try: + return self[key] + except KeyError: + return default + + def __setitem__(self, key, value): + # First, see if any value is stored under 'key' in the cache already. + # If so we are going to replace that value with the new one. + if key in self.table: + + # Lookup the node + node = self.table[key] + + # Replace the value. + node.value = value + + # Update the list ordering. + self.mtf(node) + self.head = node + + return + + # Ok, no value is currently stored under 'key' in the cache. We need + # to choose a node to place the new item in. There are two cases. If + # the cache is full some item will have to be pushed out of the + # cache. We want to choose the node with the least recently used + # item. This is the node at the tail of the list. If the cache is not + # full we want to choose a node that is empty. Because of the way the + # list is managed, the empty nodes are always together at the tail + # end of the list. Thus, in either case, by chooseing the node at the + # tail of the list our conditions are satisfied. + + # Since the list is circular, the tail node directly preceeds the + # 'head' node. + node = self.head.prev + + # If the node already contains something we need to remove the old + # key from the dictionary. + if not node.empty: + if self.callback is not None: + self.callback(node.key, node.value) + del self.table[node.key] + + # Place the new key and value in the node + node.empty = False + node.key = key + node.value = value + + # Add the node to the dictionary under the new key. + self.table[key] = node + + # We need to move the node to the head of the list. The node is the + # tail node, so it directly preceeds the head node due to the list + # being circular. Therefore, the ordering is already correct, we just + # need to adjust the 'head' variable. + self.head = node + + + def __delitem__(self, key): + + # Lookup the node, then remove it from the hash table. + node = self.table[key] + del self.table[key] + + node.empty = True + + # Not strictly necessary. + node.key = None + node.value = None + + # Because this node is now empty we want to reuse it before any + # non-empty node. To do that we want to move it to the tail of the + # list. We move it so that it directly preceeds the 'head' node. This + # makes it the tail node. The 'head' is then adjusted. This + # adjustment ensures correctness even for the case where the 'node' + # is the 'head' node. + self.mtf(node) + self.head = node.next + + def __iter__(self): + + # Return an iterator that returns the keys in the cache in order from + # the most recently to least recently used. Does not modify the cache + # order. + for node in self.dli(): + yield node.key + + def items(self): + + # Return an iterator that returns the (key, value) pairs in the cache + # in order from the most recently to least recently used. Does not + # modify the cache order. + for node in self.dli(): + yield (node.key, node.value) + + def keys(self): + + # Return an iterator that returns the keys in the cache in order from + # the most recently to least recently used. Does not modify the cache + # order. + for node in self.dli(): + yield node.key + + def values(self): + + # Return an iterator that returns the values in the cache in order + # from the most recently to least recently used. Does not modify the + # cache order. + for node in self.dli(): + yield node.value + + def size(self, size=None): + + if size is not None: + assert size > 0 + if size > self.listSize: + self.addTailNode(size - self.listSize) + elif size < self.listSize: + self.removeTailNode(self.listSize - size) + + return self.listSize + + # Increases the size of the cache by inserting n empty nodes at the tail + # of the list. + def addTailNode(self, n): + for i in range(n): + node = _dlnode() + node.next = self.head + node.prev = self.head.prev + + self.head.prev.next = node + self.head.prev = node + + self.listSize += n + + # Decreases the size of the list by removing n nodes from the tail of the + # list. + def removeTailNode(self, n): + assert self.listSize > n + for i in range(n): + node = self.head.prev + if not node.empty: + if self.callback is not None: + self.callback(node.key, node.value) + del self.table[node.key] + + # Splice the tail node out of the list + self.head.prev = node.prev + node.prev.next = self.head + + # The next four lines are not strictly necessary. + node.prev = None + node.next = None + + node.key = None + node.value = None + + self.listSize -= n + + + # This method adjusts the ordering of the doubly linked list so that + # 'node' directly precedes the 'head' node. Because of the order of + # operations, if 'node' already directly precedes the 'head' node or if + # 'node' is the 'head' node the order of the list will be unchanged. + def mtf(self, node): + node.prev.next = node.next + node.next.prev = node.prev + + node.prev = self.head.prev + node.next = self.head.prev.next + + node.next.prev = node + node.prev.next = node + + # This method returns an iterator that iterates over the non-empty nodes + # in the doubly linked list in order from the most recently to the least + # recently used. + def dli(self): + node = self.head + for i in range(len(self.table)): + yield node + node = node.next + + + + +class WriteThroughCacheManager(object): + def __init__(self, store, size): + self.store = store + self.cache = lrucache(size) + + def __len__(self): + return len(self.store) + + # Returns/sets the size of the managed cache. + def size(self, size=None): + return self.cache.size(size) + + def clear(self): + self.cache.clear() + self.store.clear() + + def __contains__(self, key): + # Check the cache first. If it is there we can return quickly. + if key in self.cache: + return True + + # Not in the cache. Might be in the underlying store. + if key in self.store: + return True + + return False + + def __getitem__(self, key): + # First we try the cache. If successful we just return the value. If + # not we catch KeyError and ignore it since that just means the key + # was not in the cache. + try: + return self.cache[key] + except KeyError: + pass + + # It wasn't in the cache. Look it up in the store, add the entry to + # the cache, and return the value. + value = self.store[key] + self.cache[key] = value + return value + + def get(self, key, default=None): + """Get an item - return default (None) if not present""" + try: + return self[key] + except KeyError: + return default + + def __setitem__(self, key, value): + # Add the key/value pair to the cache and store. + self.cache[key] = value + self.store[key] = value + + def __delitem__(self, key): + # Write-through behavior cache and store should be consistent. Delete + # it from the store. + del self.store[key] + try: + # Ok, delete from the store was successful. It might also be in + # the cache, try and delete it. If not we catch the KeyError and + # ignore it. + del self.cache[key] + except KeyError: + pass + + def __iter__(self): + return self.keys() + + def keys(self): + return self.store.keys() + + def values(self): + return self.store.values() + + def items(self): + return self.store.items() + + + +class WriteBackCacheManager(object): + def __init__(self, store, size): + self.store = store + + # Create a set to hold the dirty keys. + self.dirty = set() + + # Define a callback function to be called by the cache when a + # key/value pair is about to be ejected. This callback will check to + # see if the key is in the dirty set. If so, then it will update the + # store object and remove the key from the dirty set. + def callback(key, value): + if key in self.dirty: + self.store[key] = value + self.dirty.remove(key) + + # Create a cache and give it the callback function. + self.cache = lrucache(size, callback) + + # Returns/sets the size of the managed cache. + def size(self, size=None): + return self.cache.size(size) + + def clear(self): + self.cache.clear() + self.dirty.clear() + self.store.clear() + + def __contains__(self, key): + # Check the cache first, since if it is there we can return quickly. + if key in self.cache: + return True + + # Not in the cache. Might be in the underlying store. + if key in self.store: + return True + + return False + + def __getitem__(self, key): + # First we try the cache. If successful we just return the value. If + # not we catch KeyError and ignore it since that just means the key + # was not in the cache. + try: + return self.cache[key] + except KeyError: + pass + + # It wasn't in the cache. Look it up in the store, add the entry to + # the cache, and return the value. + value = self.store[key] + self.cache[key] = value + return value + + def get(self, key, default=None): + """Get an item - return default (None) if not present""" + try: + return self[key] + except KeyError: + return default + + def __setitem__(self, key, value): + # Add the key/value pair to the cache. + self.cache[key] = value + self.dirty.add(key) + + def __delitem__(self, key): + + found = False + try: + del self.cache[key] + found = True + self.dirty.remove(key) + except KeyError: + pass + + try: + del self.store[key] + found = True + except KeyError: + pass + + if not found: # If not found in cache or store, raise error. + raise KeyError + + + def __iter__(self): + return self.keys() + + def keys(self): + for key in self.store.keys(): + if key not in self.dirty: + yield key + + for key in self.dirty: + yield key + + + def values(self): + for key, value in self.items(): + yield value + + + def items(self): + for key, value in self.store.items(): + if key not in self.dirty: + yield (key, value) + + for key in self.dirty: + value = self.cache.peek(key) + yield (key, value) + + + + def sync(self): + # For each dirty key, peek at its value in the cache and update the + # store. Doesn't change the cache's order. + for key in self.dirty: + self.store[key] = self.cache.peek(key) + # There are no dirty keys now. + self.dirty.clear() + + def flush(self): + self.sync() + self.cache.clear() + + def __enter__(self): + return self + + def __exit__(self, exc_type, exc_val, exc_tb): + self.sync() + return False + + +class FunctionCacheManager(object): + def __init__(self, func, size): + self.func = func + self.cache = lrucache(size) + + def size(self, size=None): + return self.cache.size(size) + + def clear(self): + self.cache.clear() + + def __call__(self, *args, **kwargs): + kwtuple = tuple((key, kwargs[key]) for key in sorted(kwargs.keys())) + key = (args, kwtuple) + try: + return self.cache[key] + except KeyError: + pass + + value = self.func(*args, **kwargs) + self.cache[key] = value + return value + + +def lruwrap(store, size, writeback=False): + if writeback: + return WriteBackCacheManager(store, size) + else: + return WriteThroughCacheManager(store, size) + +import functools + +class lrudecorator(object): + def __init__(self, size): + self.cache = lrucache(size) + + def __call__(self, func): + def wrapper(*args, **kwargs): + kwtuple = tuple((key, kwargs[key]) for key in sorted(kwargs.keys())) + key = (args, kwtuple) + try: + return self.cache[key] + except KeyError: + pass + + value = func(*args, **kwargs) + self.cache[key] = value + return value + + wrapper.cache = self.cache + wrapper.size = self.cache.size + wrapper.clear = self.cache.clear + return functools.update_wrapper(wrapper, func) diff --git a/third_party/python/pylru/setup.py b/third_party/python/pylru/setup.py new file mode 100644 index 0000000000..66d441ca94 --- /dev/null +++ b/third_party/python/pylru/setup.py @@ -0,0 +1,23 @@ +from distutils.core import setup + +setup( + name = "pylru", + version = "1.0.9", + py_modules=['pylru'], + description = "A least recently used (LRU) cache implementation", + author = "Jay Hutchinson", + author_email = "jlhutch+pylru@gmail.com", + url = "https://github.com/jlhutch/pylru", + classifiers = [ + "Programming Language :: Python :: 2.6", + "Programming Language :: Python :: 2.7", + "Programming Language :: Python :: 3", + "Development Status :: 5 - Production/Stable", + "Intended Audience :: Developers", + "License :: OSI Approved :: GNU General Public License (GPL)", + "Operating System :: OS Independent", + "Topic :: Software Development :: Libraries :: Python Modules", + ], + long_description=open('README.txt').read()) + + diff --git a/third_party/python/pylru/test.py b/third_party/python/pylru/test.py new file mode 100644 index 0000000000..7a4842fb52 --- /dev/null +++ b/third_party/python/pylru/test.py @@ -0,0 +1,238 @@ + +from pylru import * +import random + +# This tests PyLRU by fuzzing it with random operations, then checking the +# results against another, simpler, LRU cache implementation. + +class simplelrucache: + + def __init__(self, size): + + # Initialize the cache as empty. + self.cache = [] + self.size = size + + def __contains__(self, key): + + for x in self.cache: + if x[0] == key: + return True + + return False + + + def __getitem__(self, key): + + for i in range(len(self.cache)): + x = self.cache[i] + if x[0] == key: + del self.cache[i] + self.cache.append(x) + return x[1] + + raise KeyError + + + def __setitem__(self, key, value): + + for i in range(len(self.cache)): + x = self.cache[i] + if x[0] == key: + x[1] = value + del self.cache[i] + self.cache.append(x) + return + + if len(self.cache) == self.size: + self.cache = self.cache[1:] + + self.cache.append([key, value]) + + + def __delitem__(self, key): + + for i in range(len(self.cache)): + if self.cache[i][0] == key: + del self.cache[i] + return + + raise KeyError + + def resize(self, x=None): + assert x > 0 + self.size = x + if x < len(self.cache): + del self.cache[:len(self.cache) - x] + + +def test(a, b, c, d, verify): + + for i in range(1000): + x = random.randint(0, 512) + y = random.randint(0, 512) + + a[x] = y + b[x] = y + verify(c, d) + + for i in range(1000): + x = random.randint(0, 512) + if x in a: + assert x in b + z = a[x] + z += b[x] + else: + assert x not in b + verify(c, d) + + for i in range(256): + x = random.randint(0, 512) + if x in a: + assert x in b + del a[x] + del b[x] + else: + assert x not in b + verify(c, d) + + +def testcache(): + def verify(a, b): + q = [] + z = a.head + for j in range(len(a.table)): + q.append([z.key, z.value]) + z = z.next + + assert q == b.cache[::-1] + + q2 = [] + for x, y in q: + q2.append((x, y)) + + assert list(a.items()) == q2 + assert list(zip(a.keys(), a.values())) == q2 + assert list(a.keys()) == list(a) + + + a = lrucache(128) + b = simplelrucache(128) + verify(a, b) + test(a, b, a, b, verify) + + a.size(71) + b.resize(71) + verify(a, b) + test(a, b, a, b, verify) + + a.size(341) + b.resize(341) + verify(a, b) + test(a, b, a, b, verify) + + a.size(127) + b.resize(127) + verify(a, b) + test(a, b, a, b, verify) + + +def wraptest(): + + def verify(p, x): + assert p == x.store + for key, value in x.cache.items(): + assert x.store[key] == value + + tmp = list(x.items()) + tmp.sort() + + tmp2 = list(p.items()) + tmp2.sort() + + assert tmp == tmp2 + + p = dict() + q = dict() + x = lruwrap(q, 128) + + test(p, x, p, x, verify) + + + +def wraptest2(): + + def verify(p, x): + for key, value in x.store.items(): + if key not in x.dirty: + assert p[key] == value + + for key in x.dirty: + assert x.cache.peek(key) == p[key] + + for key, value in x.cache.items(): + if key not in x.dirty: + assert x.store[key] == p[key] == value + + tmp = list(x.items()) + tmp.sort() + + tmp2 = list(p.items()) + tmp2.sort() + + assert tmp == tmp2 + + p = dict() + q = dict() + x = lruwrap(q, 128, True) + + test(p, x, p, x, verify) + + x.sync() + assert p == q + +def wraptest3(): + + def verify(p, x): + for key, value in x.store.items(): + if key not in x.dirty: + assert p[key] == value + + for key in x.dirty: + assert x.cache.peek(key) == p[key] + + for key, value in x.cache.items(): + if key not in x.dirty: + assert x.store[key] == p[key] == value + + p = dict() + q = dict() + with lruwrap(q, 128, True) as x: + test(p, x, p, x, verify) + + assert p == q + + +@lrudecorator(100) +def square(x): + return x*x + +def testDecorator(): + for i in range(1000): + x = random.randint(0, 200) + assert square(x) == x*x + + +if __name__ == '__main__': + + random.seed() + + + for i in range(20): + testcache() + wraptest() + wraptest2() + wraptest3() + testDecorator() + + |