Created
June 27, 2018 13:56
-
-
Save laixintao/f1114d964c19679c973c2c3c3f1fa8ba to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# -*- coding: utf-8 -*- | |
import time | |
# copy out from django | |
# https://docs.djangoproject.com/zh-hans/2.0/_modules/django/utils/functional/#cached_property | |
class cached_property: | |
""" | |
Decorator that converts a method with a single self argument into a | |
property cached on the instance. | |
Optional ``name`` argument allows you to make cached properties of other | |
methods. (e.g. url = cached_property(get_absolute_url, name='url') ) | |
""" | |
def __init__(self, func, name=None): | |
self.func = func | |
self.__doc__ = getattr(func, "__doc__") | |
self.name = name or func.__name__ | |
def __get__(self, instance, cls=None): | |
""" | |
Call the function and put the return value in instance.__dict__ so that | |
subsequent attribute access on the instance returns the cached value | |
instead of calling cached_property.__get__(). | |
""" | |
if instance is None: | |
return self | |
res = instance.__dict__[self.name] = self.func(instance) | |
return res | |
class Foo: | |
@cached_property | |
def foo(self): | |
return time.time() | |
print(dir(Foo)) | |
print(type(Foo.foo)) | |
f = Foo() | |
print(f.foo) | |
time.sleep(0.03) | |
print(f.foo) |
Author
laixintao
commented
Jun 27, 2018
Some related post:
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment