Implement decorator to lazy initialise a property

This commit is contained in:
Kristóf Tóth 2018-06-01 13:58:50 +02:00
parent e98c41d3cf
commit 06c2fc97ad
2 changed files with 20 additions and 0 deletions

View File

@ -2,3 +2,4 @@
# All Rights Reserved. See LICENSE file for details. # All Rights Reserved. See LICENSE file for details.
from .rate_limiter import RateLimiter from .rate_limiter import RateLimiter
from .lazy_initialise import LazyInitialise

View File

@ -0,0 +1,19 @@
# Copyright (C) 2018 Avatao.com Innovative Learning Kft.
# All Rights Reserved. See LICENSE file for details.
class LazyInitialise:
"""
Decorator that replaces a function with the value
it calculates on the first call.
"""
def __init__(self, func):
self.func = func
self.__doc__ = func.__doc__
def __get__(self, instance, owner):
if instance is None:
raise TypeError('Cannot get object property from class!')
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value