forked from datalad/datalad-core
Previously, if a `Flyweighted` subclass constructor would somehow alter the given representative path, the flyweight would not catch this, even if to instances alter the path to the exact same value. This change adjust the flyweight logic by double-checking against an instances `.path` property after creation, and return any existing instance matching that path, before keeping a new instance around. I added a TODO, because I suspect this could be done cleaner, by moving the path resolution to an earlier stage. I could not immediately figure this out. It would still need to be subclass specific. I believe, however, that doing this in this particular fashion is not too bad performance-wise, and the complexity of adding this feature is certainly minimal in the current form.
101 lines
4.4 KiB
Python
101 lines
4.4 KiB
Python
import threading
|
|
from abc import abstractmethod
|
|
from pathlib import Path
|
|
|
|
|
|
class PathBasedFlyweight(type):
|
|
"""Metaclass for a path-based flyweight pattern
|
|
|
|
See `https://en.wikipedia.org/wiki/Flyweight_pattern`_ for information
|
|
on the pattern.
|
|
|
|
There is a companion class :class:`Flyweighted`, which can be used as
|
|
a base class for classes implementing this pattern.
|
|
|
|
This implementation integrates the "factory" into the actual classes.
|
|
Consuming code generally need not be aware of the flyweight pattern.
|
|
|
|
To use this pattern, add this class as a metaclass to the class it shall
|
|
be used with. Additionally there needs to be a class attribute
|
|
`_unique_instances`, which should be a `WeakValueDictionary`.
|
|
"""
|
|
|
|
# to avoid parallel creation of (identical) instances
|
|
_lock = threading.Lock()
|
|
|
|
# ATM the implementation relies on the fact that the only
|
|
# constructor argument to determine the identity of
|
|
# a flyweighted entity is a `path`. As soon as we need
|
|
# to add to this set of argument, this (or a derived)
|
|
# implementation must be amended to ensure that we can
|
|
# correctly tell if and when an instance can be treated
|
|
# as "same"
|
|
def __call__(cls, path: Path):
|
|
id_ = path.absolute()
|
|
|
|
# Thread lock following block so we do not fall victim to race
|
|
# condition across threads trying to instantiate multiple instances. In
|
|
# principle we better have a lock per id_ but that mean we might race
|
|
# at getting "name specific lock" (Yarik did not research much), so
|
|
# keeping it KISS -- just lock instantiation altogether, but could be
|
|
# made smarter later on.
|
|
with cls._lock:
|
|
# ignore typing, because MIH does not know how to say that
|
|
# `cls` is required to have a particular class attribute
|
|
instance = cls._unique_instances.get(id_, None) # type: ignore
|
|
if instance is None or not instance.flyweight_valid():
|
|
# we have no such instance yet or the existing one is
|
|
# invalidated, so we instantiate.
|
|
# Importantly, we take any args at face-value and do not
|
|
# let generic code fiddle with them to preserve any and
|
|
# all semantics of the instantiated class
|
|
instance = type.__call__(cls, path)
|
|
# a particular class might resolve the input path parameter
|
|
# to a different one (think root path resolution). in this
|
|
# case we want to root the instance for that resolved path
|
|
# (if we have one), regardless of the given `id_`.
|
|
# TODO: ideally such a resolved path would already be given
|
|
# to this method. However, MIH does not immediately know
|
|
# how to wield the __new__ magic to achieve that. Doing the
|
|
# hack below should be rather cheap...for now.
|
|
if instance.path in cls._unique_instances: # type: ignore
|
|
return cls._unique_instances[instance.path] # type: ignore
|
|
# ignore typing, because MIH does not know how to say that
|
|
# `cls` is required to have a particular class attribute.
|
|
# we use the (resolved) path of the created instance as an
|
|
# ID for future comparison.
|
|
cls._unique_instances[instance.path] = instance # type: ignore
|
|
|
|
return instance
|
|
|
|
|
|
class Flyweighted:
|
|
def __hash__(self):
|
|
# the flyweight key is already determining unique instances
|
|
# add the class name to distinguish from strings of a path
|
|
return hash((self.__class__.__name__, self.__weakref__.key))
|
|
|
|
@classmethod
|
|
def _close(cls, path):
|
|
"""Finalize/clean-up when a flyweighted instance is garbage-collected
|
|
|
|
This default implementation does nothing.
|
|
|
|
This is a classmethod and not an instance method, and we also cannot
|
|
accept any `self`-type arguments. This would create an additional
|
|
reference to the object and thereby preventing it from being collected
|
|
at all.
|
|
"""
|
|
|
|
@abstractmethod
|
|
def flyweight_valid(self):
|
|
"""Tests a cached instance whether it continues to be good to reuse
|
|
|
|
This test runs on every object creation and should be kept as cheap as
|
|
possible.
|
|
"""
|
|
|
|
@property
|
|
@abstractmethod
|
|
def path(self) -> Path:
|
|
"""Absolute path representative of the instance"""
|