django-memoize-2.1.0/0000755000076500000240000000000013046416011014123 5ustar ccstaff00000000000000django-memoize-2.1.0/CHANGES0000644000076500000240000000170513046415215015126 0ustar ccstaff00000000000000Changelog Version 2.1.0 ````````````` - memoize now caches also `None` values - Py3 fixes Version 2.0.0 ````````````` - Deprecates Django<1.7 - Improves unicode stability Version 1.3.0 ````````````` - Fixes a bug #8 (*args are ignored by memoize) Version 1.2.0 ````````````` - Fixed a serious issue where memoize function ignored special `f(arg, **kwargs)` input use-case. See test `test_10ab_arg_kwarg_memoize` for more details. - Added new Django==1.8 Travis env test Version 1.1.2 ````````````` - Memoizer now accepts cache_prefix and cache parameter - Support for Django >= 1.4 Version 1.1.1 ````````````` - Default timeout set to Django's cache timeout Version 1.1.0 ````````````` - Port to Python >= 3.3 (requiring Python 2.6/2.7 for 2.x). - Fixed bug with using per-memoize timeouts greater than the default timeout - Added better support for per-instance memoization. - Various bug fixes Version 1.0.0 ````````````` - Initial public release django-memoize-2.1.0/LICENSE0000644000076500000240000000272712563111067015146 0ustar ccstaff00000000000000Copyright (c) 2010 by Thadeus Burgess. Copyright (c) 2014 by Thomas Vavrys. Some rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. * The names of the contributors may not be used to endorse or promote products derived from this software without specific prior written permission. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. django-memoize-2.1.0/MANIFEST.in0000644000076500000240000000023212563111067015664 0ustar ccstaff00000000000000include LICENSE CHANGES *.py recursive-include docs * recursive-exclude docs *.pyc recursive-exclude docs *.pyo prune docs/_build prune docs/_themes/.git django-memoize-2.1.0/PKG-INFO0000644000076500000240000000256313046416011015226 0ustar ccstaff00000000000000Metadata-Version: 1.1 Name: django-memoize Version: 2.1.0 Summary: An implementation of memoization technique for Django. Home-page: https://github.com/tvavrys/django-memoize Author: Thomas Vavrys Author-email: tvavrys@sleio.com License: BSD License Description: django-memoize -------------- **django-memoize** is an implementation of `memoization `_ technique for Django. You can think of it as a cache for function or method results. Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Environment :: Web Environment Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: BSD License Classifier: Operating System :: OS Independent Classifier: Programming Language :: Python Classifier: Programming Language :: Python :: 2 Classifier: Programming Language :: Python :: 2.7 Classifier: Programming Language :: Python :: 3 Classifier: Programming Language :: Python :: 3.3 Classifier: Programming Language :: Python :: 3.4 Classifier: Programming Language :: Python :: 3.5 Classifier: Framework :: Django Classifier: Framework :: Django :: 1.7 Classifier: Framework :: Django :: 1.8 Classifier: Framework :: Django :: 1.9 Classifier: Framework :: Django :: 1.10 Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content django-memoize-2.1.0/README.rst0000644000076500000240000000142112743231717015623 0ustar ccstaff00000000000000django-memoize ============== .. image:: https://travis-ci.org/tvavrys/django-memoize.svg?branch=master :target: https://travis-ci.org/tvavrys/django-memoize .. image:: https://badge.fury.io/py/django-memoize.svg :target: http://badge.fury.io/py/django-memoize .. image:: https://coveralls.io/repos/github/tvavrys/django-memoize/badge.svg?branch=master :target: https://coveralls.io/github/tvavrys/django-memoize?branch=master | **django-memoize** is an implementation of `memoization `_ technique for Django. You can think of it as a cache for function or method results. Documentation ------------- Documentation is available at http://pythonhosted.org/django-memoize/. Requirements ------------ Django >= 1.7 is required. django-memoize-2.1.0/docs/0000755000076500000240000000000013046416011015053 5ustar ccstaff00000000000000django-memoize-2.1.0/docs/Makefile0000644000076500000240000001102612563111067016521 0ustar ccstaff00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = sphinx-build PAPER = BUILDDIR = _build # Internal variables. PAPEROPT_a4 = -D latex_paper_size=a4 PAPEROPT_letter = -D latex_paper_size=letter ALLSPHINXOPTS = -d $(BUILDDIR)/doctrees $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest help: @echo "Please use \`make ' where is one of" @echo " html to make standalone HTML files" @echo " dirhtml to make HTML files named index.html in directories" @echo " singlehtml to make a single large HTML file" @echo " pickle to make pickle files" @echo " json to make JSON files" @echo " htmlhelp to make HTML files and a HTML help project" @echo " qthelp to make HTML files and a qthelp project" @echo " devhelp to make HTML files and a Devhelp project" @echo " epub to make an epub" @echo " latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter" @echo " latexpdf to make LaTeX files and run them through pdflatex" @echo " text to make text files" @echo " man to make manual pages" @echo " changes to make an overview of all changed/added/deprecated items" @echo " linkcheck to check all external links for integrity" @echo " doctest to run all doctests embedded in the documentation (if enabled)" clean: -rm -rf $(BUILDDIR)/* html: $(SPHINXBUILD) -b html $(ALLSPHINXOPTS) $(BUILDDIR)/html @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/html." dirhtml: $(SPHINXBUILD) -b dirhtml $(ALLSPHINXOPTS) $(BUILDDIR)/dirhtml @echo @echo "Build finished. The HTML pages are in $(BUILDDIR)/dirhtml." singlehtml: $(SPHINXBUILD) -b singlehtml $(ALLSPHINXOPTS) $(BUILDDIR)/singlehtml @echo @echo "Build finished. The HTML page is in $(BUILDDIR)/singlehtml." pickle: $(SPHINXBUILD) -b pickle $(ALLSPHINXOPTS) $(BUILDDIR)/pickle @echo @echo "Build finished; now you can process the pickle files." json: $(SPHINXBUILD) -b json $(ALLSPHINXOPTS) $(BUILDDIR)/json @echo @echo "Build finished; now you can process the JSON files." htmlhelp: $(SPHINXBUILD) -b htmlhelp $(ALLSPHINXOPTS) $(BUILDDIR)/htmlhelp @echo @echo "Build finished; now you can run HTML Help Workshop with the" \ ".hhp project file in $(BUILDDIR)/htmlhelp." qthelp: $(SPHINXBUILD) -b qthelp $(ALLSPHINXOPTS) $(BUILDDIR)/qthelp @echo @echo "Build finished; now you can run "qcollectiongenerator" with the" \ ".qhcp project file in $(BUILDDIR)/qthelp, like this:" @echo "# qcollectiongenerator $(BUILDDIR)/qthelp/Flask-SQLAlchemy.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/Flask-SQLAlchemy.qhc" devhelp: $(SPHINXBUILD) -b devhelp $(ALLSPHINXOPTS) $(BUILDDIR)/devhelp @echo @echo "Build finished." @echo "To view the help file:" @echo "# mkdir -p $$HOME/.local/share/devhelp/Flask-SQLAlchemy" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/Flask-SQLAlchemy" @echo "# devhelp" epub: $(SPHINXBUILD) -b epub $(ALLSPHINXOPTS) $(BUILDDIR)/epub @echo @echo "Build finished. The epub file is in $(BUILDDIR)/epub." latex: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo @echo "Build finished; the LaTeX files are in $(BUILDDIR)/latex." @echo "Run \`make' in that directory to run these through (pdf)latex" \ "(use \`make latexpdf' here to do that automatically)." latexpdf: $(SPHINXBUILD) -b latex $(ALLSPHINXOPTS) $(BUILDDIR)/latex @echo "Running LaTeX files through pdflatex..." make -C $(BUILDDIR)/latex all-pdf @echo "pdflatex finished; the PDF files are in $(BUILDDIR)/latex." text: $(SPHINXBUILD) -b text $(ALLSPHINXOPTS) $(BUILDDIR)/text @echo @echo "Build finished. The text files are in $(BUILDDIR)/text." man: $(SPHINXBUILD) -b man $(ALLSPHINXOPTS) $(BUILDDIR)/man @echo @echo "Build finished. The manual pages are in $(BUILDDIR)/man." changes: $(SPHINXBUILD) -b changes $(ALLSPHINXOPTS) $(BUILDDIR)/changes @echo @echo "The overview file is in $(BUILDDIR)/changes." linkcheck: $(SPHINXBUILD) -b linkcheck $(ALLSPHINXOPTS) $(BUILDDIR)/linkcheck @echo @echo "Link check complete; look for any errors in the above output " \ "or in $(BUILDDIR)/linkcheck/output.txt." doctest: $(SPHINXBUILD) -b doctest $(ALLSPHINXOPTS) $(BUILDDIR)/doctest @echo "Testing of doctests in the sources finished, look at the " \ "results in $(BUILDDIR)/doctest/output.txt." django-memoize-2.1.0/docs/_static/0000755000076500000240000000000013046416011016501 5ustar ccstaff00000000000000django-memoize-2.1.0/docs/_static/flask-cache.png0000644000076500000240000000730212563111067021360 0ustar ccstaff00000000000000PNG  IHDR8Y7tEXtSoftwareAdobe ImageReadyqe<!iTXtXML:com.adobe.xmp 5 7IDATx]q:U4%8%(@J(JxVzCWsf4;jhWv)xyyYV-9~IyoC>pW)Z>,}t1'@p @pxMI0T>Z @p'I:sRDY T"ڦԱRi'6klUIW2e$˸lrKϪlTBl3ϔ~=xdoe}ؖ}9 $olI}#7. E_ޣF1I⻧癞1kASۊoD浫.mCw?جE ~K53R}ަOG2,R'XBsW~WXjXzHfIc$".>dh@9 Nd$Tp/\N ~e GE>Dz/ d~h]c(h;~O4%&P DEq~\~_MXp"4%8rWJ0lv0)CZB )lgԃSH~+(0Ig9$\T x[A nCu>Nz\~_,1#Bg ^V2CĔWe1aLYv6Ȩա3=C&jO&IeiFeL9 Ęh+u.8LSC<7 2 Eȕ\kǘ9sd:p3(guadtGSyĕS!tp޶M1gv˃gmeSswV1ẽEjt2(g|Pۉ4J^8yf;@9##;ҹ8)͚36 :}_*\,Ro' t>f~|^5L\{_``rKt28-L;}P"5 V3/z^s|3%3lSH񳽔1LgmWW֌$w&\2(,dëڍ0{ kͶK_ۮWUY|dvb&7fƵ}bF8piLߜ1<%~y@$ZU#H)vp 11&\i뵶kcz)[#bedppӊpU-v/״ N,^g}5ߺ*9^OE\ s0 ^54;}$8]u '~xC`.;`O/c%Mij?8)eLo|:W\<\Lh3e*Sɠe%;,G>38W2Ƃ2ly[JuѦU=s8/~ZlF׈~{P 30=L}*eyÕPQ1u~)< LdnBҠ~E)]ؐ)Cɶ*UŦ~lc8'\U;IQ5";*eVy>`zioJ[\,<{[p}/-kF׈6iI+ rdKہsz{^jڸ:|J.[hw>_I te2? _w{Mwp.\ L>'+vuRWpa7eewM{xp8FΊWpg3}3c0DsՔ=gX=lN^_ h;Se.krey0eKd_ 4R27b.p_ׅfm]V'r7YwWWN+?v(Zuj䪩3\%tm+Z{q_7Zwcppp.7`'Il48îK!8iJϕwQ(Pհm~)߮ 2<1hP ;SOrh~>?urtחxIѴ^$L#u2uM =][.רiERrOq \.CߛWSPe{WvIˈ2d?S.L9=t.GרEO\3yjzu7e KKgfo탁Tf2:IѶyqVXHTn[TGrY1iZAMJn%fVtKb)}QQEfR=L[x}X1el(rWS=ˁ N:;uiK+jA@ mK̦nj9]4iui \pd96UC.pJ0 nB m=YVN2_]T:1X( vo0ٯra~\omƩD^rJ#V'dգ޺ qN PRm  ^,* W:<>EWv4jȮs$:W#00dS ^JBWz 8zU &,1\S#uYZUֵ):Bm; pۧ9IENDB`django-memoize-2.1.0/docs/conf.py0000644000076500000240000001707412700757414016376 0ustar ccstaff00000000000000# -*- coding: utf-8 -*- # # Flask-Cache documentation build configuration file, created by # sphinx-quickstart on Mon Aug 30 02:31:57 2010. # # This file is execfile()d with the current directory set to its containing dir. # # Note that not all possible configuration values are present in this # autogenerated file. # # All configuration values have a default; values that are commented out # serve to show the default. import sys, os # Set default settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "tests.test_settings") # If extensions (or modules to document with autodoc) are in another directory, # add these directories to sys.path here. If the directory is relative to the # documentation root, use os.path.abspath to make it absolute, like shown here. sys.path.insert(0, os.path.abspath(os.path.join(os.path.dirname(__file__), '..'))) sys.path.append(os.path.abspath('_themes')) from memoize import __version__, __versionfull__ # -- General configuration ----------------------------------------------------- # If your documentation needs a minimal Sphinx version, state it here. #needs_sphinx = '1.0' # Add any Sphinx extension module names here, as strings. They can be extensions # coming with Sphinx (named 'sphinx.ext.*') or your custom ones. extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx'] # Add any paths that contain templates here, relative to this directory. templates_path = ['_templates'] # The suffix of source filenames. source_suffix = '.rst' # The encoding of source files. #source_encoding = 'utf-8-sig' # The master toctree document. master_doc = 'index' # General information about the project. project = u'django-memoize' copyright = u'2014, Tom Vavrys' # The version info for the project you're documenting, acts as replacement for # |version| and |release|, also used in various other places throughout the # built documents. # # The short X.Y version. version = __version__ # The full version, including alpha/beta/rc tags. release = __versionfull__ # The language for content autogenerated by Sphinx. Refer to documentation # for a list of supported languages. #language = None # There are two options for replacing |today|: either, you set today to some # non-false value, then it is used: #today = '' # Else, today_fmt is used as the format for a strftime call. #today_fmt = '%B %d, %Y' # List of patterns, relative to source directory, that match files and # directories to ignore when looking for source files. exclude_patterns = ['_build'] # The reST default role (used for this markup: `text`) to use for all documents. #default_role = None # If true, '()' will be appended to :func: etc. cross-reference text. #add_function_parentheses = True # If true, the current module name will be prepended to all description # unit titles (such as .. function::). #add_module_names = True # If true, sectionauthor and moduleauthor directives will be shown in the # output. They are ignored by default. #show_authors = False # The name of the Pygments (syntax highlighting) style to use. #pygments_style = 'sphinx' # A list of ignored prefixes for module index sorting. #modindex_common_prefix = [] # -- Options for HTML output --------------------------------------------------- # The theme to use for HTML and HTML Help pages. See the documentation for # a list of builtin themes. html_theme = 'flask_small' # Theme options are theme-specific and customize the look and feel of a theme # further. For a list of options available for each theme, see the # documentation. html_theme_options = { 'index_logo': 'flask-cache.png', 'github_fork': 'tvavrys/django-memoize' } # Add any paths that contain custom themes here, relative to this directory. html_theme_path = ['_themes'] # The name for this set of Sphinx documents. If None, it defaults to # " v documentation". #html_title = None # A shorter title for the navigation bar. Default is the same as html_title. #html_short_title = None # The name of an image file (relative to this directory) to place at the top # of the sidebar. #html_logo = None # The name of an image file (within the static path) to use as favicon of the # docs. This file should be a Windows icon file (.ico) being 16x16 or 32x32 # pixels large. #html_favicon = None # Add any paths that contain custom static files (such as style sheets) here, # relative to this directory. They are copied after the builtin static files, # so a file named "default.css" will overwrite the builtin "default.css". html_static_path = ['_static'] # If not '', a 'Last updated on:' timestamp is inserted at every page bottom, # using the given strftime format. #html_last_updated_fmt = '%b %d, %Y' # If true, SmartyPants will be used to convert quotes and dashes to # typographically correct entities. #html_use_smartypants = True # Custom sidebar templates, maps document names to template names. #html_sidebars = {} # Additional templates that should be rendered to pages, maps page names to # template names. #html_additional_pages = {} # If false, no module index is generated. #html_domain_indices = True # If false, no index is generated. #html_use_index = True # If true, the index is split into individual pages for each letter. #html_split_index = False # If true, links to the reST sources are added to the pages. #html_show_sourcelink = True # If true, "Created using Sphinx" is shown in the HTML footer. Default is True. #html_show_sphinx = True # If true, "(C) Copyright ..." is shown in the HTML footer. Default is True. #html_show_copyright = True # If true, an OpenSearch description file will be output, and all pages will # contain a tag referring to it. The value of this option must be the # base URL from which the finished HTML is served. #html_use_opensearch = '' # If nonempty, this is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = '' # Output file base name for HTML help builder. htmlhelp_basename = 'django-memoizedoc' # -- Options for LaTeX output -------------------------------------------------- # The paper size ('letter' or 'a4'). #latex_paper_size = 'letter' # The font size ('10pt', '11pt' or '12pt'). #latex_font_size = '10pt' # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'django-memoize.tex', u'django-memoize Documentation', u'Tom Vavrys', 'manual'), ] # The name of an image file (relative to this directory) to place at the top of # the title page. #latex_logo = None # For "manual" documents, if this is true, then toplevel headings are parts, # not chapters. #latex_use_parts = False # If true, show page references after internal links. #latex_show_pagerefs = False # If true, show URL addresses after external links. #latex_show_urls = False # Additional stuff for the LaTeX preamble. #latex_preamble = '' # Documents to append as an appendix to all manuals. #latex_appendices = [] # If false, no module index is generated. #latex_domain_indices = True # -- Options for manual page output -------------------------------------------- # One entry per manual page. List of tuples # (source start file, name, description, authors, manual section). man_pages = [ ('index', 'django-memoize', u'django-memoize Documentation', [u'Tom Vavrys'], 1) ] # Example configuration for intersphinx: refer to the Python standard library. # intersphinx_mapping = {'http://docs.python.org/': None, # 'http://flask.pocoo.org/docs/': None, # 'http://werkzeug.pocoo.org/documentation/dev/': None,} autodoc_member_order = 'bysource' django-memoize-2.1.0/docs/index.rst0000644000076500000240000000675412563111067016736 0ustar ccstaff00000000000000django-memoize ================ .. module:: memoize About ----- **django-memoize** is an implementation of `memoization `_ technique for Django. You can think of it as a cache for function or method results. Installation ------------ Install the extension with one of the following commands:: $ easy_install django-memoize or alternatively if you have pip installed:: $ pip install django-memoize Set Up ------ Add 'memoize' to your INSTALLED_APPS in settings.py:: INSTALLED_APPS = [ '...', 'memoize', ] Memoization is managed through a ``Memoizer`` instance:: from memoize import Memoizer memoizer = Memoizer() Hovewer, we recommend to use already defined instance of ``Memoizer`` and use its methods:: from memoize import memoize, delete_memoized, delete_memoized_verhash @memoize(timeout=60) def count_objects(): pass delete_memoized(count_objects) Memoization ----------- See :meth:`~Memoizer.memoize` In memoization, the functions arguments are also included into the cache_key. Memoize is also designed for methods, since it will take into account the `repr `_ of the 'self' or 'cls' argument as part of the cache key. The theory behind memoization is that if you have a function you need to call several times in one request, it would only be calculated the first time that function is called with those arguments. For example, a model object that determines if a user has a role. You might need to call this function many times during a single request. To keep from hitting the database every time this information is needed you might do something like the following:: class Person(models.Model): @memoize(timeout=50) def has_membership(self, role_id): return Group.objects.filter(user=self, role_id=role_id).count() >= 1 .. warning:: Using mutable objects (classes, etc) as part of the cache key can become tricky. It is suggested to not pass in an object instance into a memoized function. However, the memoize does perform a repr() on the passed in arguments so that if the object has a __repr__ function that returns a uniquely identifying string for that object, that will be used as part of the cache key. For example, a model person object that returns the database id as part of the unique identifier.:: class Person(models.Model): def __repr__(self): return "%s(%s)" % (self.__class__.__name__, self.id) Deleting memoize cache `````````````````````` You might need to delete the cache on a per-function bases. Using the above example, lets say you change the users permissions and assign them to a role, but now you need to re-calculate if they have certain memberships or not. You can do this with the :meth:`~Memoizer.delete_memoized` function.:: delete_memoized('user_has_membership') .. note:: If only the function name is given as parameter, all the memoized versions of it will be invalidated. However, you can delete specific cache by providing the same parameter values as when caching. In following example only the ``user``-role cache is deleted: .. code-block:: python user_has_membership('demo', 'admin') user_has_membership('demo', 'user') delete_memoized('user_has_membership', 'demo', 'user') API --- .. autoclass:: Memoizer :members: memoize, delete_memoized, delete_memoized_verhash .. include:: ../CHANGES django-memoize-2.1.0/docs/make.bat0000644000076500000240000001003612563111067016466 0ustar ccstaff00000000000000@ECHO OFF REM Command file for Sphinx documentation if "%SPHINXBUILD%" == "" ( set SPHINXBUILD=sphinx-build ) set BUILDDIR=_build set ALLSPHINXOPTS=-d %BUILDDIR%/doctrees %SPHINXOPTS% . if NOT "%PAPER%" == "" ( set ALLSPHINXOPTS=-D latex_paper_size=%PAPER% %ALLSPHINXOPTS% ) if "%1" == "" goto help if "%1" == "help" ( :help echo.Please use `make ^` where ^ is one of echo. html to make standalone HTML files echo. dirhtml to make HTML files named index.html in directories echo. singlehtml to make a single large HTML file echo. pickle to make pickle files echo. json to make JSON files echo. htmlhelp to make HTML files and a HTML help project echo. qthelp to make HTML files and a qthelp project echo. devhelp to make HTML files and a Devhelp project echo. epub to make an epub echo. latex to make LaTeX files, you can set PAPER=a4 or PAPER=letter echo. text to make text files echo. man to make manual pages echo. changes to make an overview over all changed/added/deprecated items echo. linkcheck to check all external links for integrity echo. doctest to run all doctests embedded in the documentation if enabled goto end ) if "%1" == "clean" ( for /d %%i in (%BUILDDIR%\*) do rmdir /q /s %%i del /q /s %BUILDDIR%\* goto end ) if "%1" == "html" ( %SPHINXBUILD% -b html %ALLSPHINXOPTS% %BUILDDIR%/html echo. echo.Build finished. The HTML pages are in %BUILDDIR%/html. goto end ) if "%1" == "dirhtml" ( %SPHINXBUILD% -b dirhtml %ALLSPHINXOPTS% %BUILDDIR%/dirhtml echo. echo.Build finished. The HTML pages are in %BUILDDIR%/dirhtml. goto end ) if "%1" == "singlehtml" ( %SPHINXBUILD% -b singlehtml %ALLSPHINXOPTS% %BUILDDIR%/singlehtml echo. echo.Build finished. The HTML pages are in %BUILDDIR%/singlehtml. goto end ) if "%1" == "pickle" ( %SPHINXBUILD% -b pickle %ALLSPHINXOPTS% %BUILDDIR%/pickle echo. echo.Build finished; now you can process the pickle files. goto end ) if "%1" == "json" ( %SPHINXBUILD% -b json %ALLSPHINXOPTS% %BUILDDIR%/json echo. echo.Build finished; now you can process the JSON files. goto end ) if "%1" == "htmlhelp" ( %SPHINXBUILD% -b htmlhelp %ALLSPHINXOPTS% %BUILDDIR%/htmlhelp echo. echo.Build finished; now you can run HTML Help Workshop with the ^ .hhp project file in %BUILDDIR%/htmlhelp. goto end ) if "%1" == "qthelp" ( %SPHINXBUILD% -b qthelp %ALLSPHINXOPTS% %BUILDDIR%/qthelp echo. echo.Build finished; now you can run "qcollectiongenerator" with the ^ .qhcp project file in %BUILDDIR%/qthelp, like this: echo.^> qcollectiongenerator %BUILDDIR%\qthelp\Flask-SQLAlchemy.qhcp echo.To view the help file: echo.^> assistant -collectionFile %BUILDDIR%\qthelp\Flask-SQLAlchemy.ghc goto end ) if "%1" == "devhelp" ( %SPHINXBUILD% -b devhelp %ALLSPHINXOPTS% %BUILDDIR%/devhelp echo. echo.Build finished. goto end ) if "%1" == "epub" ( %SPHINXBUILD% -b epub %ALLSPHINXOPTS% %BUILDDIR%/epub echo. echo.Build finished. The epub file is in %BUILDDIR%/epub. goto end ) if "%1" == "latex" ( %SPHINXBUILD% -b latex %ALLSPHINXOPTS% %BUILDDIR%/latex echo. echo.Build finished; the LaTeX files are in %BUILDDIR%/latex. goto end ) if "%1" == "text" ( %SPHINXBUILD% -b text %ALLSPHINXOPTS% %BUILDDIR%/text echo. echo.Build finished. The text files are in %BUILDDIR%/text. goto end ) if "%1" == "man" ( %SPHINXBUILD% -b man %ALLSPHINXOPTS% %BUILDDIR%/man echo. echo.Build finished. The manual pages are in %BUILDDIR%/man. goto end ) if "%1" == "changes" ( %SPHINXBUILD% -b changes %ALLSPHINXOPTS% %BUILDDIR%/changes echo. echo.The overview file is in %BUILDDIR%/changes. goto end ) if "%1" == "linkcheck" ( %SPHINXBUILD% -b linkcheck %ALLSPHINXOPTS% %BUILDDIR%/linkcheck echo. echo.Link check complete; look for any errors in the above output ^ or in %BUILDDIR%/linkcheck/output.txt. goto end ) if "%1" == "doctest" ( %SPHINXBUILD% -b doctest %ALLSPHINXOPTS% %BUILDDIR%/doctest echo. echo.Testing of doctests in the sources finished, look at the ^ results in %BUILDDIR%/doctest/output.txt. goto end ) :end django-memoize-2.1.0/memoize/0000755000076500000240000000000013046416011015570 5ustar ccstaff00000000000000django-memoize-2.1.0/memoize/__init__.py0000644000076500000240000004271713046414773017731 0ustar ccstaff00000000000000# -*- coding: utf-8 -*- __version__ = '2.1.0' __versionfull__ = __version__ import functools import hashlib import inspect import logging import uuid from django.conf import settings from django.core.cache import cache as default_cache from django.core.cache.backends.base import DEFAULT_TIMEOUT from django.utils.encoding import force_bytes logger = logging.getLogger(__name__) class DefaultCacheObject(object): pass DEFAULT_CACHE_OBJECT = DefaultCacheObject() def _get_argspec(f): try: argspec = inspect.getargspec(f) except ValueError: # this can happen in python 3.5 when # function has keyword-only arguments or annotations argspec = inspect.getfullargspec(f) return argspec def function_namespace(f, args=None): """ Attempts to returns unique namespace for function """ m_args = _get_argspec(f).args instance_token = None instance_self = getattr(f, '__self__', None) if instance_self and not inspect.isclass(instance_self): instance_token = repr(f.__self__) elif m_args and m_args[0] == 'self' and args: instance_token = repr(args[0]) module = f.__module__ or __name__ if hasattr(f, '__qualname__'): name = f.__qualname__ else: klass = getattr(f, '__self__', None) if klass and not inspect.isclass(klass): klass = klass.__class__ if not klass: klass = getattr(f, 'im_class', None) if not klass: if m_args and args: if m_args[0] == 'self': klass = args[0].__class__ elif m_args[0] == 'cls': klass = args[0] if klass: name = klass.__name__ + '.' + f.__name__ else: name = f.__name__ ns = '.'.join((module, name)) if instance_token: ins = '.'.join((module, name, instance_token)) else: ins = None return ns, ins class Memoizer(object): """ This class is used to control the memoizer objects. """ def __init__(self, cache=default_cache, cache_prefix='memoize', default_cache_value=DEFAULT_CACHE_OBJECT): self.cache = cache self.cache_prefix = cache_prefix self.default_cache_value = default_cache_value def get(self, key): "Proxy function for internal cache object." return self.cache.get(key=key, default=self.default_cache_value) def set(self, key, value, timeout=DEFAULT_TIMEOUT): "Proxy function for internal cache object." self.cache.set(key=key, value=value, timeout=timeout) def add(self, key, value, timeout=DEFAULT_TIMEOUT): "Proxy function for internal cache object." self.cache.add(key=key, value=value, timeout=timeout) def delete(self, key): "Proxy function for internal cache object." self.cache.delete(key=key) def delete_many(self, *keys): "Proxy function for internal cache object." self.cache.delete_many(keys=keys) def clear(self): "Proxy function for internal cache object." self.cache.clear() def get_many(self, *keys): "Proxy function for internal cache object." d = self.cache.get_many(keys=keys) values = [] for key in keys: values.append( d.get(key) ) return values def set_many(self, mapping, timeout=DEFAULT_TIMEOUT): "Proxy function for internal cache object." self.cache.set_many(data=mapping, timeout=timeout) def _memvname(self, funcname): return funcname + '_memver' def _memoize_make_version_hash(self): return uuid.uuid4().hex def _memoize_version(self, f, args=None, reset=False, delete=False, timeout=DEFAULT_TIMEOUT): """ Updates the hash version associated with a memoized function or method. """ fname, instance_fname = function_namespace(f, args=args) version_key = self._memvname(fname) fetch_keys = [version_key] if instance_fname: instance_version_key = self._memvname(instance_fname) fetch_keys.append(instance_version_key) # Only delete the per-instance version key or per-function version # key but not both. if delete: self.delete(fetch_keys[-1]) return fname, None version_data_list = self.get_many(*fetch_keys) dirty = False if version_data_list[0] is None: version_data_list[0] = self._memoize_make_version_hash() dirty = True if instance_fname and version_data_list[1] is None: version_data_list[1] = self._memoize_make_version_hash() dirty = True # Only reset the per-instance version or the per-function version # but not both. if reset: fetch_keys = fetch_keys[-1:] version_data_list = [self._memoize_make_version_hash()] dirty = True if dirty: self.set_many( dict(zip(fetch_keys, version_data_list)), timeout=timeout ) return fname, ''.join(version_data_list) def _memoize_make_cache_key(self, make_name=None, timeout=DEFAULT_TIMEOUT): """ Function used to create the cache_key for memoized functions. """ def make_cache_key(f, *args, **kwargs): _timeout = getattr(timeout, 'cache_timeout', timeout) fname, version_data = self._memoize_version(f, args=args, timeout=_timeout) #: this should have to be after version_data, so that it #: does not break the delete_memoized functionality. if callable(make_name): altfname = make_name(fname) else: altfname = fname if callable(f): keyargs, keykwargs = self._memoize_kwargs_to_args( f, *args, **kwargs ) else: keyargs, keykwargs = args, kwargs cache_key = hashlib.md5( force_bytes((altfname, keyargs, keykwargs)) ).hexdigest() cache_key += version_data if self.cache_prefix: cache_key = '%s:%s' % (self.cache_prefix, cache_key) return cache_key return make_cache_key def _memoize_kwargs_to_args(self, f, *args, **kwargs): #: Inspect the arguments to the function #: This allows the memoization to be the same #: whether the function was called with #: 1, b=2 is equivilant to a=1, b=2, etc. new_args = [] arg_num = 0 argspec = _get_argspec(f) args_len = len(argspec.args) for i in range(args_len): if i == 0 and argspec.args[i] in ('self', 'cls'): #: use the repr of the class instance #: this supports instance methods for #: the memoized functions, giving more #: flexibility to developers arg = repr(args[0]) arg_num += 1 elif argspec.args[i] in kwargs: arg = kwargs.pop(argspec.args[i]) elif arg_num < len(args): arg = args[arg_num] arg_num += 1 elif abs(i - args_len) <= len(argspec.defaults): arg = argspec.defaults[i - args_len] arg_num += 1 else: arg = None arg_num += 1 #: Attempt to convert all arguments to a #: hash/id or a representation? #: Not sure if this is necessary, since #: using objects as keys gets tricky quickly. # if hasattr(arg, '__class__'): # try: # arg = hash(arg) # except: # arg = repr(arg) #: Or what about a special __cacherepr__ function #: on an object, this allows objects to act normal #: upon inspection, yet they can define a representation #: that can be used to make the object unique in the #: cache key. Given that a case comes across that #: an object "must" be used as a cache key # if hasattr(arg, '__cacherepr__'): # arg = arg.__cacherepr__ new_args.append(arg) # If there are any missing varargs then # just append them since consistency of the key trumps order. if argspec.varargs and args_len < len(args): new_args.extend(args[args_len:]) return tuple(new_args), kwargs def memoize(self, timeout=DEFAULT_TIMEOUT, make_name=None, unless=None): """ Use this to cache the result of a function, taking its arguments into account in the cache key. Information on `Memoization `_. Example:: @memoize(timeout=50) def big_foo(a, b): return a + b + random.randrange(0, 1000) .. code-block:: pycon >>> big_foo(5, 2) 753 >>> big_foo(5, 3) 234 >>> big_foo(5, 2) 753 .. note:: The returned decorated function now has three function attributes assigned to it. **uncached** The original undecorated function. readable only **cache_timeout** The cache timeout value for this function. For a custom value to take affect, this must be set before the function is called. readable and writable **make_cache_key** A function used in generating the cache_key used. readable and writable :param timeout: Default: 300. If set to an integer, will cache for that amount of time. Unit of time is in seconds. :param make_name: Default None. If set this is a function that accepts a single argument, the function name, and returns a new string to be used as the function name. If not set then the function name is used. :param unless: Default None. Cache will *always* execute the caching facilities unelss this callable is true. This will bypass the caching entirely. """ def memoize(f): @functools.wraps(f) def decorated_function(*args, **kwargs): #: bypass cache if callable(unless) and unless() is True: return f(*args, **kwargs) try: cache_key = decorated_function.make_cache_key( f, *args, **kwargs ) rv = self.get(cache_key) except Exception: if settings.DEBUG: raise logger.exception( "Exception possibly due to cache backend." ) return f(*args, **kwargs) if rv == self.default_cache_value: rv = f(*args, **kwargs) try: self.set( cache_key, rv, timeout=decorated_function.cache_timeout ) except Exception: if settings.DEBUG: raise logger.exception( "Exception possibly due to cache backend." ) return rv decorated_function.uncached = f decorated_function.cache_timeout = timeout decorated_function.make_cache_key = self._memoize_make_cache_key( make_name, decorated_function ) decorated_function.delete_memoized = ( lambda: self.delete_memoized(f) ) return decorated_function return memoize def delete_memoized(self, f, *args, **kwargs): """ Deletes the specified functions caches, based by given parameters. If parameters are given, only the functions that were memoized with them will be erased. Otherwise all versions of the caches will be forgotten. Example:: @memoize(50) def random_func(): return random.randrange(1, 50) @memoize() def param_func(a, b): return a+b+random.randrange(1, 50) .. code-block:: pycon >>> random_func() 43 >>> random_func() 43 >>> delete_memoized('random_func') >>> random_func() 16 >>> param_func(1, 2) 32 >>> param_func(1, 2) 32 >>> param_func(2, 2) 47 >>> delete_memoized('param_func', 1, 2) >>> param_func(1, 2) 13 >>> param_func(2, 2) 47 Delete memoized is also smart about instance methods vs class methods. When passing a instancemethod, it will only clear the cache related to that instance of that object. (object uniqueness can be overridden by defining the __repr__ method, such as user id). When passing a classmethod, it will clear all caches related across all instances of that class. Example:: class Adder(object): @memoize() def add(self, b): return b + random.random() .. code-block:: pycon >>> adder1 = Adder() >>> adder2 = Adder() >>> adder1.add(3) 3.23214234 >>> adder2.add(3) 3.60898509 >>> delete_memoized(adder.add) >>> adder1.add(3) 3.01348673 >>> adder2.add(3) 3.60898509 >>> delete_memoized(Adder.add) >>> adder1.add(3) 3.53235667 >>> adder2.add(3) 3.72341788 :param fname: Name of the memoized function, or a reference to the function. :param \*args: A list of positional parameters used with memoized function. :param \**kwargs: A dict of named parameters used with memoized function. .. note:: django-memoize uses inspect to order kwargs into positional args when the function is memoized. If you pass a function reference into ``fname`` instead of the function name, django-memoize will be able to place the args/kwargs in the proper order, and delete the positional cache. However, if ``delete_memoized`` is just called with the name of the function, be sure to pass in potential arguments in the same order as defined in your function as args only, otherwise django-memoize will not be able to compute the same cache key. .. note:: django-memoize maintains an internal random version hash for the function. Using delete_memoized will only swap out the version hash, causing the memoize function to recompute results and put them into another key. This leaves any computed caches for this memoized function within the caching backend. It is recommended to use a very high timeout with memoize if using this function, so that when the version has is swapped, the old cached results would eventually be reclaimed by the caching backend. """ if not callable(f): raise DeprecationWarning( "Deleting messages by relative name is no longer" " reliable, please switch to a function reference" ) try: if not args and not kwargs: self._memoize_version(f, reset=True) else: cache_key = f.make_cache_key(f.uncached, *args, **kwargs) self.delete(cache_key) except Exception: if settings.DEBUG: raise logger.exception("Exception possibly due to cache backend.") def delete_memoized_verhash(self, f, *args): """ Delete the version hash associated with the function. .. warning:: Performing this operation could leave keys behind that have been created with this version hash. It is up to the application to make sure that all keys that may have been created with this version hash at least have timeouts so they will not sit orphaned in the cache backend. """ if not callable(f): raise DeprecationWarning( "Deleting messages by relative name is no longer" " reliable, please use a function reference" ) try: self._memoize_version(f, delete=True) except Exception: if settings.DEBUG: raise logger.exception("Exception possibly due to cache backend.") # Memoizer instance _memoizer = Memoizer() # Public objects memoize = _memoizer.memoize delete_memoized = _memoizer.delete_memoized delete_memoized_verhash = _memoizer.delete_memoized_verhash django-memoize-2.1.0/runtests.py0000644000076500000240000000066112563121431016371 0ustar ccstaff00000000000000#!/usr/bin/env python import os import sys os.environ['DJANGO_SETTINGS_MODULE'] = 'tests.test_settings' import django from django.conf import settings from django.test.utils import get_runner if __name__ == "__main__": if hasattr(django, 'setup'): django.setup() TestRunner = get_runner(settings) test_runner = TestRunner() failures = test_runner.run_tests(["tests"]) sys.exit(bool(failures)) django-memoize-2.1.0/setup.cfg0000644000076500000240000000026313046416011015745 0ustar ccstaff00000000000000[build_sphinx] source-dir = docs/ build-dir = docs/_build all_files = 1 [upload_sphinx] upload-dir = docs/_build/html [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 django-memoize-2.1.0/setup.py0000644000076500000240000000277613046415250015655 0ustar ccstaff00000000000000#!/usr/bin/env python """ django-memoize -------------- **django-memoize** is an implementation of `memoization `_ technique for Django. You can think of it as a cache for function or method results. """ from setuptools import setup setup( name='django-memoize', version='2.1.0', packages=['memoize'], include_package_data=True, license='BSD License', description='An implementation of memoization technique for Django.', url='https://github.com/tvavrys/django-memoize', author='Thomas Vavrys', author_email='tvavrys@sleio.com', long_description=__doc__, install_requires=[ 'django >= 1.7' ], classifiers=[ 'Development Status :: 5 - Production/Stable', 'Environment :: Web Environment', 'Intended Audience :: Developers', 'License :: OSI Approved :: BSD License', 'Operating System :: OS Independent', 'Programming Language :: Python', 'Programming Language :: Python :: 2', 'Programming Language :: Python :: 2.7', 'Programming Language :: Python :: 3', 'Programming Language :: Python :: 3.3', 'Programming Language :: Python :: 3.4', 'Programming Language :: Python :: 3.5', 'Framework :: Django', 'Framework :: Django :: 1.7', 'Framework :: Django :: 1.8', 'Framework :: Django :: 1.9', 'Framework :: Django :: 1.10', 'Topic :: Internet :: WWW/HTTP :: Dynamic Content', ], ) django-memoize-2.1.0/tests/0000755000076500000240000000000013046416011015265 5ustar ccstaff00000000000000django-memoize-2.1.0/tests/__init__.py0000644000076500000240000000000012563113112017363 0ustar ccstaff00000000000000django-memoize-2.1.0/tests/test_settings.py0000644000076500000240000000022112563122253020536 0ustar ccstaff00000000000000DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3' } } SECRET_KEY = "123456789" INSTALLED_APPS = ( 'tests', ) django-memoize-2.1.0/tests/tests.py0000644000076500000240000003613213046414525017016 0ustar ccstaff00000000000000# -*- coding: utf-8 -*- # vi:si:et:sw=4:sts=4:ts=4 import random import time from django.test import SimpleTestCase from memoize import Memoizer, function_namespace class MemoizeTestCase(SimpleTestCase): def setUp(self): self.memoizer = Memoizer() def test_00_set(self): self.memoizer.set('hi', 'hello') assert self.memoizer.get('hi') == 'hello' def test_01_add(self): self.memoizer.add('hi', 'hello') assert self.memoizer.get('hi') == 'hello' self.memoizer.add('hi', 'foobar') assert self.memoizer.get('hi') == 'hello' def test_02_delete(self): self.memoizer.set('hi', 'hello') self.memoizer.delete('hi') assert self.memoizer.get('hi') is self.memoizer.default_cache_value def test_06_memoize(self): @self.memoizer.memoize(5) def big_foo(a, b): return a+b+random.randrange(0, 100000) result = big_foo(5, 2) time.sleep(1) assert big_foo(5, 2) == result result2 = big_foo(5, 3) assert result2 != result time.sleep(6) assert big_foo(5, 2) != result time.sleep(1) assert big_foo(5, 3) != result2 def test_06a_memoize(self): @self.memoizer.memoize(50) def big_foo(a, b): return a+b+random.randrange(0, 100000) result = big_foo(5, 2) time.sleep(2) assert big_foo(5, 2) == result def test_07_delete_memoize(self): @self.memoizer.memoize(5) def big_foo(a, b): return a+b+random.randrange(0, 100000) result = big_foo(5, 2) result2 = big_foo(5, 3) time.sleep(1) assert big_foo(5, 2) == result assert big_foo(5, 2) == result assert big_foo(5, 3) != result assert big_foo(5, 3) == result2 self.memoizer.delete_memoized(big_foo) assert big_foo(5, 2) != result assert big_foo(5, 3) != result2 def test_07b_delete_memoized_verhash(self): @self.memoizer.memoize(5) def big_foo(a, b): return a+b+random.randrange(0, 100000) result = big_foo(5, 2) result2 = big_foo(5, 3) time.sleep(1) assert big_foo(5, 2) == result assert big_foo(5, 2) == result assert big_foo(5, 3) != result assert big_foo(5, 3) == result2 self.memoizer.delete_memoized_verhash(big_foo) _fname, _fname_instance = function_namespace(big_foo) version_key = self.memoizer._memvname(_fname) assert ( self.memoizer.get(version_key) is self.memoizer.default_cache_value ) assert big_foo(5, 2) != result assert big_foo(5, 3) != result2 assert ( self.memoizer.get(version_key) is not self.memoizer.default_cache_value ) def test_08_delete_memoize(self): @self.memoizer.memoize() def big_foo(a, b): return a+b+random.randrange(0, 100000) result_a = big_foo(5, 1) result_b = big_foo(5, 2) assert big_foo(5, 1) == result_a assert big_foo(5, 2) == result_b self.memoizer.delete_memoized(big_foo, 5, 2) assert big_foo(5, 1) == result_a assert big_foo(5, 2) != result_b # Cleanup bigfoo 5,1 5,2 or it might conflict with # following run if it also uses memecache self.memoizer.delete_memoized(big_foo, 5, 2) self.memoizer.delete_memoized(big_foo, 5, 1) def test_09_args_memoize(self): @self.memoizer.memoize() def big_foo(a, b): return sum(a)+sum(b)+random.randrange(0, 100000) result_a = big_foo([5, 3, 2], [1]) result_b = big_foo([3, 3], [3, 1]) assert big_foo([5, 3, 2], [1]) == result_a assert big_foo([3, 3], [3, 1]) == result_b self.memoizer.delete_memoized(big_foo, [5, 3, 2], [1]) assert big_foo([5, 3, 2], [1]) != result_a assert big_foo([3, 3], [3, 1]) == result_b # Cleanup bigfoo 5,1 5,2 or it might conflict with # following run if it also uses memecache self.memoizer.delete_memoized(big_foo, [5, 3, 2], [1]) self.memoizer.delete_memoized(big_foo, [3, 3], [1]) def test_10_kwargs_memoize(self): @self.memoizer.memoize() def big_foo(a, b=None): return a+sum(b.values())+random.randrange(0, 100000) result_a = big_foo(1, dict(one=1, two=2)) result_b = big_foo(5, dict(three=3, four=4)) assert big_foo(1, dict(one=1, two=2)) == result_a assert big_foo(5, dict(three=3, four=4)) == result_b self.memoizer.delete_memoized(big_foo, 1, dict(one=1, two=2)) assert big_foo(1, dict(one=1, two=2)) != result_a assert big_foo(5, dict(three=3, four=4)) == result_b def test_10a_kwargonly_memoize(self): @self.memoizer.memoize() def big_foo(a=None): if a is None: a = 0 return a+random.random() result_a = big_foo() result_b = big_foo(5) assert big_foo() == result_a assert big_foo() < 1 assert big_foo(5) == result_b assert big_foo(5) >= 5 and big_foo(5) < 6 def test_10a_arg_kwarg_memoize(self): @self.memoizer.memoize() def f(a, b, c=1): return a+b+c+random.randrange(0, 100000) assert f(1, 2) == f(1, 2, c=1) assert f(1, 2) == f(1, 2, 1) assert f(1, 2) == f(1, 2) assert f(1, 2) != f(2, 1) assert f(1, 2, 3) != f(1, 2) with self.assertRaises(TypeError): f(1) def test_10ab_arg_kwarg_memoize(self): @self.memoizer.memoize() def f(a, **kwargs): return (a, kwargs, random.randrange(0, 100000000)) f1 = f(1, b=2) assert f1 == f(1, b=2) assert f1 != f(1, b=4) f2 = f(5, c=6) assert f2 == f(5, c=6) assert f2 != f(7, c=6) self.memoizer.delete_memoized(f, 1, b=2) assert f1 != f(1, b=2) assert f2 == f(5, c=6) assert f2 != f(7, c=6) def test_10ac_arg_kwarg_memoize(self): @self.memoizer.memoize() def f(a, *args, **kwargs): return (a, args, kwargs, random.randrange(0, 100000000)) f1 = f(1, 2, b=3) assert f1 == f(1, 2, b=3) assert f1 != f(1, 3, b=3) f2 = f(5, 6, c=7) assert f2 == f(5, 6, c=7) assert f2 != f(7, 6, c=7) self.memoizer.delete_memoized(f, 1, 2, b=3) assert f1 != f(1, 2, b=3) assert f2 == f(5, 6, c=7) assert f2 != f(7, 6, c=7) @self.memoizer.memoize() def f(a, b=1, *args, **kwargs): return (a, b, args, kwargs, random.randrange(0, 100000000)) f3 = f(1, 3, 4) assert f3 == f(1, 3, 4) assert f3 == f(*(1, 3, 4)) assert f3 != f(1, 3) self.memoizer.delete_memoized(f, 1, 3, 4) assert f3 != f(1, 3, 4) def test_10b_classarg_memoize(self): @self.memoizer.memoize() def bar(a, *args): return a.value + random.random() + sum(args) class Adder(object): def __init__(self, value, *args): self.value = (value + sum(args)) adder = Adder(15) adder2 = Adder(20) adder3 = Adder(16, 5) adder4 = Adder(21, 6) w = bar(adder) x = bar(adder2) y = bar(adder3) z = bar(adder4) assert w != x assert y != z assert bar(adder) == w assert bar(adder) != x assert bar(adder3) == y assert bar(adder3) != z adder.value = 14 adder3.value = 15 assert bar(adder) == w assert bar(adder) != x assert bar(adder3) == y assert bar(adder3) != z assert bar(adder) != bar(adder2) assert bar(adder3) != bar(adder4) assert bar(adder2) == x assert bar(adder4) == z def test_10c_classfunc_memoize(self): class Adder(object): def __init__(self, initial): self.initial = initial @self.memoizer.memoize() def add(self, b, *args): return self.initial + b + sum(args) adder1 = Adder(1) adder2 = Adder(2) x = adder1.add(3) y = adder1.add(3, 4) assert adder1.add(3) == x assert adder1.add(4) != x assert adder1.add(3, 4) == y assert adder1.add(4, 4) != y assert adder1.add(3) != adder2.add(3) def test_10d_classfunc_memoize_delete(self): class Adder(object): def __init__(self, initial): self.initial = initial @self.memoizer.memoize() def add(self, b, *args): return self.initial + b + sum(args) + random.random() adder1 = Adder(1) adder2 = Adder(2) a1 = adder1.add(3) a2 = adder2.add(3) b1 = adder1.add(3, 1) b2 = adder2.add(3, 1) assert a1 != a2 assert a1 != b1 assert a2 != b2 assert adder1.add(3) == a1 assert adder2.add(3) == a2 assert adder1.add(3, 1) == b1 assert adder2.add(3, 1) == b2 self.memoizer.delete_memoized(adder1.add) a3 = adder1.add(3) a4 = adder2.add(3) b3 = adder1.add(3, 1) b4 = adder2.add(3, 1) self.assertNotEqual(a1, a3) self.assertNotEqual(b1, b3) assert a1 != a3 assert b1 != b3 self.assertEqual(a2, a4) self.assertEqual(b2, b4) self.memoizer.delete_memoized(Adder.add) a5 = adder1.add(3) a6 = adder2.add(3) b5 = adder1.add(3, 1) b6 = adder2.add(3, 1) self.assertNotEqual(a5, a6) self.assertNotEqual(b5, b6) self.assertNotEqual(a3, a5) self.assertNotEqual(b3, b5) self.assertNotEqual(a4, a6) self.assertNotEqual(b4, b6) def test_10e_delete_memoize_classmethod(self): class Mock(object): @classmethod @self.memoizer.memoize(5) def big_foo(cls, a, b, *args): return a+b+sum(args)+random.randrange(0, 100000) result = Mock.big_foo(5, 2) result2 = Mock.big_foo(5, 3) result3 = Mock.big_foo(5, 2, 1) result4 = Mock.big_foo(5, 3, 1) time.sleep(1) assert Mock.big_foo(5, 2) == result assert Mock.big_foo(5, 2) == result assert Mock.big_foo(5, 3) != result assert Mock.big_foo(5, 3) == result2 assert Mock.big_foo(5, 2, 1) == result3 assert Mock.big_foo(5, 2, 1) == result3 assert Mock.big_foo(5, 3, 1) != result3 assert Mock.big_foo(5, 3, 1) == result4 self.memoizer.delete_memoized(Mock.big_foo) assert Mock.big_foo(5, 2) != result assert Mock.big_foo(5, 3) != result2 assert Mock.big_foo(5, 2, 1) != result3 assert Mock.big_foo(5, 3, 1) != result4 def test_14_memoized_multiple_arg_kwarg_calls(self): @self.memoizer.memoize() def big_foo(a, b, c=[1, 1], d=[1, 1]): return sum(a)+sum(b)+sum(c)+sum(d)+random.randrange(0, 100000) result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) assert big_foo([5, 3, 2], [1], d=[3, 3], c=[3, 3]) == result_a assert big_foo(b=[1], a=[5, 3, 2], c=[3, 3], d=[3, 3]) == result_a assert big_foo([5, 3, 2], [1], [3, 3], [3, 3]) == result_a def test_15_memoize_multiple_arg_kwarg_delete(self): @self.memoizer.memoize() def big_foo(a, b, c=[1, 1], d=[1, 1]): return sum(a)+sum(b)+sum(c)+sum(d)+random.randrange(0, 100000) result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) self.memoizer.delete_memoized(big_foo, [5, 3, 2], [1], [3, 3], [3, 3]) result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) assert result_a != result_b self.memoizer.delete_memoized( big_foo, [5, 3, 2], b=[1], c=[3, 3], d=[3, 3] ) result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) assert result_a != result_b self.memoizer.delete_memoized( big_foo, [5, 3, 2], [1], c=[3, 3], d=[3, 3] ) result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) assert result_a != result_b self.memoizer.delete_memoized( big_foo, [5, 3, 2], b=[1], c=[3, 3], d=[3, 3] ) result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) assert result_a != result_b self.memoizer.delete_memoized( big_foo, [5, 3, 2], [1], c=[3, 3], d=[3, 3] ) result_b = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) assert result_a != result_b self.memoizer.delete_memoized(big_foo, [5, 3, 2], [1], [3, 3], [3, 3]) result_a = big_foo([5, 3, 2], [1], c=[3, 3], d=[3, 3]) assert result_a != result_b def test_16_memoize_kwargs_to_args(self): def big_foo(a, b, c=None, d=None): return sum(a)+sum(b)+random.randrange(0, 100000) expected = (1, 2, 'foo', 'bar') args, kwargs = self.memoizer._memoize_kwargs_to_args( big_foo, 1, 2, 'foo', 'bar') assert (args == expected) args, kwargs = self.memoizer._memoize_kwargs_to_args( big_foo, 2, 'foo', 'bar', a=1) assert (args == expected) args, kwargs = self.memoizer._memoize_kwargs_to_args( big_foo, a=1, b=2, c='foo', d='bar') assert (args == expected) args, kwargs = self.memoizer._memoize_kwargs_to_args( big_foo, d='bar', b=2, a=1, c='foo') assert (args == expected) args, kwargs = self.memoizer._memoize_kwargs_to_args( big_foo, 1, 2, d='bar', c='foo') assert (args == expected) def test_17_memoize_none_value(self): self.memoizer = Memoizer() @self.memoizer.memoize() def foo(): return None cache_key = foo.make_cache_key(foo.uncached) assert ( self.memoizer.get(cache_key) is self.memoizer.default_cache_value) result = foo() assert result is None assert self.memoizer.get(cache_key) is None self.memoizer.delete_memoized(foo) cache_key = foo.make_cache_key(foo.uncached) assert ( self.memoizer.get(cache_key) is self.memoizer.default_cache_value) def test_17_delete_memoized_instancemethod_with_mutable_param(self): class Foo(object): def __init__(self, id): self.id = id @self.memoizer.memoize(5) def foo(self, bar_obj): return random.randrange(0, 100000) + bar_obj.id def __repr__(self): return ('{}({})'.format(self.__class__.__name__, self.id)) class Bar(object): def __init__(self, id): self.id = id def __repr__(self): return ('{}({})'.format(self.__class__.__name__, self.id)) a = Foo(1) b = Bar(1) c = Bar(2) result1 = a.foo(b) result2 = a.foo(c) time.sleep(1) assert(a.foo(b) == result1) assert(a.foo(c) == result2) self.memoizer.delete_memoized(a.foo, a, b) assert(a.foo(b) != result1) assert(a.foo(c) == result2)