https://github.com/althonos/property-cached

A (better) decorator for caching properties in classes (forked from cached-property).

https://github.com/althonos/property-cached

Science Score: 10.0%

This score indicates how likely this project is to be science-related based on various indicators:

  • CITATION.cff file
  • codemeta.json file
  • .zenodo.json file
  • DOI references
  • Academic publication links
  • Committers with academic emails
    2 of 26 committers (7.7%) from academic institutions
  • Institutional organization owner
  • JOSS paper metadata
  • Scientific vocabulary similarity
    Low similarity (9.4%) to scientific vocabulary

Keywords

cache fork property python python-library

Keywords from Contributors

pallets unit-testing parsing json-schema notebooks asyncio pypi documentation-tool bioinformatics static-analysis
Last synced: 5 months ago · JSON representation

Repository

A (better) decorator for caching properties in classes (forked from cached-property).

Basic Info
Statistics
  • Stars: 6
  • Watchers: 3
  • Forks: 2
  • Open Issues: 16
  • Releases: 0
Fork of pydanny/cached-property
Topics
cache fork property python python-library
Created about 7 years ago · Last pushed almost 3 years ago
Metadata Files
Readme Changelog Contributing License

README.rst

===============================
property-cached
===============================

.. 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/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

.. 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.

How to use it
--------------

Let's define a class with an expensive property. Every time you stay there the
price goes up by $50!

.. code-block:: python

    class Monopoly(object):

        def __init__(self):
            self.boardwalk_price = 500

        @property
        def boardwalk(self):
            # In reality, this might represent a database call or time
            # intensive task like calling a third-party API.
            self.boardwalk_price += 50
            return self.boardwalk_price

Now run it:

.. code-block:: python

    >>> monopoly = Monopoly()
    >>> monopoly.boardwalk
    550
    >>> monopoly.boardwalk
    600

Let's convert the boardwalk property into a ``cached_property``.

.. code-block:: python

    from cached_property import cached_property

    class Monopoly(object):

        def __init__(self):
            self.boardwalk_price = 500

        @cached_property
        def boardwalk(self):
            # Again, this is a silly example. Don't worry about it, this is
            #   just an example for clarity.
            self.boardwalk_price += 50
            return self.boardwalk_price

Now when we run it the price stays at $550.

.. code-block:: python

    >>> monopoly = Monopoly()
    >>> monopoly.boardwalk
    550
    >>> monopoly.boardwalk
    550
    >>> monopoly.boardwalk
    550

Why doesn't the value of ``monopoly.boardwalk`` change? Because it's a **cached property**!

Invalidating the Cache
----------------------

Results of cached functions can be invalidated by outside forces. Let's demonstrate how to force the cache to invalidate:

.. code-block:: python

    >>> monopoly = Monopoly()
    >>> monopoly.boardwalk
    550
    >>> monopoly.boardwalk
    550
    >>> # invalidate the cache
    >>> del monopoly.__dict__['boardwalk']
    >>> # request the boardwalk property again
    >>> monopoly.boardwalk
    600
    >>> monopoly.boardwalk
    600

Working with Threads
---------------------

What if a whole bunch of people want to stay at Boardwalk all at once? This means using threads, which
unfortunately causes problems with the standard ``cached_property``. In this case, switch to using the
``threaded_cached_property``:

.. code-block:: python

    from cached_property import threaded_cached_property

    class Monopoly(object):

        def __init__(self):
            self.boardwalk_price = 500

        @threaded_cached_property
        def boardwalk(self):
            """threaded_cached_property is really nice for when no one waits
                for other people to finish their turn and rudely start rolling
                dice and moving their pieces."""

            sleep(1)
            self.boardwalk_price += 50
            return self.boardwalk_price

Now use it:

.. code-block:: python

    >>> from threading import Thread
    >>> from monopoly import Monopoly
    >>> monopoly = Monopoly()
    >>> threads = []
    >>> for x in range(10):
    >>>     thread = Thread(target=lambda: monopoly.boardwalk)
    >>>     thread.start()
    >>>     threads.append(thread)

    >>> for thread in threads:
    >>>     thread.join()

    >>> self.assertEqual(m.boardwalk, 550)


Working with async/await (Python 3.5+)
--------------------------------------

The cached property can be async, in which case you have to use await
as usual to get the value. Because of the caching, the value is only
computed once and then cached:

.. code-block:: python

    from cached_property import cached_property

    class Monopoly(object):

        def __init__(self):
            self.boardwalk_price = 500

        @cached_property
        async def boardwalk(self):
            self.boardwalk_price += 50
            return self.boardwalk_price

Now use it:

.. code-block:: python

    >>> async def print_boardwalk():
    ...     monopoly = Monopoly()
    ...     print(await monopoly.boardwalk)
    ...     print(await monopoly.boardwalk)
    ...     print(await monopoly.boardwalk)
    >>> import asyncio
    >>> asyncio.get_event_loop().run_until_complete(print_boardwalk())
    550
    550
    550

Note that this does not work with threading either, most asyncio
objects are not thread-safe. And if you run separate event loops in
each thread, the cached version will most likely have the wrong event
loop. To summarize, either use cooperative multitasking (event loop)
or threading, but not both at the same time.


Timing out the cache
--------------------

Sometimes you want the price of things to reset after a time. Use the ``ttl``
versions of ``cached_property`` and ``threaded_cached_property``.

