Add decorator django.utils.functional.cached_classproperty

173 views
Skip to first unread message

Boris Krause

unread,
Dec 30, 2020, 9:47:03 AM12/30/20
to Django developers (Contributions to Django itself)
Hello,
I propose new feature - decorator cached_classproperty.
Django has a lot of methods for caching, like cached_page and cached_property.
Сaching improves response times.
For me it was useful.
What do you think about it?
Thanks!:)

Tom Forbes

unread,
Dec 30, 2020, 10:10:58 AM12/30/20
to django-d...@googlegroups.com
I’m slightly skeptical - a cached class property seems slightly iffy and could be achieved with just a @functools.cache’d classmethod instead? 

Is there a specific use case where a cached, class _property_ would be the best way? And perhaps we need to care about concurrent access here, more than with our other cache implementations.

However, this is a really small change, so maybe it’s OK.

Tom

On 30 Dec 2020, at 14:46, Boris Krause <mgbi...@gmail.com> wrote:

Hello,
--
You received this message because you are subscribed to the Google Groups "Django developers (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-develop...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-developers/fe13f5c9-8ef5-44eb-bfc4-731865a9123an%40googlegroups.com.

Adam Johnson

unread,
Dec 30, 2020, 1:43:11 PM12/30/20
to django-d...@googlegroups.com
There's no need for such a decorator - a class-level cached property can already be achieved with @classproperty and @lru_cache:

In [1]: from functools import lru_cache

In [2]: from django.utils.functional import classproperty

In [3]: class Thing:
   ...:     @classproperty
   ...:     @lru_cache(maxsize=1)
   ...:     def coefficient(cls):
   ...:         return 3.14
   ...:

In [4]: Thing.coefficient
Out[4]: 3.14

That said if I saw this in code I'd normally move it out into a standalone @lru_cache function - I don't see the need for it to be in a class, ad the caching behaviour often hides a potentially-expensive first operatio.



--
Adam
Reply all
Reply to author
Forward
0 new messages