Coverage for python/lsst/utils/classes.py: 62%

39 statements  

« prev     ^ index     » next       coverage.py v7.3.1, created at 2023-09-17 07:53 +0000

1# This file is part of utils. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

5# (https://www.lsst.org). 

6# See the COPYRIGHT file at the top-level directory of this distribution 

7# for details of code ownership. 

8# 

9# Use of this source code is governed by a 3-clause BSD-style 

10# license that can be found in the LICENSE file. 

11# 

12 

13"""Utilities to help with class creation. 

14""" 

15 

16from __future__ import annotations 

17 

18__all__ = ["Singleton", "cached_getter", "immutable"] 

19 

20import functools 

21from collections.abc import Callable 

22from typing import Any, ClassVar, Type, TypeVar 

23 

24 

25class Singleton(type): 

26 """Metaclass to convert a class to a Singleton. 

27 

28 If this metaclass is used the constructor for the singleton class must 

29 take no arguments. This is because a singleton class will only accept 

30 the arguments the first time an instance is instantiated. 

31 Therefore since you do not know if the constructor has been called yet it 

32 is safer to always call it with no arguments and then call a method to 

33 adjust state of the singleton. 

34 """ 

35 

36 _instances: ClassVar[dict[type, Any]] = {} 

37 

38 # Signature is intentionally not substitutable for type.__call__ (no *args, 

39 # **kwargs) to require classes that use this metaclass to have no 

40 # constructor arguments. 

41 def __call__(cls) -> Any: 

42 if cls not in cls._instances: 

43 cls._instances[cls] = super().__call__() 

44 return cls._instances[cls] 

45 

46 

47_T = TypeVar("_T", bound="Type") 

48 

49 

50def immutable(cls: _T) -> _T: 

51 """Decorate a class to simulate a simple form of immutability. 

52 

53 A class decorated as `immutable` may only set each of its attributes once; 

54 any attempts to set an already-set attribute will raise `AttributeError`. 

55 

56 Notes 

57 ----- 

58 Subclasses of classes marked with ``@immutable`` are also immutable. 

59 

60 Because this behavior interferes with the default implementation for the 

61 ``pickle`` modules, `immutable` provides implementations of 

62 ``__getstate__`` and ``__setstate__`` that override this behavior. 

63 Immutable classes can then implement pickle via ``__reduce__`` or 

64 ``__getnewargs__``. 

65 

66 Following the example of Python's built-in immutable types, such as `str` 

67 and `tuple`, the `immutable` decorator provides a ``__copy__`` 

68 implementation that just returns ``self``, because there is no reason to 

69 actually copy an object if none of its shared owners can modify it. 

70 

71 Similarly, objects that are recursively (i.e. are themselves immutable and 

72 have only recursively immutable attributes) should also reimplement 

73 ``__deepcopy__`` to return ``self``. This is not done by the decorator, as 

74 it has no way of checking for recursive immutability. 

75 """ 

76 

77 def __setattr__(self: _T, name: str, value: Any) -> None: # noqa: N807 

78 if hasattr(self, name): 

79 raise AttributeError(f"{cls.__name__} instances are immutable.") 

80 object.__setattr__(self, name, value) 

81 

82 # mypy says the variable here has signature (str, Any) i.e. no "self"; 

83 # I think it's just confused by descriptor stuff. 

84 cls.__setattr__ = __setattr__ # type: ignore 

85 

86 def __getstate__(self: _T) -> dict: # noqa: N807 

87 # Disable default state-setting when unpickled. 

88 return {} 

89 

90 cls.__getstate__ = __getstate__ # type: ignore[assignment] 

91 

92 def __setstate__(self: _T, state: Any) -> None: # noqa: N807 

93 # Disable default state-setting when copied. 

94 # Sadly what works for pickle doesn't work for copy. 

95 assert not state 

96 

97 cls.__setstate__ = __setstate__ 

98 

99 def __copy__(self: _T) -> _T: # noqa: N807 

100 return self 

101 

102 cls.__copy__ = __copy__ 

103 return cls 

104 

105 

106_S = TypeVar("_S") 

107_R = TypeVar("_R") 

108 

109 

110def cached_getter(func: Callable[[_S], _R]) -> Callable[[_S], _R]: 

111 """Decorate a method to cache the result. 

112 

113 Only works on methods that take only ``self`` 

114 as an argument, and returns the cached result on subsequent calls. 

115 

116 Notes 

117 ----- 

118 This is intended primarily as a stopgap for Python 3.8's more sophisticated 

119 ``functools.cached_property``, but it is also explicitly compatible with 

120 the `immutable` decorator, which may not be true of ``cached_property``. 

121 

122 `cached_getter` guarantees that the cached value will be stored in 

123 an attribute named ``_cached_{name-of-decorated-function}``. Classes that 

124 use `cached_getter` are responsible for guaranteeing that this name is not 

125 otherwise used, and is included if ``__slots__`` is defined. 

126 """ 

127 attribute = f"_cached_{func.__name__}" 

128 

129 @functools.wraps(func) 

130 def inner(self: _S) -> _R: 

131 if not hasattr(self, attribute): 

132 object.__setattr__(self, attribute, func(self)) 

133 return getattr(self, attribute) 

134 

135 return inner