Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[issue #123] decorated property with new name support #124

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
20 changes: 15 additions & 5 deletions cached_property.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,10 @@ class cached_property(object):
def __init__(self, func):
self.__doc__ = getattr(func, "__doc__")
self.func = func
self.name = func.__name__

def __set_name__(self, owner, name):
self.name = name

def __get__(self, obj, cls):
if obj is None:
Expand All @@ -32,15 +36,15 @@ 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 = obj.__dict__[self.name] = self.func(obj)
return value

def _wrap_in_coroutine(self, obj):

@asyncio.coroutine
def wrapper():
future = asyncio.ensure_future(self.func(obj))
obj.__dict__[self.func.__name__] = future
obj.__dict__[self.name] = future
return future

return wrapper()
Expand All @@ -56,21 +60,24 @@ def __init__(self, func):
self.__doc__ = getattr(func, "__doc__")
self.func = func
self.lock = threading.RLock()
self.name = func.__name__

def __set_name__(self, owner, name):
self.name = name

def __get__(self, obj, cls):
if obj is None:
return self

obj_dict = obj.__dict__
name = self.func.__name__
with self.lock:
try:
# check if the value was computed before the lock was acquired
return obj_dict[name]
return obj_dict[self.name]

except KeyError:
# if not, do the calculation and release the lock
return obj_dict.setdefault(name, self.func(obj))
return obj_dict.setdefault(self.name, self.func(obj))


class cached_property_with_ttl(object):
Expand All @@ -89,6 +96,9 @@ def __init__(self, ttl=None):
self.ttl = ttl
self._prepare_func(func)

def __set_name__(self, owner, name):
self.__name__ = name

def __call__(self, func):
self._prepare_func(func)
return self
Expand Down
39 changes: 28 additions & 11 deletions tests/test_cached_property.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
# -*- coding: utf-8 -*-

import sys
import time
import unittest
from threading import Lock, Thread
Expand All @@ -8,12 +9,23 @@
import cached_property


def CheckFactory(cached_property_decorator, threadsafe=False):
def CheckFactory(cached_property_decorator, threadsafe=False, change_name=False):
"""
Create dynamically a Check class whose add_cached method is decorated by
the cached_property_decorator.
"""

def add_cached_func(self):
if threadsafe:
time.sleep(1)
# Need to guard this since += isn't atomic.
with self.lock:
self.cached_total += 1
else:
self.cached_total += 1

return self.cached_total

class Check(object):

def __init__(self):
Expand All @@ -26,17 +38,15 @@ def add_control(self):
self.control_total += 1
return self.control_total

@cached_property_decorator
def add_cached(self):
if threadsafe:
time.sleep(1)
# Need to guard this since += isn't atomic.
with self.lock:
self.cached_total += 1
else:
self.cached_total += 1
if change_name:
def add_cached_orig(self):
return add_cached_func(self)

return self.cached_total
add_cached = cached_property_decorator(add_cached_orig)
else:
@cached_property_decorator
def add_cached(self):
return add_cached_func(self)

def run_threads(self, num_threads):
threads = []
Expand Down Expand Up @@ -124,6 +134,13 @@ def test_set_cached_property(self):
self.assertEqual(check.add_cached, "foo")
self.assertEqual(check.cached_total, 0)

@unittest.skipUnless(sys.version_info >= (3, 6), 'No __set_name__ support until Python 3.6')
def test_cached_property_change_name(self):
Check = CheckFactory(self.cached_property_factory, change_name=True)
check = Check()
self.assertEqual(check.add_cached, 1)
self.assertEqual(check.add_cached_orig(), 2)

def test_threads(self):
Check = CheckFactory(self.cached_property_factory, threadsafe=True)
check = Check()
Expand Down