def FieldForeign(i, cls):
    def f(self):
        raw = self._get_raw_foreign_field(i)
        print('pos', i, 'raw', raw)
        return cls.from_foreign(raw)

    return cached_property(f)
Exemple #2
0
def dynamic(get: Callable[[K], T_co]) -> cached_property[T_co]:

    def __get__(self: K) -> T_co:
        assert isinstance(self, Konfig), f"object {self} must be subclass of `Konfig` class"
        return get(self)

    return cached_property(get)
Exemple #3
0
def make_prop(parent, cls, field):
    def _property(self):
        return getattr(getattr(self, parent), field)

    prop = cached_property(_property)
    prop.__set_name__(cls, field)
    return prop
Exemple #4
0
    def _cached_property(func):
        try:
            from functools import cached_property

            return cached_property(func)
        except ImportError:
            from functools import lru_cache

            return property(lru_cache(maxsize=None)(func))
Exemple #5
0
    def __new__(meta, name, bases, dct):
        # only for subclasses, not for Cell class
        if bases:
            for k, v in dct.items():
                if (not k.startswith('_') and inspect.isfunction(v)
                        and not hasattr(v, '_fragment')
                        and len(inspect.signature(v).parameters) == 1):
                    # turn functions with single argument (self) into cached properties
                    dct[k] = cached_property(v)

        return super().__new__(meta, name, bases, dct)
        class Class:
            @cached_property
            def value(self):
                """Here is the docstring..."""
                return 1, object()

            @cached_property
            def __foo__(self):
                """Here is the docstring..."""
                return 1, object()

            def other_value(self):
                """Here is the docstring..."""
                return 1, object()

            other = cached_property(other_value, name='other')
Exemple #7
0
    def register(
        cls,
        model: tp.Type[ModelType],
        repository: tp.Type[RepositoryType],
        name: tp.Optional[str] = None,
        *args: tp.Any,
        **kwargs: tp.Any,
    ) -> None:
        """Registers a storage repository with this unit of work.

        Parameters
        ----------
        model : ModelType
            The model class to register with this unit of work class.
        repository : RepositoryType
            The repository class to use to manage the CRUD operations
            for the given `model`.
        name : str, optional
            The name to register the repository (and access it) with on
            this unit of work.

        Raises
        ------
        ValueError
            If the given `model` is already registered with this class,
            or if the name for the repository is not a valid name.

        """
        if model in cls.__models:
            raise ValueError(f"Model already registered: {model}")
        name = name or camel_to_snake(model.__name__)
        if hasattr(cls, name):
            raise ValueError(f"Class already has attribute: {name}")
        elif not name.isidentifier():
            raise ValueError(f"Invalid attribute name: {name}")

        # - Create and attach property
        get_fn = cls._repo_getter(model, repository, name, *args, **kwargs)
        repo_prop = cached_property(get_fn)
        setattr(cls, name, repo_prop)
        repo_prop.__set_name__(cls, name)

        # - Register ModelType meta
        cls.__models.add(model)
    def __init__(self, func):
        self.__doc__ = getattr(func, '__doc__')
        self.func = func

    def __get__(self, instance, cls):
        if instance is None:
            return self
        else:
            value = instance.__dict__[self.func.__name__] = self.func(instance)
            return value

class D:
    def __init__(self, greeting='Hello'):
        self.greeting = greeting

def greet(self):
    return self.greeting + " world!"


# Beazley's version works...
D.greet = lazyprop(greet)
assert D().greet == "Hello world!"

# ... but the builtin version will fail
D.greet = cached_property(greet)
# D().greet  # this will fail

D.greet = cached_property(greet)
D.greet.__set_name__(D, 'greet')  # sets D.greet.attrname = "greet" for later use

assert D().greet == "hello world!"
Exemple #9
0
def nozip_gallery_file(album, settings=None):
    """Filesystem based switch to disable ZIP generation for an Album"""
    Album.zip = cached_property(generate_album_zip)
    Album.zip.__set_name__(Album, 'zip')
Exemple #10
0
            yield AlbumDir(path.parent)


def iter_albums_or_files(paths: Paths) -> Iterator[Union[AlbumDir, SongFile]]:
    for path in iter_paths(paths):
        if path.is_dir():
            for root, dirs, files in os.walk(
                    path.as_posix()):  # as_posix for 3.5 compatibility
                if files and not dirs:
                    yield AlbumDir(root)
        elif path.is_file():
            yield SongFile(path)


def _album_dir_obj(self):
    if self._album_dir is not None:
        return self._album_dir
    try:
        return AlbumDir(self.path.parent)
    except InvalidAlbumDir:
        pass
    return None


# Note: The only time this property is not available is in interactive sessions started for the files.track.base module
SongFile.album_dir_obj = cached_property(_album_dir_obj)

if __name__ == '__main__':
    from .patches import apply_mutagen_patches
    apply_mutagen_patches()
"""Backport of python 3.8 functools.cached_property.

cached_property() - computed once per instance, cached as attribute
"""

__all__ = ("cached_property",)

# Standard Library
from sys import version_info

if version_info >= (3, 8):
    # Standard Library
    from functools import cached_property  # pylint: disable=no-name-in-module
else:
    # Standard Library
    from threading import RLock
    from typing import Any
    from typing import Callable
    from typing import Optional
    from typing import Type
    from typing import TypeVar

    _NOT_FOUND = object()
    _T = TypeVar("_T")
    _S = TypeVar("_S")

    # noinspection PyPep8Naming
    class cached_property:  # NOSONAR  # pylint: disable=invalid-name  # noqa: N801
        """Cached property implementation.
Exemple #12
0
 def cached_property_e(expression):
     return cached_property(e(expression))
Exemple #13
0
def FieldForeignDirect(i, constructor):
    def f(self):
        raw = self._get_raw_direct_foreign_field(i)
        return constructor(raw)

    return cached_property(f)