felix-andreas / apace

Another Particle Accelerator Code
https://apace.readthedocs.io
GNU General Public License v3.0
7 stars 1 forks source link

Python 3.8: Cached property #67

Open felix-andreas opened 4 years ago

felix-andreas commented 4 years ago

Python 3.8 now has a functools.cached_property

from functools import cached_property

class Foo:
    def __init__(self):
        self._x = 0

    @cached_property
    def x(self):
        print("Increment x!")
        return self._x

Create a new foo:

>>> foo = Foo()
>>> foo.x
Increment x!
1
>>> foo.x
1

The cache can be invalidated with:

>>> del foo.x
>>> foo.x
Increment x!
2
felix-andreas commented 4 years ago

TODO: Write minimal example with numpy array. Is it possible to avoid reallocating the array every time the cache is invalidated??