.. code-block:: python

    import random
    from cached_property import cached_property_with_ttl

    class Monopoly(object):

        @cached_property_with_ttl(ttl=5) # cache invalidates after 5 seconds
        def dice(self):
            # I dare the reader to implement a game using this method of 'rolling dice'.
            return random.randint(2,12)

Now use it:

.. code-block:: python

    >>> monopoly = Monopoly()
    >>> monopoly.dice
    10
    >>> monopoly.dice
    10
    >>> from time import sleep
    >>> sleep(6) # Sleeps long enough to expire the cache
    >>> monopoly.dice
    3
    >>> monopoly.dice
    3

**Note:** The ``ttl`` tools do not reliably allow the clearing of the cache. This
is why they are broken out into seperate tools. See https://github.com/pydanny/cached-property/issues/16.

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.
* ``@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

Owner

  • Name: Martin Larralde
  • Login: althonos
  • Kind: user
  • Location: Heidelberg, Germany
  • Company: EMBL / LUMC, @zellerlab

PhD candidate in Bioinformatics, passionate about programming, SIMD-enthusiast, Pythonista, Rustacean. I write poems, and sometimes they are executable.

GitHub Events

Total
Last Year

Committers

Last synced: almost 3 years ago

All Time
  • Total Commits: 169
  • Total Committers: 26
  • Avg Commits per committer: 6.5
  • Development Distribution Score (DDS): 0.763
Past Year
  • Commits: 0
  • Committers: 0
  • Avg Commits per committer: 0.0
  • Development Distribution Score (DDS): 0.0
Top Committers
Name Email Commits
Daniel Greenfeld p****y@g****m 40
Daniel Greenfeld p****y@u****m 28
pyup-bot g****t@p****o 19
Martin Larralde m****e@e****r 15
Martin Larralde m****e@e****r 12
Daniel d****d@b****m 11
George Sakkis g****s@g****m 10
dependabot-preview[bot] 2****]@u****m 5
Audrey Roy Greenfeld a****y@a****u 4
Daniel Greenfeld d****y@e****m 4
hbc b****x@g****m 3
Ionel Cristian Mărieș c****t@i****o 2
Tin Tvrtkovic t****r@g****m 2
robert-cody r****y@m****u 2
Darian Moody m****l@d****k 1
Ademola s****s@g****m 1
Greg Back 1****k@u****m 1
Artem Malyshev p****4@g****m 1
Robert Schütz r****7@g****m 1
Fabio C. Barrioneuvo da Luz f****z@b****m 1
Volker Braun v****e@g****m 1
Mathias Behrle m****b@m****z 1
Adam Williamson a****m@r****m 1
Sean Aubin s****n@g****m 1
Anthony Sottile a****e@u****u 1
William Martin Stewart z****l@g****m 1

Issues and Pull Requests

Last synced: 7 months ago

All Time
  • Total issues: 0
  • Total pull requests: 177
  • Average time to close issues: N/A
  • Average time to close pull requests: about 2 months
  • Total issue authors: 0
  • Total pull request authors: 4
  • Average comments per issue: 0
  • Average comments per pull request: 1.25
  • Merged pull requests: 7
  • Bot issues: 0
  • Bot pull requests: 174
Past Year
  • Issues: 0
  • Pull requests: 1
  • Average time to close issues: N/A
  • Average time to close pull requests: N/A
  • Issue authors: 0
  • Pull request authors: 1
  • Average comments per issue: 0
  • Average comments per pull request: 0.0
  • Merged pull requests: 0
  • Bot issues: 0
  • Bot pull requests: 0
Top Authors
Issue Authors
Pull Request Authors
  • dependabot[bot] (55)
  • dependabot-preview[bot] (44)
  • nicolas-graves (1)
  • Seanny123 (1)
Top Labels
Issue Labels
Pull Request Labels
dependencies (99) security (2) enhancement (1)

Packages

  • Total packages: 3
  • Total downloads:
    • pypi 308,527 last-month
  • Total docker downloads: 1,063
  • Total dependent packages: 10
    (may contain duplicates)
  • Total dependent repositories: 178
    (may contain duplicates)
  • Total versions: 8
  • Total maintainers: 1
pypi.org: property-cached

A decorator for caching properties in classes (forked from cached-property).

  • Versions: 5
  • Dependent Packages: 6
  • Dependent Repositories: 176
  • Downloads: 308,527 Last month
  • Docker Downloads: 1,063
Rankings
Downloads: 0.6%
Dependent repos count: 1.2%
Dependent packages count: 1.6%
Docker downloads count: 2.3%
Average: 8.1%
Stargazers count: 20.3%
Forks count: 22.6%
Maintainers (1)
Last synced: 6 months ago
conda-forge.org: property-cached
  • Versions: 2
  • Dependent Packages: 3
  • Dependent Repositories: 1
Rankings
Dependent packages count: 15.6%
Dependent repos count: 24.3%
Average: 40.2%
Stargazers count: 58.4%
Forks count: 62.3%
Last synced: 6 months ago
conda-forge.org: property_cached
  • Versions: 1
  • Dependent Packages: 1
  • Dependent Repositories: 1
Rankings
Dependent repos count: 24.3%
Dependent packages count: 29.0%
Average: 43.5%
Stargazers count: 58.3%
Forks count: 62.3%
Last synced: 6 months ago

Dependencies

tests/requirements.txt pypi
  • coverage ==5.1 test
  • freezegun ==0.3.10 test
  • green ==3.0.0 test
  • lxml ==4.3.5 test
  • twine ==1.12.1 test
  • wheel ==0.34.2 test