Move lazy_property to util package.

This commit is contained in:
Simon Persson 2019-05-10 19:29:51 +02:00
parent 337b6bc4c9
commit 96d83ad1db
2 changed files with 25 additions and 18 deletions

View file

@ -24,14 +24,13 @@ import time
import re
import six
import string
import functools
from beets import logging
from beets.mediafile import MediaFile, UnreadableFileError
from beets import plugins
from beets import util
from beets.util import bytestring_path, syspath, normpath, samefile, \
MoveOperation
MoveOperation, lazy_property
from beets.util.functemplate import Template
from beets import dbcore
from beets.dbcore import types
@ -369,22 +368,6 @@ class LibModel(dbcore.Model):
return self.__str__().encode('utf-8')
def lazy_property(func):
field_name = '_' + func.__name__
@property
@functools.wraps(func)
def wrapper(self):
if hasattr(self, field_name):
return getattr(self, field_name)
value = func(self)
setattr(self, field_name, value)
return value
return wrapper
class FormattedItemMapping(dbcore.db.FormattedMapping):
"""Add lookup for album-level fields.

View file

@ -23,6 +23,7 @@ import locale
import re
import shutil
import fnmatch
import functools
from collections import Counter
from multiprocessing.pool import ThreadPool
import traceback
@ -1031,3 +1032,26 @@ def par_map(transform, items):
pool.map(transform, items)
pool.close()
pool.join()
def lazy_property(func):
"""A decorator that creates a lazily evaluated property. On first access,
the property is assigned the return value of `func`. This first value is
stored, so that future accesses do not have to evaluate `func` again.
This behaviour is useful when `func` is expensive to evaluate, and it is
not certain that the result will be needed.
"""
field_name = '_' + func.__name__
@property
@functools.wraps(func)
def wrapper(self):
if hasattr(self, field_name):
return getattr(self, field_name)
value = func(self)
setattr(self, field_name, value)
return value
return wrapper