Browse Source

add 'cached_property' example & requirements

master
Julian 4 months ago
parent
commit
f9f413c00c
2 changed files with 59 additions and 0 deletions
  1. +1
    -0
      requirements.txt
  2. +58
    -0
      scripts/property.py

+ 1
- 0
requirements.txt View File

@@ -0,0 +1 @@
cached_property==1.5.1

+ 58
- 0
scripts/property.py View File

@@ -0,0 +1,58 @@
from time import sleep

from cached_property import cached_property, cached_property_with_ttl


class Uncached(object):

def __init__(self):
self.number = 0

@property
def gimme_number(self):
self.number += 1
return self.number


class Cached(Uncached):

@cached_property
def gimme_number(self):
self.number += 1
return self.number


TTL = 2


class CachedWithTtl(Uncached):

@cached_property_with_ttl(ttl=TTL)
def gimme_number(self):
self.number += 1
return self.number


def loop(thing, iterations=5):
for _ in range(iterations):
print(thing.gimme_number)
sleep(1)

return thing


if __name__ == '__main__':

print('uncached property:')
loop(Uncached())

print('cached property:')
loop(Cached())

print('cached property, cache deletion after 3rd iteration:')
cached = loop(Cached(), 3)
del cached.__dict__['gimme_number']
cached = loop(cached, 2)

print(f'cached property with ttl of {TTL} seconds:')
loop(CachedWithTtl())

Loading…
Cancel
Save