Skip to content

Commit

Permalink
grc: Improve documentation of _lazy.py
Browse files Browse the repository at this point in the history
Signed-off-by: Martin Braun <[email protected]>
  • Loading branch information
mbr0wn committed Dec 19, 2023
1 parent e85a3bb commit 241a475
Showing 1 changed file with 34 additions and 4 deletions.
38 changes: 34 additions & 4 deletions grc/core/utils/descriptors/_lazy.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,38 @@
#
# SPDX-License-Identifier: GPL-2.0-or-later
#
"""
Class method decorators.
"""

import functools


class lazy_property(object):
# pylint: disable=too-few-public-methods,invalid-name
class lazy_property:
"""
Class method decorator, similar to @property. This causes a method that is
declared as @lazy_property to be evaluated once, the first time it is called.
Subsequent calls to this property will always return the cached value.
Careful! Not suitable for properties that change at runtime.
Example:
>>> class Foo:
... def __init__(self):
... self.x = 5
...
... @lazy_property
... def xyz(self):
... return complicated_slow_function(self.x)
...
...
>>> f = Foo()
>>> print(f.xyz) # Will give the result, but takes long to compute
>>> print(f.xyz) # Blazing fast!
>>> f.x = 7 # Careful! f.xyz will not be updated any more!
>>> print(f.xyz) # Blazing fast, but returns the same value as before.
"""

def __init__(self, func):
self.func = func
Expand All @@ -19,11 +46,14 @@ def __get__(self, instance, owner):
value = self.func(instance)
setattr(instance, self.func.__name__, value)
return value

# pylint: enable=too-few-public-methods,invalid-name

def nop_write(prop):
"""Make this a property with a nop setter"""
"""
Make this a property with a nop setter
Effectively, makes a property read-only, with no error on write.
"""
def nop(self, value):
pass
return prop.setter(nop)

0 comments on commit 241a475

Please sign in to comment.