Skip to content
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
39 changes: 13 additions & 26 deletions isimip_utils/utils.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
"""Additional utility functions for ISIMIP tools."""
from collections.abc import Callable
import warnings
from functools import cached_property as _cached_property
from pathlib import Path
from typing import Any, Literal

Expand All @@ -21,32 +22,18 @@ def __new__(cls) -> 'Singleton':
return cls._instance


class cached_property:
"""Decorator that converts a method into a cached property.
class cached_property(_cached_property):
def __init_subclass__(cls, **kwargs):
super().__init_subclass__(**kwargs)

The property value is computed once and then cached as an instance attribute.
Subsequent accesses return the cached value without re-computing.

Simplified version of
[Django's cached_property](https://github.com/django/django/blob/main/django/utils/functional.py).
"""

name: str | None = None

def __init__(self, func: Callable) -> None:
self.func = func

def __set_name__(self, owner: type, name: str) -> None:
if self.name is None:
self.name = name
else:
raise TypeError("Cannot assign the same cached_property to two different names")

def __get__(self, instance: Any, cls: type | None = None) -> Any:
if instance is None:
return self
value = instance.__dict__[self.name] = self.func(instance)
return value
def __get__(self, instance, cls=None):
warnings.warn(
'isimip-utils.utils.cached_property is deprecated and will be removed in 2.1.0, '
'use functools.cached_property instead.',
DeprecationWarning,
stacklevel=2,
)
return super().__get__(instance, cls)


def exclude_path(exclude: list[str] | None, path: Path | str, match: Literal['any', 'all'] = 'any') -> bool:
Expand Down
Loading