diff --git a/.github/dependabot.yml b/.github/dependabot.yml new file mode 100644 index 0000000..d318b22 --- /dev/null +++ b/.github/dependabot.yml @@ -0,0 +1,16 @@ +version: 2 +updates: +- package-ecosystem: pip + directory: "/" + schedule: + interval: daily + time: "04:00" + open-pull-requests-limit: 10 + ignore: + - dependency-name: twine + versions: + - 3.3.0 + - 3.4.0 + - dependency-name: coverage + versions: + - "5.4" diff --git a/.gitignore b/.gitignore index b0df7f7..ac7a9b0 100644 --- a/.gitignore +++ b/.gitignore @@ -1,53 +1,131 @@ + +# Created by https://www.gitignore.io/api/python +# Edit at https://www.gitignore.io/?templates=python + +### Python ### +# Byte-compiled / optimized / DLL files +__pycache__/ *.py[cod] +*$py.class # C extensions *.so -# Packages -*.egg -*.egg-info -dist -build -eggs -parts -bin -var -sdist -develop-eggs +# Distribution / packaging +.Python +build/ +develop-eggs/ +dist/ +downloads/ +eggs/ +.eggs/ +lib/ +lib64/ +parts/ +sdist/ +var/ +wheels/ +pip-wheel-metadata/ +share/python-wheels/ +*.egg-info/ .installed.cfg -lib -lib64 +*.egg +MANIFEST + +# PyInstaller +# Usually these files are written by a python script from a template +# before PyInstaller builds the exe, so as to inject date/other infos into it. +*.manifest +*.spec # Installer logs pip-log.txt +pip-delete-this-directory.txt # Unit test / coverage reports +htmlcov/ +.tox/ +.nox/ .coverage -.tox -nosetests.xml -htmlcov +.coverage.* .cache -.pytest_cache +nosetests.xml +coverage.xml +*.cover +.hypothesis/ +.pytest_cache/ # Translations *.mo +*.pot + +# Django stuff: +*.log +local_settings.py +db.sqlite3 +db.sqlite3-journal + +# Flask stuff: +instance/ +.webassets-cache + +# Scrapy stuff: +.scrapy + +# Sphinx documentation +docs/_build/ + +# PyBuilder +target/ + +# Jupyter Notebook +.ipynb_checkpoints + +# IPython +profile_default/ +ipython_config.py + +# pyenv +.python-version + +# pipenv +# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control. +# However, in case of collaboration, if having platform-specific dependencies or dependencies +# having no cross-platform support, pipenv may install dependencies that don't work, or not +# install all needed dependencies. +#Pipfile.lock + +# celery beat schedule file +celerybeat-schedule + +# SageMath parsed files +*.sage.py + +# Environments +.env +.venv +env/ +venv/ +ENV/ +env.bak/ +venv.bak/ + +# Spyder project settings +.spyderproject +.spyproject -# Mr Developer -.mr.developer.cfg -.project -.pydevproject +# Rope project settings +.ropeproject -# Complexity -output/*.html -output/*/index.html +# mkdocs documentation +/site -# Sphinx -docs/_build +# mypy +.mypy_cache/ +.dmypy.json +dmypy.json -# IntelliJ IDEA -/.idea/ -/out/ -*.iml +# Pyre type checker +.pyre/ -# Local virtualenv directories -/venv*/ \ No newline at end of file +# End of https://www.gitignore.io/api/python diff --git a/.travis.yml b/.travis.yml index 1cf7fa4..873e8a8 100644 --- a/.travis.yml +++ b/.travis.yml @@ -1,37 +1,48 @@ # Config file for automatic testing at travis-ci.org sudo: false +dist: xenial language: python -env: - global: - - CC_TEST_REPORTER_ID=56a0691204179e8edcdde4c7ecab73b3693706aa1186ed018ca78acc663520cf +git: + depth: false -before_script: # code coverage tool - - curl -L https://codeclimate.com/downloads/test-reporter/test-reporter-latest-linux-amd64 > ./cc-test-reporter - - chmod +x ./cc-test-reporter - - ./cc-test-reporter before-build +matrix: + include: + - python: pypy3.5 + env: TESTS=tests.test_cached_property + - python: 3.5 + env: TESTS=tests.test_cached_property + - python: 3.6 + env: TESTS=tests + - python: 3.7 + env: TESTS=tests + +before_script: + - pip install -r tests/requirements.txt + +install: + - pip install . -# command to run tests and save coverage script: - - py.test --cov cached_property - -after_script: - - coverage report -m - - coverage xml - - ./cc-test-reporter format-coverage --input-type coverage.py --debug - - ./cc-test-reporter upload-coverage --debug -python: - - "3.6" - - "3.5" - - "3.4" - - "2.7" - - "pypy" + - green $TESTS -matrix: - include: - - python: 3.7 - dist: xenial - sudo: true +after_success: + - python -m coverage xml + - bash <(curl -s https://codecov.io/bash) + +before_deploy: + - python setup.py sdist bdist_wheel + - twine check dist/* + +deploy: + provider: script + on: + python: 3.7 + tags: true + repo: althonos/property-cached + skip_cleanup: true + script: twine upload --skip-existing dist/* -# command to install dependencies, e.g. pip install -r requirements.txt --use-mirrors -install: pip install -r requirements.txt +notifications: + email: + - althonosdev@gmail.com diff --git a/AUTHORS.rst b/AUTHORS.rst index f8d446d..8df0ebd 100644 --- a/AUTHORS.rst +++ b/AUTHORS.rst @@ -8,6 +8,11 @@ Development Lead * Daniel Roy Greenfeld (@pydanny) * Audrey Roy Greenfeld (@audreyr) +Maintainer +---------- + +* Martin Larralde (@althonos) + Contributors ------------ @@ -18,4 +23,7 @@ Contributors * Ionel Cristian Mărieș (@ionelmc) * Malyshev Artem (@proofit404) * Volker Braun (@vbraun) +* Vadim Pushtaev (@VadimPushtaev) +* Martin Larralde (@althonos) * Qudus Oladipo (@stikks) +* Sean Aubin (@seanny123) diff --git a/HISTORY.rst b/CHANGELOG.rst similarity index 77% rename from HISTORY.rst rename to CHANGELOG.rst index e7dbf47..8770117 100644 --- a/HISTORY.rst +++ b/CHANGELOG.rst @@ -3,6 +3,34 @@ History ------- +1.6.4 (2020-03-06) +++++++++++++++++++ + +* Fix some remaining Python 2 support code (`#25 `_) + +1.6.3 (2019-09-07) +++++++++++++++++++ + +* Resolve `cached_property` docstring not showing (`#171 `_). + +1.6.2 (2019-07-22) +++++++++++++++++++ + +* Fix metadata to keep original author and add @althonos as maintainer + +1.6.1 (2019-07-22) +++++++++++++++++++ + +* Fix unneeded dependencies being present in ``setup.cfg`` + +1.6.0 (2019-07-22) +++++++++++++++++++ + +* Fixed class hierarchy, ``cached_property`` now inherits from ``property`` +* Add support for slotted classes and stop using the object ``__dict__`` +* Improve function wrapping using ``functools.update_wrapper`` +* Implement the ``__set_name__`` magic method available since Python 3.6 + 1.5.1 (2018-08-05) ++++++++++++++++++ diff --git a/CONTRIBUTING.rst b/CONTRIBUTING.rst index 7451fcb..4c364a5 100644 --- a/CONTRIBUTING.rst +++ b/CONTRIBUTING.rst @@ -3,7 +3,7 @@ Contributing ============ Contributions are welcome, and they are greatly appreciated! Every -little bit helps, and credit will always be given. +little bit helps, and credit will always be given. You can contribute in many ways: @@ -13,7 +13,7 @@ Types of Contributions Report Bugs ~~~~~~~~~~~ -Report bugs at https://github.com/pydanny/cached-property/issues. +Report bugs at https://github.com/althonos/property-cached/issues. If you are reporting a bug, please include: @@ -36,14 +36,14 @@ is open to whoever wants to implement it. Write Documentation ~~~~~~~~~~~~~~~~~~~ -cached-property could always use more documentation, whether as part of the -official cached-property docs, in docstrings, or even on the web in blog posts, +property-cached could always use more documentation, whether as part of the +official property-cached docs, in docstrings, or even on the web in blog posts, articles, and such. Submit Feedback ~~~~~~~~~~~~~~~ -The best way to send feedback is to file an issue at https://github.com/pydanny/cached-property/issues. +The best way to send feedback is to file an issue at https://github.com/althonos/property-cached/issues. If you are proposing a feature: @@ -55,37 +55,37 @@ If you are proposing a feature: Get Started! ------------ -Ready to contribute? Here's how to set up `cached-property` for local development. +Ready to contribute? Here's how to set up ``property-cached`` for local development. -1. Fork the `cached-property` repo on GitHub. +1. Fork the ``property-cached`` repo on GitHub. 2. Clone your fork locally:: - $ git clone git@github.com:your_name_here/cached-property.git + $ git clone git@github.com:your_name_here/property-cached.git 3. Install your local copy into a virtualenv. Assuming you have virtualenvwrapper installed, this is how you set up your fork for local development:: - $ mkvirtualenv cached-property - $ cd cached-property/ + $ mkvirtualenv property-cached + $ cd property-cached/ $ python setup.py develop 4. Create a branch for local development:: $ git checkout -b name-of-your-bugfix-or-feature - + Now you can make your changes locally. - + 5. Clean up the formatting (must be running at least Python 3.6):: - + $ pip install -U black $ black . - + 6. When you're done making changes, check that your changes pass the tests, including testing other Python versions with tox:: $ pytest tests/ $ tox - To get tox, just pip install it into your virtualenv. + To get tox, just pip install it into your virtualenv. 7. Commit your changes and push your branch to GitHub:: @@ -104,8 +104,8 @@ Before you submit a pull request, check that it meets these guidelines: 2. If the pull request adds functionality, the docs should be updated. Put your new functionality into a function with a docstring, and add the feature to the list in README.rst. -3. The pull request should work for Python 2.7, and 3.3, 3.4, 3.5, 3.6 and for PyPy. Check - https://travis-ci.org/pydanny/cached-property/pull_requests +3. The pull request should work for Python 2.7, and 3.3, 3.4, 3.5, 3.6 and for PyPy. Check + https://travis-ci.org/althonos/property-cached/pull_requests and make sure that the tests pass for all supported Python versions. Tips @@ -114,4 +114,3 @@ Tips To run a subset of tests:: $ python -m unittest tests.test_cached-property - diff --git a/LICENSE b/LICENSE index a181761..a9f5694 100644 --- a/LICENSE +++ b/LICENSE @@ -1,4 +1,5 @@ -Copyright (c) 2015, Daniel Greenfeld +Copyright (c) 2018-2020, Martin Larralde +Copyright (c) 2015-2018, Daniel Greenfeld All rights reserved. Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: @@ -7,6 +8,6 @@ Redistribution and use in source and binary forms, with or without modification, * 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. -* Neither the name of cached-property nor the names of its contributors may be used to endorse or promote products derived from this software without specific prior written permission. +* Neither the name of cached-property or property-cached nor the names of its contributors may 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 HOLDER 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. diff --git a/MANIFEST.in b/MANIFEST.in index 7e355c4..97e7701 100644 --- a/MANIFEST.in +++ b/MANIFEST.in @@ -4,6 +4,8 @@ include HISTORY.rst include LICENSE include README.rst +recursive-include * _version.txt + recursive-include tests * recursive-exclude * __pycache__ recursive-exclude * *.py[co] diff --git a/Makefile b/Makefile deleted file mode 100644 index 2446d51..0000000 --- a/Makefile +++ /dev/null @@ -1,57 +0,0 @@ -.PHONY: clean-pyc clean-build docs clean - -help: - @echo "clean-build - remove build artifacts" - @echo "clean-pyc - remove Python file artifacts" - @echo "lint - check style with flake8" - @echo "test - run tests quickly with the default Python" - @echo "test-all - run tests on every Python version with tox" - @echo "coverage - check code coverage quickly with the default Python" - @echo "docs - generate Sphinx HTML documentation, including API docs" - @echo "release - package and upload a release" - @echo "dist - package" - -clean: clean-build clean-pyc - rm -fr htmlcov/ - -clean-build: - rm -fr build/ - rm -fr dist/ - rm -fr *.egg-info - -clean-pyc: - find . -name '*.pyc' -exec rm -f {} + - find . -name '*.pyo' -exec rm -f {} + - find . -name '*~' -exec rm -f {} + - -lint: - flake8 cached_property.py tests - -test: - py.test - -test-all: - tox - -coverage: - py.test --cov cached_property - coverage report -m - coverage html - open htmlcov/index.html - -docs: - rm -f docs/cached-property.rst - rm -f docs/modules.rst - sphinx-apidoc -o docs/ cached-property - $(MAKE) -C docs clean - $(MAKE) -C docs html - open docs/_build/html/index.html - -release: clean - python setup.py sdist upload - python setup.py bdist_wheel upload - -dist: clean - python setup.py sdist - python setup.py bdist_wheel - ls -l dist \ No newline at end of file diff --git a/README.rst b/README.rst index 9c57d00..b202b7c 100644 --- a/README.rst +++ b/README.rst @@ -1,26 +1,35 @@ =============================== -cached-property +property-cached =============================== -.. image:: https://img.shields.io/pypi/v/cached-property.svg - :target: https://pypi.python.org/pypi/cached-property +.. image:: https://img.shields.io/travis/althonos/property-cached/master.svg?style=flat-square + :target: https://travis-ci.org/althonos/property-cached -.. image:: https://img.shields.io/travis/pydanny/cached-property/master.svg - :target: https://travis-ci.org/pydanny/cached-property - -.. image:: https://img.shields.io/badge/code%20style-black-000000.svg - :target: https://github.com/ambv/black - :alt: Code style: black +.. image:: https://img.shields.io/codecov/c/gh/althonos/property-cached.svg?style=flat-square + :target: https://codecov.io/gh/althonos/property-cached +.. image:: https://img.shields.io/pypi/v/property-cached.svg?style=flat-square + :target: https://pypi.python.org/pypi/property-cached -A decorator for caching properties in classes. +.. image:: https://img.shields.io/badge/code%20style-black-000000.svg?style=flat-square + :target: https://github.com/ambv/black + + +A decorator for caching properties in classes (forked from ``cached-property``). + +This library was forked from the upstream library ``cached-property`` since its +developer does not seem to be maintaining it anymore. It works as a drop-in +replacement with fully compatible API (import ``property_cached`` instead of +``cached_property`` in your code and *voilà*). In case development resumes on +the original library, this one is likely to be deprecated. + +*Slightly modified README included below:* Why? ----- * Makes caching of time or computational expensive properties quick and easy. * Because I got tired of copy/pasting this code from non-web project to non-web project. -* I needed something really simple that worked in Python 2 and 3. How to use it -------------- @@ -232,22 +241,12 @@ is why they are broken out into seperate tools. See https://github.com/pydanny/c Credits -------- +* ``@pydanny`` for the original ``cached-property`` implementation. * Pip, Django, Werkzueg, Bottle, Pyramid, and Zope for having their own implementations. This package originally used an implementation that matched the Bottle version. * Reinout Van Rees for pointing out the `cached_property` decorator to me. -* My awesome wife `@audreyr`_ who created `cookiecutter`_, which meant rolling this out took me just 15 minutes. -* @tinche for pointing out the threading issue and providing a solution. -* @bcho for providing the time-to-expire feature +* ``@audreyr``_ who created ``cookiecutter``_, which meant rolling this out took ``@pydanny`` just 15 minutes. +* ``@tinche`` for pointing out the threading issue and providing a solution. +* ``@bcho`` for providing the time-to-expire feature .. _`@audreyr`: https://github.com/audreyr .. _`cookiecutter`: https://github.com/audreyr/cookiecutter - -Support This Project ---------------------------- - -This project is maintained by volunteers. Support their efforts by spreading the word about: - -.. image:: https://cdn.shopify.com/s/files/1/0304/6901/t/2/assets/logo.png?8399580890922549623 - :name: Two Scoops Press - :align: center - :alt: Two Scoops Press - :target: https://www.twoscoopspress.com diff --git a/conftest.py b/conftest.py deleted file mode 100644 index 0563f64..0000000 --- a/conftest.py +++ /dev/null @@ -1,20 +0,0 @@ - -import sys - -# Whether "import asyncio" works -has_asyncio = sys.version_info[0] == 3 and sys.version_info[1] >= 4 - -# Whether the async and await keywords work -has_async_await = sys.version_info[0] == 3 and sys.version_info[1] >= 5 - - -print("conftest.py", has_asyncio, has_async_await) - - -collect_ignore = [] - -if not has_asyncio: - collect_ignore.append("tests/test_coroutine_cached_property.py") - -if not has_async_await: - collect_ignore.append("tests/test_async_cached_property.py") diff --git a/cached_property.py b/property_cached/__init__.py similarity index 53% rename from cached_property.py rename to property_cached/__init__.py index 3e530fc..3353048 100644 --- a/cached_property.py +++ b/property_cached/__init__.py @@ -1,30 +1,31 @@ -# -*- coding: utf-8 -*- - -__author__ = "Daniel Greenfeld" -__email__ = "pydanny@gmail.com" -__version__ = "1.5.1" -__license__ = "BSD" - -from functools import wraps -from time import time +import asyncio +import functools +import pkg_resources import threading +import weakref +from time import time + -try: - import asyncio -except (ImportError, SyntaxError): - asyncio = None +__author__ = "Martin Larralde" +__email__ = "martin.larralde@ens-paris-saclay.fr" +__license__ = "BSD" +__version__ = pkg_resources.resource_string(__name__, "_version.txt").decode('utf-8').strip() -class cached_property(object): +class cached_property(property): """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Deleting the attribute resets the property. Source: https://github.com/bottlepy/bottle/commit/fa7733e075da0d790d809aa3d2f53071897e6f76 """ # noqa + _sentinel = object() + _update_wrapper = functools.update_wrapper + def __init__(self, func): - self.__doc__ = getattr(func, "__doc__") + self.cache = weakref.WeakKeyDictionary() self.func = func + self._update_wrapper(func) def __get__(self, obj, cls): if obj is None: @@ -33,48 +34,60 @@ def __get__(self, obj, cls): if asyncio and asyncio.iscoroutinefunction(self.func): return self._wrap_in_coroutine(obj) - value = obj.__dict__[self.func.__name__] = self.func(obj) + value = self.cache.get(obj, self._sentinel) + if value is self._sentinel: + value = self.cache[obj] = self.func(obj) + return value + def __set_name__(self, owner, name): + self.__name__ = name + + def __set__(self, obj, value): + self.cache[obj] = value + + def __delete__(self, obj): + del self.cache[obj] + def _wrap_in_coroutine(self, obj): - @wraps(obj) + + @functools.wraps(obj) @asyncio.coroutine def wrapper(): - future = asyncio.ensure_future(self.func(obj)) - obj.__dict__[self.func.__name__] = future - return future + value = self.cache.get(obj, self._sentinel) + if value is self._sentinel: + self.cache[obj] = value = asyncio.ensure_future(self.func(obj)) + return value return wrapper() -class threaded_cached_property(object): +class threaded_cached_property(cached_property): """ A cached_property version for use in environments where multiple threads might concurrently try to access the property. """ def __init__(self, func): - self.__doc__ = getattr(func, "__doc__") - self.func = func + super(threaded_cached_property, self).__init__(func) self.lock = threading.RLock() def __get__(self, obj, cls): if obj is None: return self + with self.lock: + return super(threaded_cached_property, self).__get__(obj, cls) - obj_dict = obj.__dict__ - name = self.func.__name__ + def __set__(self, obj, value): with self.lock: - try: - # check if the value was computed before the lock was acquired - return obj_dict[name] + super(threaded_cached_property, self).__set__(obj, value) - except KeyError: - # if not, do the calculation and release the lock - return obj_dict.setdefault(name, self.func(obj)) + def __delete__(self, obj): + with self.lock: + super(threaded_cached_property, self).__delete__(obj) -class cached_property_with_ttl(object): +class cached_property_with_ttl(cached_property): """ A property that is only computed once per instance and then replaces itself with an ordinary attribute. Setting the ttl to a number expresses how long @@ -88,10 +101,10 @@ def __init__(self, ttl=None): else: func = None self.ttl = ttl - self._prepare_func(func) + super(cached_property_with_ttl, self).__init__(func) def __call__(self, func): - self._prepare_func(func) + super(cached_property_with_ttl, self).__init__(func) return self def __get__(self, obj, cls): @@ -99,33 +112,16 @@ def __get__(self, obj, cls): return self now = time() - obj_dict = obj.__dict__ - name = self.__name__ - try: - value, last_updated = obj_dict[name] - except KeyError: - pass - else: - ttl_expired = self.ttl and self.ttl < now - last_updated - if not ttl_expired: + if obj in self.cache: + value, last_updated = self.cache[obj] + if not self.ttl or self.ttl > now - last_updated: return value - value = self.func(obj) - obj_dict[name] = (value, now) + value, _ = self.cache[obj] = (self.func(obj), now) return value - def __delete__(self, obj): - obj.__dict__.pop(self.__name__, None) - def __set__(self, obj, value): - obj.__dict__[self.__name__] = (value, time()) - - def _prepare_func(self, func): - self.func = func - if func: - self.__doc__ = func.__doc__ - self.__name__ = func.__name__ - self.__module__ = func.__module__ + super(cached_property_with_ttl, self).__set__(obj, (value, time())) # Aliases to make cached_property_with_ttl easier to use @@ -133,7 +129,9 @@ def _prepare_func(self, func): timed_cached_property = cached_property_with_ttl -class threaded_cached_property_with_ttl(cached_property_with_ttl): +class threaded_cached_property_with_ttl( + cached_property_with_ttl, threaded_cached_property +): """ A cached_property version for use in environments where multiple threads might concurrently try to access the property. @@ -147,6 +145,14 @@ def __get__(self, obj, cls): with self.lock: return super(threaded_cached_property_with_ttl, self).__get__(obj, cls) + def __set__(self, obj, value): + with self.lock: + return super(threaded_cached_property_with_ttl, self).__set__(obj, value) + + def __delete__(self, obj): + with self.lock: + return super(threaded_cached_property_with_ttl, self).__delete__(obj) + # Alias to make threaded_cached_property_with_ttl easier to use threaded_cached_property_ttl = threaded_cached_property_with_ttl diff --git a/property_cached/_version.txt b/property_cached/_version.txt new file mode 100644 index 0000000..9edc58b --- /dev/null +++ b/property_cached/_version.txt @@ -0,0 +1 @@ +1.6.4 diff --git a/requirements.txt b/requirements.txt deleted file mode 100644 index 1433eb3..0000000 --- a/requirements.txt +++ /dev/null @@ -1,7 +0,0 @@ -# Testing and deployment packages. -coverage==4.4.2 -pytest==3.8.2 -pytest-cov==2.6.0 -freezegun==0.3.10 -twine==1.12.1 -wheel==0.32.0 \ No newline at end of file diff --git a/setup.cfg b/setup.cfg index 0a8df87..8924192 100644 --- a/setup.cfg +++ b/setup.cfg @@ -1,2 +1,89 @@ -[wheel] -universal = 1 \ No newline at end of file +[metadata] +name = property-cached +version = file: property_cached/_version.txt +author = Daniel Greenfeld +author-email = pydanny@gmail.com +maintainer = Martin Larralde +maintainer-email = martin.larralde@ens-paris-saclay.fr +home-page = https://github.com/althonos/property-cached/ +description = A decorator for caching properties in classes (forked from cached-property). +long-description = file: README.rst, CHANGELOG.rst +license = BSD +license-file = LICENSE +platform = any +keywords = cached-property, cache, property +classifiers = + Development Status :: 5 - Production/Stable + Intended Audience :: Developers + License :: OSI Approved :: BSD License + Natural Language :: English + Operating System :: OS Independent + Programming Language :: Python + Programming Language :: Python :: 3 + Programming Language :: Python :: 3.5 + Programming Language :: Python :: 3.6 + Programming Language :: Python :: 3.7 + Programming Language :: Python :: 3.8 + +[options] +zip_safe = true +include_package_data = true +python_requires = >= 3.5 +packages = property_cached +test_suite = tests +setup_requires = + setuptools >=39.2 + +[bdist_wheel] +universal = 1 + +[check] +metadata = true +restructuredtext = true +strict = true + +[sdist] +formats = zip + +[coverage:report] +show_missing = true +exclude_lines = + pragma: no cover + if typing.TYPE_CHECKING: + @abc.abstractmethod + @abc.abstractproperty + raise NotImplementedError + return NotImplemented + +[green] +file-pattern = test_*.py +verbose = 2 +no-skip-report = true +quiet-stdout = true +run-coverage = true + +[pydocstyle] +match-dir = (?!tests)(?!resources)(?!docs)[^\.].* +match = (?!test)(?!setup)[^\._].*\.py +inherit = false +ignore = D200, D203, D213, D406, D407 # Google conventions + +[flake8] +max-line-length = 99 +doctests = True +exclude = .git, .eggs, __pycache__, tests/, docs/, build/, dist/ +ignore = D200, D203, D213, D406, D407 # Google conventions + +[mypy] +ignore_missing_imports = true + +[mypy-property_cached.*] +disallow_any_decorated = false +disallow_any_generics = false +disallow_any_unimported = true +disallow_subclassing_any = true +disallow_untyped_calls = false +disallow_untyped_defs = false +ignore_missing_imports = false +warn_unused_ignores = false +warn_return_any = false diff --git a/setup.py b/setup.py index af68a07..18d7a07 100755 --- a/setup.py +++ b/setup.py @@ -1,58 +1,5 @@ #!/usr/bin/env python # -*- coding: utf-8 -*- -import os -import sys -import codecs - -try: - from setuptools import setup -except ImportError: - from distutils.core import setup - -__version__ = "1.5.1" - - -def read(fname): - return codecs.open( - os.path.join(os.path.dirname(__file__), fname), "r", "utf-8" - ).read() - - -readme = read("README.rst") -history = read("HISTORY.rst").replace(".. :changelog:", "") - -if sys.argv[-1] == "publish": - os.system("python setup.py sdist bdist_wheel") - os.system("twine upload dist/*") - os.system("git tag -a %s -m 'version %s'" % (__version__, __version__)) - os.system("git push --tags") - sys.exit() - -setup( - name="cached-property", - version=__version__, - description="A decorator for caching properties in classes.", - long_description=readme + "\n\n" + history, - author="Daniel Greenfeld", - author_email="pydanny@gmail.com", - url="https://github.com/pydanny/cached-property", - py_modules=["cached_property"], - include_package_data=True, - license="BSD", - zip_safe=False, - keywords="cached-property", - classifiers=[ - "Development Status :: 5 - Production/Stable", - "Intended Audience :: Developers", - "License :: OSI Approved :: BSD License", - "Natural Language :: English", - "Programming Language :: Python :: 2", - "Programming Language :: Python :: 2.7", - "Programming Language :: Python :: 3", - "Programming Language :: Python :: 3.4", - "Programming Language :: Python :: 3.5", - "Programming Language :: Python :: 3.6", - "Programming Language :: Python :: 3.7", - ], -) +import setuptools +setuptools.setup() diff --git a/tests/requirements.txt b/tests/requirements.txt new file mode 100644 index 0000000..e0cadd9 --- /dev/null +++ b/tests/requirements.txt @@ -0,0 +1,7 @@ +# Testing and deployment packages. +coverage==5.1 +freezegun==0.3.10 +twine==1.12.1 +wheel==0.34.2 +green==3.0.0 +lxml==4.3.5 ; python_version=="3.4" diff --git a/tests/test_async_cached_property.py b/tests/test_async_cached_property.py index f4f93c7..1af139d 100644 --- a/tests/test_async_cached_property.py +++ b/tests/test_async_cached_property.py @@ -4,7 +4,7 @@ import unittest from threading import Lock, Thread from freezegun import freeze_time -import cached_property +import property_cached as cached_property def unittest_run_loop(f): diff --git a/tests/test_cached_property.py b/tests/test_cached_property.py index 5082416..8351807 100644 --- a/tests/test_cached_property.py +++ b/tests/test_cached_property.py @@ -1,11 +1,12 @@ # -*- coding: utf-8 -*- +import platform import time import unittest from threading import Lock, Thread from freezegun import freeze_time -import cached_property +import property_cached as cached_property def CheckFactory(cached_property_decorator, threadsafe=False): @@ -27,6 +28,8 @@ def add_control(self): @cached_property_decorator def add_cached(self): + """A cached adder. + """ if threadsafe: time.sleep(1) # Need to guard this since += isn't atomic. @@ -68,6 +71,12 @@ def assert_cached(self, check, expected): self.assertEqual(check.add_cached, expected) self.assertEqual(check.cached_total, expected) + def test_magic_attributes(self): + Check = CheckFactory(self.cached_property_factory) + self.assertEqual(Check.add_cached.__doc__.strip(), "A cached adder.") + self.assertEqual(Check.add_cached.__name__.strip(), "add_cached") + self.assertEqual(Check.add_cached.__module__, __name__) + def test_cached_property(self): Check = CheckFactory(self.cached_property_factory) check = Check() @@ -143,6 +152,37 @@ def test_threads(self): self.assert_cached(check, num_threads) self.assert_cached(check, num_threads) + @unittest.skipUnless(platform.python_implementation() == "CPython", + "unknow garbage collection mechanism") + def test_garbage_collection(self): + Check = CheckFactory(self.cached_property_factory) + check = Check() + check.add_cached = "foo" + + # check the instance is in the cache + self.assertIn(check, Check.add_cached.cache) + # remove the only reference to the Check instance + del check + # make sure the cache of the deleted object was removed + self.assertEqual(Check.add_cached.cache, {}) + + def test_object_independent(self): + Check = CheckFactory(self.cached_property_factory) + check1 = Check() + check2 = Check() + + self.assert_cached(check1, 1) + self.assert_cached(check1, 1) + self.assert_cached(check2, 1) + self.assert_cached(check2, 1) + + del check1.add_cached + + self.assert_cached(check1, 2) + self.assert_cached(check1, 2) + self.assert_cached(check2, 1) + self.assert_cached(check2, 1) + class TestThreadedCachedProperty(TestCachedProperty): """Tests for threaded_cached_property""" diff --git a/tests/test_coroutine_cached_property.py b/tests/test_coroutine_cached_property.py index 88790a0..40e443b 100644 --- a/tests/test_coroutine_cached_property.py +++ b/tests/test_coroutine_cached_property.py @@ -9,7 +9,7 @@ import asyncio from freezegun import freeze_time -import cached_property +import property_cached as cached_property def unittest_run_loop(f): diff --git a/tox.ini b/tox.ini deleted file mode 100644 index 9d7c8b3..0000000 --- a/tox.ini +++ /dev/null @@ -1,10 +0,0 @@ -[tox] -envlist = py27, py34, py35, py36, py37 - -[testenv] -setenv = - PYTHONPATH = {toxinidir}:{toxinidir}/cached-property -commands = pytest tests/ -deps = - pytest - freezegun