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

Fixed #19872 #812

Merged
merged 1 commit into from Feb 23, 2013
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
4 changes: 3 additions & 1 deletion django/utils/functional.py
Expand Up @@ -39,7 +39,9 @@ class cached_property(object):
def __init__(self, func):
self.func = func

def __get__(self, instance, type):
def __get__(self, instance, type=None):
if instance is None:
return self
res = instance.__dict__[self.func.__name__] = self.func(instance)
return res

Expand Down
29 changes: 28 additions & 1 deletion tests/regressiontests/utils/functional.py
@@ -1,5 +1,5 @@
from django.utils import unittest
from django.utils.functional import lazy, lazy_property
from django.utils.functional import lazy, lazy_property, cached_property


class FunctionalTestCase(unittest.TestCase):
Expand Down Expand Up @@ -37,3 +37,30 @@ def _get_do(self):

self.assertRaises(NotImplementedError, lambda: A().do)
self.assertEqual(B().do, 'DO IT')

def test_cached_property(self):
"""
Test that cached_property caches its value,
and that it behaves like a property
"""

class A(object):

@cached_property
def value(self):
return 1, object()

a = A()

# check that it is cached
self.assertEqual(a.value, a.value)

# check that it returns the right thing
self.assertEqual(a.value[0], 1)

# check that state isn't shared between instances
a2 = A()
self.assertNotEqual(a.value, a2.value)

# check that it behaves like a property when there's no instance
self.assertIsInstance(A.value, cached_property)