Skip to content

Commit

Permalink
remove CacheMeta-based caching (#784)
Browse files Browse the repository at this point in the history
This PR removes all uses of the `__cache__` mechanism, facilitated by
the `CacheMeta` meta class, and replaces it by the cached_property and
`lru_cache` decorators which are considered to give better visibility to
caching structures. The `CacheMeta` class is removed as no longer
relevant.
  • Loading branch information
gertjanvanzwieten committed Apr 7, 2023
2 parents c0f3b80 + f646e7e commit 038700b
Show file tree
Hide file tree
Showing 18 changed files with 290 additions and 892 deletions.
53 changes: 53 additions & 0 deletions nutils/_backports.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
"""
The backports module provides minimal fallback implementations for functions
that are introduced in versions of Python that are newer than the minimum
required version. Function behavour is equal to its Python counterpart only to
the extent that the Nutils code base requires it to be. As such,
implementations found in this module should not be relied upon as general
drop-on replacements.
"""

# Introduced in Python 3.8

try:
from functools import cached_property
except ImportError:

# Fallback implementation. Notable difference: no lock is used to prevent
# race conditions in multi-threaded contexts.

class cached_property:

def __init__(self, func):
self.func = func

def __set_name__(self, owner, name):
self.attrname = name

def __get__(self, instance, owner=None):
if instance is None:
return self
try:
val = instance.__dict__[self.attrname]
except KeyError:
val = instance.__dict__[self.attrname] = self.func(instance)
return val


try:
from math import comb
except ImportError:

# Fallback implementation. Notable difference: if k > n, this
# implementation raises a ValueError rather than returning 0.

import math, functools, operator

def comb(n, k):
a, b = sorted([k, n-k])
numer = functools.reduce(operator.mul, range(1+b, 1+n), 1)
denom = math.factorial(a)
return numer // denom


# vim:sw=4:sts=4:et
14 changes: 0 additions & 14 deletions nutils/_util.py
Original file line number Diff line number Diff line change
Expand Up @@ -384,20 +384,6 @@ def unique(items, key=None):
return unique, indices


try:
cached_property = functools.cached_property
except AttributeError: # python < 3.8
def cached_property(func): # minimal backport
@functools.wraps(func)
def wrapped(self):
try:
val = self.__dict__[func.__name__]
except KeyError:
self.__dict__[func.__name__] = val = func(self)
return val
return property(wrapped)


def defaults_from_env(f):
'''Decorator for changing function defaults based on environment.
Expand Down

0 comments on commit 038700b

Please sign in to comment.