Skip to content

Commit

Permalink
Move lazyprop decorator to the utils module
Browse files Browse the repository at this point in the history
  • Loading branch information
scriptator authored and Sebastian Böck committed May 19, 2017
1 parent e9240e3 commit 78aa1f8
Show file tree
Hide file tree
Showing 2 changed files with 30 additions and 14 deletions.
15 changes: 1 addition & 14 deletions madmom/audio/cepstrogram.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
from .filters import MelFilterbank
from .spectrogram import Spectrogram
from ..processors import Processor
from ..utils import lazyprop


class Cepstrogram(np.ndarray):
Expand All @@ -37,7 +38,6 @@ class applies some transformation (usually a DCT) on a spectrogram.
one is instantiated with these additional keyword arguments.
"""

# pylint: disable=super-on-old-class
# pylint: disable=super-init-not-called
# pylint: disable=attribute-defined-outside-init
Expand Down Expand Up @@ -130,19 +130,6 @@ def process(self, data, **kwargs):
MFCC_DELTADELTA_FILTER = np.linspace(1, -1, 3) / 2


# https://stackoverflow.com/questions/3012421/python-memoising-deferred-lookup-property-decorator#3013910
def lazyprop(fn):
attr_name = '_lazy_' + fn.__name__

@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)

return _lazyprop


class MFCC(Cepstrogram):
"""
MFCC class.
Expand Down
29 changes: 29 additions & 0 deletions madmom/utils/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -591,6 +591,35 @@ def segment_axis(signal, frame_size, hop_size, axis=None, end='cut',
dtype=signal.dtype)


# taken from: https://stackoverflow.com/questions/3012421/
def lazyprop(fn):
"""
A decorator for a caching, lazily evaluated property. If a function is
decorated with @lazyprop, the original function of the resulting property
is only called on the first access. Afterwards the result which was
produced then is returned again.
Parameters
----------
fn: Function
A function without argument which returns the value of the property
Returns
-------
property
A property which wraps the original one and caches it first result
"""
attr_name = '_lazy_' + fn.__name__

@property
def _lazyprop(self):
if not hasattr(self, attr_name):
setattr(self, attr_name, fn(self))
return getattr(self, attr_name)

return _lazyprop


# keep namespace clean
del contextlib

Expand Down

0 comments on commit 78aa1f8

Please sign in to comment.