pax_global_header00006660000000000000000000000064143354370260014521gustar00rootroot0000000000000052 comment=2ea8e6d086b4183c41f0178fa0bf17d1add74eb6 lazy-1.5.1/000077500000000000000000000000001433543702600125045ustar00rootroot00000000000000lazy-1.5.1/.github/000077500000000000000000000000001433543702600140445ustar00rootroot00000000000000lazy-1.5.1/.github/workflows/000077500000000000000000000000001433543702600161015ustar00rootroot00000000000000lazy-1.5.1/.github/workflows/python-package.yml000066400000000000000000000053541433543702600215450ustar00rootroot00000000000000name: CI on: push: branches: [main] pull_request: branches: [main] env: PIP_DISABLE_PIP_VERSION_CHECK: 1 PIP_NO_PYTHON_VERSION_WARNING: 1 jobs: build: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["2.7", "3.6", "3.7", "3.8", "3.9", "3.10", "3.11", pypy-2.7, pypy-3.9] steps: - name: Cancel previous runs uses: styfle/cancel-workflow-action@0.11.0 with: all_but_latest: true - name: Check out project uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Get pip cache info id: pip-cache run: | echo "dir=$(python -m pip cache dir)" >> $GITHUB_OUTPUT echo "py=$(python -c'import sys; print("%d.%d" % sys.version_info[:2])')" >> $GITHUB_OUTPUT - name: Cache pip uses: actions/cache@v3 with: path: ${{ steps.pip-cache.outputs.dir }} key: ${{ runner.os }}-pip-py${{ steps.pip-cache.outputs.py }}-${{ hashFiles('setup.cfg') }} restore-keys: ${{ runner.os }}-pip-py${{ steps.pip-cache.outputs.py }}- - name: Install dependencies run: python -m pip install -e . - name: List installed packages run: python -m pip list - name: Run tests run: python -m unittest discover type-check: runs-on: ubuntu-latest strategy: fail-fast: false matrix: python-version: ["3.9", "3.10", "3.11"] steps: - name: Cancel previous runs uses: styfle/cancel-workflow-action@0.11.0 with: all_but_latest: true - name: Check out project uses: actions/checkout@v3 - name: Set up Python ${{ matrix.python-version }} uses: actions/setup-python@v4 with: python-version: ${{ matrix.python-version }} - name: Get pip cache info id: pip-cache run: | echo "dir=$(python -m pip cache dir)" >> $GITHUB_OUTPUT echo "py=$(python -c'import sys; print("%d.%d" % sys.version_info[:2])')" >> $GITHUB_OUTPUT - name: Cache pip uses: actions/cache@v3 with: path: ${{ steps.pip-cache.outputs.dir }} key: ${{ runner.os }}-pip-py${{ steps.pip-cache.outputs.py }}-${{ hashFiles('setup.cfg') }} restore-keys: ${{ runner.os }}-pip-py${{ steps.pip-cache.outputs.py }}- - name: Install dependencies run: python -m pip install -e .[testing] - name: List installed packages run: python -m pip list - name: Run type checker run: python -m mypy --strict --exclude lazy/tests lazy lazy-1.5.1/.readthedocs.yaml000066400000000000000000000003261433543702600157340ustar00rootroot00000000000000version: 2 build: os: "ubuntu-20.04" tools: python: "3.10" python: install: - method: pip path: . extra_requirements: - docs sphinx: configuration: docs/conf.py formats: all lazy-1.5.1/CHANGES.rst000066400000000000000000000021341433543702600143060ustar00rootroot00000000000000Changelog ========= 1.6 - Unreleased ---------------- 1.5 - 2022-09-18 ---------------- - Allow type checkers to infer the type of a lazy attribute. Thanks to Elias Keis and Palpatineli for their contributions. [elKei24] [Palpatineli] - Add Python 3.8-3.11 to tox.ini. Remove old Python versions. [stefan] - Replace deprecated ``python setup.py test`` in tox.ini. [stefan] - Remove deprecated ``test_suite`` from setup.py. [stefan] - Move metadata to setup.cfg and add a pyproject.toml file. [stefan] - Include tests in sdist but not in wheel. [stefan] 1.4 - 2019-01-28 ---------------- - Add MANIFEST.in. [stefan] - Release as universal wheel. [stefan] 1.3 - 2017-02-05 ---------------- - Support Python 2.6-3.6 without 2to3. [stefan] - Add a LICENSE file. [stefan] 1.2 - 2014-04-19 ---------------- - Remove setuptools from install_requires because it isn't. [stefan] 1.1 - 2012-10-12 ---------------- - Use ``functools.wraps()`` properly; the list of attributes changes with every version of Python 3. [stefan] 1.0 - 2011-03-24 ---------------- - Initial release. lazy-1.5.1/LICENSE000066400000000000000000000024101433543702600135060ustar00rootroot00000000000000Copyright (c) 2011-2022 Stefan H. Holek All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: 1. Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. 2. 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. THIS SOFTWARE IS PROVIDED BY THE AUTHOR 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 AUTHOR 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. lazy-1.5.1/MANIFEST.in000066400000000000000000000001451433543702600142420ustar00rootroot00000000000000include LICENSE tox.ini *.rst recursive-include lazy/examples *.py recursive-include lazy/tests *.py lazy-1.5.1/README.rst000066400000000000000000000032321433543702600141730ustar00rootroot00000000000000==== lazy ==== ---------------------------------- Lazy attributes for Python objects ---------------------------------- Package Contents ================ @lazy A decorator to create lazy attributes. Overview ======== Lazy attributes are computed attributes that are evaluated only once, the first time they are used. Subsequent uses return the results of the first call. They come handy when code should run - *late*, i.e. just before it is needed, and - *once*, i.e. not twice, in the lifetime of an object. You can think of it as *deferred initialization*. The possibilities are endless. Typing ====== The decorator is fully typed. Type checkers can infer the type of a lazy attribute from the return value of the decorated method. Examples ======== The class below creates its ``store`` resource lazily: .. code-block:: python from lazy import lazy class FileUploadTmpStore(object): @lazy def store(self): location = settings.get('fs.filestore') return FileSystemStore(location) def put(self, uid, fp): self.store.put(uid, fp) fp.seek(0) def get(self, uid, default=None): return self.store.get(uid, default) Another application area is caching: .. code-block:: python class PersonView(View): @lazy def person_id(self): return self.request.get('person_id', -1) @lazy def person_data(self): return self.session.query(Person).get(self.person_id) Documentation ============= For further details please refer to the `API Documentation`_. .. _`API Documentation`: https://lazy.readthedocs.io/en/stable/ lazy-1.5.1/docs/000077500000000000000000000000001433543702600134345ustar00rootroot00000000000000lazy-1.5.1/docs/Makefile000066400000000000000000000126731433543702600151050ustar00rootroot00000000000000# Makefile for Sphinx documentation # # You can set these variables from the command line. SPHINXOPTS = SPHINXBUILD = ../bin/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) . # the i18n builder cannot share the environment and doctrees with the others I18NSPHINXOPTS = $(PAPEROPT_$(PAPER)) $(SPHINXOPTS) . .PHONY: help clean html dirhtml singlehtml pickle json htmlhelp qthelp devhelp epub latex latexpdf text man changes linkcheck doctest gettext 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 " texinfo to make Texinfo files" @echo " info to make Texinfo files and run them through makeinfo" @echo " gettext to make PO message catalogs" @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/term.qhcp" @echo "To view the help file:" @echo "# assistant -collectionFile $(BUILDDIR)/qthelp/term.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/term" @echo "# ln -s $(BUILDDIR)/devhelp $$HOME/.local/share/devhelp/term" @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." texinfo: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo @echo "Build finished. The Texinfo files are in $(BUILDDIR)/texinfo." @echo "Run \`make' in that directory to run these through makeinfo" \ "(use \`make info' here to do that automatically)." info: $(SPHINXBUILD) -b texinfo $(ALLSPHINXOPTS) $(BUILDDIR)/texinfo @echo "Running Texinfo files through makeinfo..." make -C $(BUILDDIR)/texinfo info @echo "makeinfo finished; the Info files are in $(BUILDDIR)/texinfo." gettext: $(SPHINXBUILD) -b gettext $(I18NSPHINXOPTS) $(BUILDDIR)/locale @echo @echo "Build finished. The message catalogs are in $(BUILDDIR)/locale." 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." lazy-1.5.1/docs/_build/000077500000000000000000000000001433543702600146725ustar00rootroot00000000000000lazy-1.5.1/docs/_build/.placeholder000066400000000000000000000000001433543702600171430ustar00rootroot00000000000000lazy-1.5.1/docs/_static/000077500000000000000000000000001433543702600150625ustar00rootroot00000000000000lazy-1.5.1/docs/_static/.placeholder000066400000000000000000000000001433543702600173330ustar00rootroot00000000000000lazy-1.5.1/docs/_templates/000077500000000000000000000000001433543702600155715ustar00rootroot00000000000000lazy-1.5.1/docs/_templates/.placeholder000066400000000000000000000000001433543702600200420ustar00rootroot00000000000000lazy-1.5.1/docs/conf.py000066400000000000000000000200161433543702600147320ustar00rootroot00000000000000# -*- coding: utf-8 -*- # # lazy documentation build configuration file, created by # sphinx-quickstart on Thu May 10 17:11:01 2012. # # 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 # 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('.')) # -- 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'lazy' copyright = u'2011-2022, Stefan H. Holek' # 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 full version, including alpha/beta/rc tags. release = '1.5' # The short X.Y version. version = '1.5' # 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. try: import sphinx_rtd_theme except ImportError: pass else: html_theme = 'sphinx_rtd_theme' html_theme_path = [sphinx_rtd_theme.get_html_theme_path()] # 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 = {} # Add any paths that contain custom themes here, relative to this directory. #html_theme_path = [] # 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 html_show_sourcelink = False # 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 = '' # This is the file name suffix for HTML files (e.g. ".xhtml"). #html_file_suffix = None # Output file base name for HTML help builder. htmlhelp_basename = 'lazydoc' # -- Options for LaTeX output -------------------------------------------------- latex_elements = { # The paper size ('letterpaper' or 'a4paper'). #'papersize': 'letterpaper', # The font size ('10pt', '11pt' or '12pt'). #'pointsize': '10pt', # Additional stuff for the LaTeX preamble. #'preamble': '', } # Grouping the document tree into LaTeX files. List of tuples # (source start file, target name, title, author, documentclass [howto/manual]). latex_documents = [ ('index', 'lazy.tex', u'lazy Documentation', u'Stefan H. Holek', '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 # 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', 'lazy', u'lazy Documentation', [u'Stefan H. Holek'], 1) ] # If true, show URL addresses after external links. #man_show_urls = False # -- Options for Texinfo output ------------------------------------------------ # Grouping the document tree into Texinfo files. List of tuples # (source start file, target name, title, author, # dir menu entry, description, category) texinfo_documents = [ ('index', 'lazy', u'lazy Documentation', u'Stefan H. Holek', 'lazy', 'One line description of project.', 'Miscellaneous'), ] # Documents to append as an appendix to all manuals. #texinfo_appendices = [] # If false, no module index is generated. #texinfo_domain_indices = True # How to display URL addresses: 'footnote', 'no', or 'inline'. #texinfo_show_urls = 'footnote' # -- Intersphinx configuration ------------------------------------------------- intersphinx_mapping = { 'py': ('https://docs.python.org/2', 'https://docs.python.org/2/objects.inv'), 'py3k': ('https://docs.python.org/3', 'https://docs.python.org/3/objects.inv'), } lazy-1.5.1/docs/index.rst000066400000000000000000000027771433543702600153120ustar00rootroot00000000000000.. lazy documentation master file, created by sphinx-quickstart on Thu May 10 17:11:01 2012. You can adapt this file completely to your liking, but it should at least contain the root `toctree` directive. =============================================== lazy |version| -- Lazy Attributes =============================================== .. toctree:: :maxdepth: 2 .. module:: lazy The :mod:`lazy` module provides a decorator to create lazy attributes. A lazy attribute is a computed attribute that is evaluated only once, the first time it is used. Subsequent uses return the results of the first call. The decorator is fully typed, and type checkers can infer the type of a lazy attribute from the return value of the decorated method. API Documentation ================= .. class:: lazy(func) lazy descriptor. Used as a decorator to create lazy attributes. Lazy attributes are evaluated on first use. .. classmethod:: invalidate(inst, name) Invalidate lazy attribute `name` of instance `inst`. This obviously violates the :class:`~lazy.lazy` contract. Subclasses of :class:`~lazy.lazy` may however have a contract where invalidation is appropriate. .. note:: The :class:`~lazy.lazy` descriptor is not thread safe. If your objects are used across thread boundaries, you may be better off with a locking descriptor like :func:`cached_property `. Indices and Tables ================== * :ref:`genindex` * :ref:`modindex` * :ref:`search` lazy-1.5.1/lazy/000077500000000000000000000000001433543702600134635ustar00rootroot00000000000000lazy-1.5.1/lazy/__init__.py000066400000000000000000000002011433543702600155650ustar00rootroot00000000000000"""The lazy module.""" from __future__ import absolute_import from .lazy import lazy __all__ = ["lazy"] # Re-export attribute lazy-1.5.1/lazy/examples/000077500000000000000000000000001433543702600153015ustar00rootroot00000000000000lazy-1.5.1/lazy/examples/__init__.py000066400000000000000000000000001433543702600174000ustar00rootroot00000000000000lazy-1.5.1/lazy/examples/example.py000066400000000000000000000040211433543702600173030ustar00rootroot00000000000000from datetime import date from lazy import lazy class C(object): @lazy def foo(self) -> str: return 'foo' @lazy def bar(self) -> str: return 'bar' @lazy def baz(self) -> int: return 42 @lazy def quux(self) -> date: return date(2010, 10, 10) class D(C): @lazy def foo(self) -> str: return super().foo def f() -> None: c = C() 'hello ' + c.foo 'hello ' + c.bar 1 + c.baz str(c.baz) == '42' c.quux.strftime('%y') == '10' lazy.invalidate(c, 'foo') type(C.foo) == lazy type(C.bar) == lazy type(c.foo) == str type(c.baz) == int d = D() 'hello ' + d.foo 'hello ' + super(D, d).foo # Inherit from lazy # Also see https://github.com/python/mypy/pull/8573/files from typing import TYPE_CHECKING, TypeVar _R = TypeVar('_R') if TYPE_CHECKING: class cached(lazy[_R]): pass else: class cached(lazy): pass class E(object): @cached def foo(self) -> str: return 'foo' @cached def bar(self) -> str: return 'bar' @cached def baz(self) -> int: return 42 @cached def quux(self) -> date: return date(2010, 10, 10) def g() -> None: e = E() 'hello' + e.foo 'hello' + e.bar 1 + e.baz str(e.baz) == '42' e.quux.strftime('%y') == '10' cached.invalidate(e, 'foo') # Check Python >= 3.9 class Y(object): @lazy[str] def foo(self) -> str: return 'foo' @cached[str] def bar(self) -> str: return 'bar' @cached[int] def baz(self) -> int: return 42 def h() -> None: y = Y() 'hello' + y.foo 'hello' + y.bar 1 + y.baz # Check __class_getitem__ declaration if TYPE_CHECKING: from typing import Any from types import GenericAlias class supercached(lazy[_R]): @classmethod def __class_getitem__(cls, params: Any) -> GenericAlias: return super().__class_getitem__(params) if __name__ == '__main__': f() g() h() lazy-1.5.1/lazy/lazy.py000066400000000000000000000034361433543702600150220ustar00rootroot00000000000000"""Decorator to create lazy attributes.""" import sys import functools if sys.version_info >= (3, 9): from types import GenericAlias _marker = object() class lazy(object): """lazy descriptor Used as a decorator to create lazy attributes. Lazy attributes are evaluated on first use. """ def __init__(self, func): self.__func = func functools.wraps(self.__func)(self) def __get__(self, inst, inst_cls): if inst is None: return self if not hasattr(inst, '__dict__'): raise AttributeError("'%s' object has no attribute '__dict__'" % (inst_cls.__name__,)) name = self.__name__ if name.startswith('__') and not name.endswith('__'): name = '_%s%s' % (inst_cls.__name__, name) value = inst.__dict__.get(name, _marker) if value is _marker: inst.__dict__[name] = value = self.__func(inst) return value @classmethod def invalidate(cls, inst, name): """Invalidate a lazy attribute. This obviously violates the lazy contract. A subclass of lazy may however have a contract where invalidation is appropriate. """ inst_cls = inst.__class__ if not hasattr(inst, '__dict__'): raise AttributeError("'%s' object has no attribute '__dict__'" % (inst_cls.__name__,)) if name.startswith('__') and not name.endswith('__'): name = '_%s%s' % (inst_cls.__name__, name) if not isinstance(getattr(inst_cls, name), cls): raise AttributeError("'%s.%s' is not a %s attribute" % (inst_cls.__name__, name, cls.__name__)) if name in inst.__dict__: del inst.__dict__[name] if sys.version_info >= (3, 9): __class_getitem__ = classmethod(GenericAlias) lazy-1.5.1/lazy/lazy.pyi000066400000000000000000000013011433543702600151600ustar00rootroot00000000000000import sys from typing import TypeVar, Callable, Type, Generic from typing import Optional, Any, overload if sys.version_info >= (3, 9): from types import GenericAlias _R = TypeVar("_R") class lazy(Generic[_R]): __func: Callable[[Any], _R] def __init__(self, func: Callable[[Any], _R]) -> None: ... @overload def __get__(self, inst: None, inst_cls: Optional[Type[Any]] = ...) -> lazy[_R]: ... @overload def __get__(self, inst: object, inst_cls: Optional[Type[Any]] = ...) -> _R: ... @classmethod def invalidate(cls, inst: object, name: str) -> None: ... if sys.version_info >= (3, 9): def __class_getitem__(cls, params: Any) -> GenericAlias: ... lazy-1.5.1/lazy/py.typed000066400000000000000000000001011433543702600151520ustar00rootroot00000000000000# Marker file indicating support for type checking. See PEP 561. lazy-1.5.1/lazy/tests/000077500000000000000000000000001433543702600146255ustar00rootroot00000000000000lazy-1.5.1/lazy/tests/__init__.py000066400000000000000000000000001433543702600167240ustar00rootroot00000000000000lazy-1.5.1/lazy/tests/test_lazy.py000066400000000000000000000435041433543702600172230ustar00rootroot00000000000000import sys import unittest from lazy import lazy class TestCase(unittest.TestCase): def assertException(self, exc_cls, pattern, func, *args, **kw): """Assert an exception of type 'exc_cls' is raised and 'pattern' is contained in the exception message. """ try: func(*args, **kw) except exc_cls as e: exc_str = str(e) else: self.fail('%s not raised' % (exc_cls.__name__,)) if pattern not in exc_str: self.fail('%r not in %r' % (pattern, exc_str)) class LazyTests(TestCase): def test_evaluate(self): # Lazy attributes should be evaluated when accessed. called = [] class Foo(object): @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertEqual(f.foo, 1) self.assertEqual(len(called), 1) def test_evaluate_once(self): # Lazy attributes should be evaluated only once. called = [] class Foo(object): @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertEqual(f.foo, 1) self.assertEqual(f.foo, 1) self.assertEqual(f.foo, 1) self.assertEqual(len(called), 1) def test_private_attribute(self): # It should be possible to create private, name-mangled # lazy attributes. called = [] class Foo(object): @lazy def __foo(self): called.append('foo') return 1 def get_foo(self): return self.__foo f = Foo() self.assertEqual(f.get_foo(), 1) self.assertEqual(f.get_foo(), 1) self.assertEqual(f.get_foo(), 1) self.assertEqual(len(called), 1) def test_reserved_attribute(self): # It should be possible to create reserved lazy attributes. called = [] class Foo(object): @lazy def __foo__(self): called.append('foo') return 1 f = Foo() self.assertEqual(f.__foo__, 1) self.assertEqual(f.__foo__, 1) self.assertEqual(f.__foo__, 1) self.assertEqual(len(called), 1) def test_result_shadows_descriptor(self): # The result of the function call should be stored in # the object __dict__, shadowing the descriptor. called = [] class Foo(object): @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertTrue(isinstance(Foo.foo, lazy)) self.assertTrue(f.foo is f.foo) self.assertTrue(f.foo is f.__dict__['foo']) # ! self.assertEqual(len(called), 1) self.assertEqual(f.foo, 1) self.assertEqual(f.foo, 1) self.assertEqual(len(called), 1) lazy.invalidate(f, 'foo') self.assertEqual(f.foo, 1) self.assertEqual(len(called), 2) self.assertEqual(f.foo, 1) self.assertEqual(f.foo, 1) self.assertEqual(len(called), 2) def test_readonly_object(self): # The descriptor should raise an AttributeError when lazy is # used on a read-only object (an object with __slots__). called = [] class Foo(object): __slots__ = () @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertEqual(len(called), 0) self.assertException(AttributeError, "'Foo' object has no attribute '__dict__'", getattr, f, 'foo') # The function was not called self.assertEqual(len(called), 0) def test_introspection(self): # The lazy decorator should support basic introspection. class Foo(object): def foo(self): """foo func doc""" @lazy def bar(self): """bar func doc""" self.assertEqual(Foo.foo.__name__, "foo") self.assertEqual(Foo.foo.__doc__, "foo func doc") self.assertEqual(Foo.foo.__module__, "lazy.tests.test_lazy") self.assertEqual(Foo.bar.__name__, "bar") self.assertEqual(Foo.bar.__doc__, "bar func doc") self.assertEqual(Foo.bar.__module__, "lazy.tests.test_lazy") def test_types(self): # A lazy attribute should be of type lazy. class Foo(object): @lazy def foo(self): return 1 @property def bar(self): return "bar" self.assertEqual(type(Foo.foo), lazy) self.assertEqual(type(Foo.bar), property) f = Foo() self.assertEqual(type(f.foo), int) self.assertEqual(type(f.bar), str) def test_super(self): # A lazy attribute should work when invoked via super. class Foo(object): @lazy def foo(self): return 'foo' class Bar(Foo): @lazy def foo(self): return super(Bar, self).foo + 'x' class Baz(Foo): @lazy def foo(self): return super().foo + 'xx' b = Bar() self.assertEqual(b.foo, 'foox') self.assertEqual(b.foo, 'foox') if sys.version_info >= (3,): b = Baz() self.assertEqual(b.foo, 'fooxx') self.assertEqual(b.foo, 'fooxx') def test_super_binding(self): # It should be impossible to change the cache once set. class Foo(object): @lazy def foo(self): return 'foo' class Bar(Foo): @lazy def foo(self): return super(Bar, self).foo + 'x' b = Bar() self.assertEqual(b.foo, 'foox') orig_id = id(b.foo) self.assertEqual(b.foo, 'foox') self.assertEqual(orig_id, id(b.foo)) self.assertEqual(super(Bar, b).foo, 'foox') self.assertEqual(orig_id, id(b.foo)) lazy.invalidate(b, 'foo') self.assertEqual(super(Bar, b).foo, 'foo') self.assertEqual(b.foo, 'foo') class InvalidateTests(TestCase): def test_invalidate_attribute(self): # It should be possible to invalidate a lazy attribute. called = [] class Foo(object): @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertEqual(f.foo, 1) self.assertEqual(len(called), 1) lazy.invalidate(f, 'foo') self.assertEqual(f.foo, 1) self.assertEqual(len(called), 2) def test_invalidate_attribute_twice(self): # It should be possible to invalidate a lazy attribute # twice without causing harm. called = [] class Foo(object): @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertEqual(f.foo, 1) self.assertEqual(len(called), 1) lazy.invalidate(f, 'foo') lazy.invalidate(f, 'foo') # Nothing happens self.assertEqual(f.foo, 1) self.assertEqual(len(called), 2) def test_invalidate_uncalled_attribute(self): # It should be possible to invalidate an empty attribute # cache without causing harm. called = [] class Foo(object): @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertEqual(len(called), 0) lazy.invalidate(f, 'foo') # Nothing happens def test_invalidate_private_attribute(self): # It should be possible to invalidate a private lazy attribute. called = [] class Foo(object): @lazy def __foo(self): called.append('foo') return 1 def get_foo(self): return self.__foo f = Foo() self.assertEqual(f.get_foo(), 1) self.assertEqual(len(called), 1) lazy.invalidate(f, '__foo') self.assertEqual(f.get_foo(), 1) self.assertEqual(len(called), 2) def test_invalidate_mangled_attribute(self): # It should be possible to invalidate a private lazy attribute # by its mangled name. called = [] class Foo(object): @lazy def __foo(self): called.append('foo') return 1 def get_foo(self): return self.__foo f = Foo() self.assertEqual(f.get_foo(), 1) self.assertEqual(len(called), 1) lazy.invalidate(f, '_Foo__foo') self.assertEqual(f.get_foo(), 1) self.assertEqual(len(called), 2) def test_invalidate_reserved_attribute(self): # It should be possible to invalidate a reserved lazy attribute. called = [] class Foo(object): @lazy def __foo__(self): called.append('foo') return 1 f = Foo() self.assertEqual(f.__foo__, 1) self.assertEqual(len(called), 1) lazy.invalidate(f, '__foo__') self.assertEqual(f.__foo__, 1) self.assertEqual(len(called), 2) def test_invalidate_nonlazy_attribute(self): # Invalidating an attribute that is not lazy should # raise an AttributeError. called = [] class Foo(object): def foo(self): called.append('foo') return 1 f = Foo() self.assertException(AttributeError, "'Foo.foo' is not a lazy attribute", lazy.invalidate, f, 'foo') def test_invalidate_nonlazy_private_attribute(self): # Invalidating a private attribute that is not lazy should # raise an AttributeError. called = [] class Foo(object): def __foo(self): called.append('foo') return 1 f = Foo() self.assertException(AttributeError, "'Foo._Foo__foo' is not a lazy attribute", lazy.invalidate, f, '__foo') def test_invalidate_unknown_attribute(self): # Invalidating an unknown attribute should # raise an AttributeError. called = [] class Foo(object): @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertException(AttributeError, "type object 'Foo' has no attribute 'bar'", lazy.invalidate, f, 'bar') def test_invalidate_readonly_object(self): # Calling invalidate on a read-only object should # raise an AttributeError. called = [] class Foo(object): __slots__ = () @lazy def foo(self): called.append('foo') return 1 f = Foo() self.assertException(AttributeError, "'Foo' object has no attribute '__dict__'", lazy.invalidate, f, 'foo') # A lazy subclass class cached(lazy): pass class InvalidateSubclassTests(TestCase): def test_invalidate_attribute(self): # It should be possible to invalidate a cached attribute. called = [] class Bar(object): @cached def bar(self): called.append('bar') return 1 b = Bar() self.assertEqual(b.bar, 1) self.assertEqual(len(called), 1) cached.invalidate(b, 'bar') self.assertEqual(b.bar, 1) self.assertEqual(len(called), 2) def test_invalidate_attribute_twice(self): # It should be possible to invalidate a cached attribute # twice without causing harm. called = [] class Bar(object): @cached def bar(self): called.append('bar') return 1 b = Bar() self.assertEqual(b.bar, 1) self.assertEqual(len(called), 1) cached.invalidate(b, 'bar') cached.invalidate(b, 'bar') # Nothing happens self.assertEqual(b.bar, 1) self.assertEqual(len(called), 2) def test_invalidate_uncalled_attribute(self): # It should be possible to invalidate an empty attribute # cache without causing harm. called = [] class Bar(object): @cached def bar(self): called.append('bar') return 1 b = Bar() self.assertEqual(len(called), 0) cached.invalidate(b, 'bar') # Nothing happens def test_invalidate_private_attribute(self): # It should be possible to invalidate a private cached attribute. called = [] class Bar(object): @cached def __bar(self): called.append('bar') return 1 def get_bar(self): return self.__bar b = Bar() self.assertEqual(b.get_bar(), 1) self.assertEqual(len(called), 1) cached.invalidate(b, '__bar') self.assertEqual(b.get_bar(), 1) self.assertEqual(len(called), 2) def test_invalidate_mangled_attribute(self): # It should be possible to invalidate a private cached attribute # by its mangled name. called = [] class Bar(object): @cached def __bar(self): called.append('bar') return 1 def get_bar(self): return self.__bar b = Bar() self.assertEqual(b.get_bar(), 1) self.assertEqual(len(called), 1) cached.invalidate(b, '_Bar__bar') self.assertEqual(b.get_bar(), 1) self.assertEqual(len(called), 2) def test_invalidate_reserved_attribute(self): # It should be possible to invalidate a reserved cached attribute. called = [] class Bar(object): @cached def __bar__(self): called.append('bar') return 1 b = Bar() self.assertEqual(b.__bar__, 1) self.assertEqual(len(called), 1) cached.invalidate(b, '__bar__') self.assertEqual(b.__bar__, 1) self.assertEqual(len(called), 2) def test_invalidate_uncached_attribute(self): # Invalidating an attribute that is not cached should # raise an AttributeError. called = [] class Bar(object): def bar(self): called.append('bar') return 1 b = Bar() self.assertException(AttributeError, "'Bar.bar' is not a cached attribute", cached.invalidate, b, 'bar') def test_invalidate_uncached_private_attribute(self): # Invalidating a private attribute that is not cached should # raise an AttributeError. called = [] class Bar(object): def __bar(self): called.append('bar') return 1 b = Bar() self.assertException(AttributeError, "'Bar._Bar__bar' is not a cached attribute", cached.invalidate, b, '__bar') def test_invalidate_unknown_attribute(self): # Invalidating an unknown attribute should # raise an AttributeError. called = [] class Bar(object): @cached def bar(self): called.append('bar') return 1 b = Bar() self.assertException(AttributeError, "type object 'Bar' has no attribute 'baz'", lazy.invalidate, b, 'baz') def test_invalidate_readonly_object(self): # Calling invalidate on a read-only object should # raise an AttributeError. called = [] class Bar(object): __slots__ = () @cached def bar(self): called.append('bar') return 1 b = Bar() self.assertException(AttributeError, "'Bar' object has no attribute '__dict__'", cached.invalidate, b, 'bar') def test_invalidate_superclass_attribute(self): # cached.invalidate CANNOT invalidate a superclass (lazy) attribute. called = [] class Bar(object): @lazy def bar(self): called.append('bar') return 1 b = Bar() self.assertException(AttributeError, "'Bar.bar' is not a cached attribute", cached.invalidate, b, 'bar') def test_invalidate_subclass_attribute(self): # Whereas lazy.invalidate CAN invalidate a subclass (cached) attribute. called = [] class Bar(object): @cached def bar(self): called.append('bar') return 1 b = Bar() self.assertEqual(b.bar, 1) self.assertEqual(len(called), 1) lazy.invalidate(b, 'bar') self.assertEqual(b.bar, 1) self.assertEqual(len(called), 2) class AssertExceptionTests(TestCase): def test_assert_AttributeError(self): self.assertException(AttributeError, "'AssertExceptionTests' object has no attribute 'foobar'", getattr, self, 'foobar') def test_assert_IOError(self): self.assertException(IOError, "No such file or directory", open, './foo/bar/baz/peng/quux', 'rb') def test_assert_SystemExit(self): self.assertException(SystemExit, "", sys.exit) def test_assert_exception_not_raised(self): self.assertRaises(AssertionError, self.assertException, AttributeError, "'AssertExceptionTests' object has no attribute 'run'", getattr, self, 'run') def test_assert_pattern_mismatch(self): self.assertRaises(AssertionError, self.assertException, AttributeError, "baz", getattr, self, 'foobar') lazy-1.5.1/pyproject.toml000066400000000000000000000001321433543702600154140ustar00rootroot00000000000000[build-system] requires = ["setuptools", "wheel"] build-backend = "setuptools.build_meta" lazy-1.5.1/setup.cfg000066400000000000000000000023131433543702600143240ustar00rootroot00000000000000[metadata] name = lazy version = 1.6 description = Lazy attributes for Python objects long_description = file: README.rst, CHANGES.rst long_description_content_type = text/x-rst classifiers = Development Status :: 5 - Production/Stable Intended Audience :: Developers License :: OSI Approved :: BSD License Operating System :: OS Independent Programming Language :: Python Programming Language :: Python :: 2 Programming Language :: Python :: 3 keywords = decorator, lazy, lazy attribute, descriptor, property author = Stefan H. Holek author_email = stefan@epy.co.at url = https://github.com/stefanholek/lazy project_urls = Documentation = https://lazy.readthedocs.io/en/stable/ license = BSD-2-Clause [options] packages = find: include_package_data = false zip_safe = false python_requires = >=2.7,!=3.0.*,!=3.1.*,!=3.2.*,!=3.3.* [options.packages.find] exclude = lazy.examples lazy.tests [options.package_data] lazy = lazy.pyi py.typed [options.extras_require] testing = mypy docs = sphinx == 5.3.0 sphinx-rtd-theme == 1.0.0 [egg_info] tag_build = dev0 [bdist_wheel] universal = true [build_sphinx] source_dir = docs build_dir = docs/_build all_files = true lazy-1.5.1/setup.py000066400000000000000000000000461433543702600142160ustar00rootroot00000000000000from setuptools import setup setup() lazy-1.5.1/tox.ini000066400000000000000000000013171433543702600140210ustar00rootroot00000000000000# Tox (https://tox.readthedocs.io/) is a tool for running tests # in multiple virtualenvs. This configuration file will run the # test suite on all supported Python versions. To use it, # "pip install tox" and then run "tox" from this directory. [tox] envlist = py27, py36, py37, py38, py39, py310, py311, pypy, pypy3, mypy [testenv] commands = python -m unittest discover {posargs} [testenv:pypy] basepython = pypy-2.7 [testenv:pypy3] basepython = pypy-3.8 [testenv:mypy] extras = testing commands = python -m mypy --strict --exclude lazy/tests {posargs} lazy python lazy/examples/example.py [testenv:docs] extras = docs commands = python setup.py build_sphinx {posargs} [pytest] testpaths = lazy/tests