Skip to content

Instantly share code, notes, and snippets.

@mrtj
Created May 13, 2022 21:10
Show Gist options
  • Select an option

  • Save mrtj/0e64599ff1245a81d2c0a80c4337b261 to your computer and use it in GitHub Desktop.

Select an option

Save mrtj/0e64599ff1245a81d2c0a80c4337b261 to your computer and use it in GitHub Desktop.

Revisions

  1. mrtj created this gist May 13, 2022.
    29 changes: 29 additions & 0 deletions lazy_property.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,29 @@
    import functools

    def lazy_property(func):
    ''' Caches the return value of a function, and turns it into a property.
    Intended to be used as a function decorator::
    >>> class Foo:
    >>> @lazy_property
    >>> def bar(self):
    >>> print('expensive calculation')
    >>> return 'bar'
    >>> foo = Foo()
    >>> foo.bar()
    expensive calculation
    'bar'
    >>> foo.bar()
    'bar'
    '''
    attrib_name = '_' + func.__name__
    @property
    @functools.wraps(func)
    def lazy_wrapper(instance, *args, **kwargs):
    if hasattr(instance, attrib_name):
    return getattr(instance, attrib_name)
    value = func(instance, *args, **kwargs)
    object.__setattr__(instance, attrib_name, value)
    return value
    return lazy_wrapper