Coverage for src/python/ensembl/vep/common/mixins.py: 96%

41 statements  

« prev     ^ index     » next       coverage.py v7.17.2, created at 2026-11-18 14:41 +0000

1# See the NOTICE file distributed with this work for additional information 

2# regarding copyright ownership. 

3# 

4# Licensed under the Apache License, Version 2.0 (the "License"); 

5# you may not use this file except in compliance with the License. 

6# You may obtain a copy of the License at 

7# http://www.apache.org/licenses/LICENSE-2.0 

8# 

9# Unless required by applicable law or agreed to in writing, software 

10# distributed under the License is distributed on an "AS IS" BASIS, 

11# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 

12# See the License for the specific language governing permissions and 

13# limitations under the License. 

14"""Common mixins. Mixins are for reusable behavior without data.""" 

15 

16from contextlib import contextmanager 

17 

18from ensembl.vep.common.methods import invalidate 

19 

20 

21class UnsafeSetterMixin: 

22 """ 

23 Can be used to temporarily disable cache invalidation to allow faster but unsafe attribute update. 

24 

25 Caveat: 

26 This can be very expansive in terms of storage as it stores the type(self) for every instance. 

27 It also create a temporary subclass under the unsafe context although that gets cleaned up 

28 after the context exits. 

29 

30 It also allows setting of cached properties directly using seed_attrs and seed_and_invalidate_attrs 

31 which can lead to inconsistent state if not used carefully. 

32 """ 

33 

34 __slots__ = () 

35 

36 @contextmanager 

37 def unsafe(self): # type: ignore 

38 """Context manager that temporarily swaps the class of this instance to a version with an 

39 unsafe __setattr__ that bypasses attrs' on_setattr hooks.""" 

40 safe_cls = type(self) 

41 

42 # create a throwaway subclass with a bare __setattr__ 

43 unsafe_cls = type( 

44 f"{safe_cls.__name__}_unsafe", 

45 (safe_cls,), 

46 { 

47 "__slots__": (), 

48 "__setattr__": object.__setattr__, 

49 }, 

50 ) 

51 

52 # point this instance at the unsafe subclass 

53 object.__setattr__(self, "__class__", unsafe_cls) 

54 try: 

55 yield self 

56 finally: 

57 # restore the original class 

58 object.__setattr__(self, "__class__", safe_cls) 

59 

60 def assign_without_hooks(self, **values: object) -> None: 

61 """Assign real (non-derived) fields directly, via ``object.__setattr__``. 

62 

63 Unlike ``seed_attrs``, which seeds a protected cached-property slot (``_name``), this sets 

64 the real field (``name``) -- bypassing not just any ``on_setattr`` hook but also any 

65 validator or converter attrs would normally run. 

66 

67 Only for building a brand-new object, before construction is complete and before anything 

68 has read a value derived from the field being set: an already-live object's hooks, 

69 validators and converters would not run, so its invariants could break silently. 

70 

71 Args: 

72 **values (object): Field name to value, exactly as the attrs field is declared (no 

73 leading underscore). 

74 """ 

75 for name, value in values.items(): 

76 object.__setattr__(self, name, value) 

77 

78 def seed_attrs(self, **seeds: object) -> None: 

79 """(Pre-)populate derived and cached attributes, by name, without triggering their normal 

80 derivation. 

81 

82 Writes directly into each named protected slot (``object.__setattr__``, bypassing ``on_setattr`` 

83 hooks and any setter), exactly as a normal ``cached_property`` computation would populate it on 

84 first access. 

85 

86 Seeded attribute can be cleared by the ``invalidates()`` hooks that clear a computed value. 

87 Therefore, Seeding a property derived from such a field must happen after that field is set, or 

88 the seed is invalidated before anything ever reads it. 

89 

90 A derived attribute's computation may depend on other derived attributes. Seeding a derived attribute 

91 does not invalidate derived attributes that depend on it. Use seed_and_invalidate_attrs() if you want 

92 to seed and invalidate dependent derived attributes. 

93 

94 Args: 

95 object: The object to seed. 

96 **seeds (object): Cached-property name (without the leading underscore) with value to 

97 seed, e.g. ``transcript.seed_attrs(cds=my_cds)``. 

98 """ 

99 for name, value in seeds.items(): 

100 object.__setattr__(self, f"_{name}", value) 

101 

102 def seed_and_invalidate_attrs(self, **seeds: object) -> None: 

103 """(Pre-)populate derived and cached attributes, by name, without triggering their 

104 normal derivation and invalidate dependent derived attributes. Don't invalidate dependent 

105 derived attributes if they have also been seeded in the call to ``seed_and_invalidate_attrs``. 

106 

107 This depends on the class having a SEED_INVALIDATES mapping that defines which derived 

108 attributes should be invalidated when a given attribute is seeded. 

109 

110 Args: 

111 object: The object to seed. 

112 **seeds (object): Cached-property name (without the leading underscore) with value to seed, 

113 e.g. ``transcript.seed_and_invalidate_attrs(translation=my_translation, cds=my_cds)``. 

114 """ 

115 seed_invalidations = getattr(type(self), "SEED_INVALIDATES", {}) 

116 seeded_slots: set[str] = set() 

117 invalidation_candidates: set[str] = set() 

118 

119 for name, value in seeds.items(): 

120 object.__setattr__(self, f"_{name}", value) 

121 seeded_slots.add(f"_{name}") 

122 invalidation_candidates.update(seed_invalidations.get(name, ())) 

123 

124 for invalidation_candidate in invalidation_candidates - seeded_slots: 

125 invalidate(self, invalidation_candidate) 

126 

127 

128class CachedAttributeGuardMixin: 

129 """Mixin that guards against setting attributes that are internal properties 

130 and/or invalidate cached properties when their dependencies change. 

131 

132 Caveat: 

133 These can be very expansive as it will be called every time any attribute is updated. 

134 

135 Currently not in use as a less preferable method. Instead, name mangling is used for guarding update to 

136 internal properties and attrs' on_setattr hook for invalidation. 

137 """ 

138 

139 __slots__ = () 

140 

141 def __setattr__(self, name, value): # type: ignore 

142 """Override __setattr__ to guard against setting attributes that are internal properties 

143 and/or invalidate cached properties when their dependencies change. 

144 

145 Args: 

146 name (str): The name of the attribute being set. 

147 value: The value to set the attribute to. 

148 

149 Raises: 

150 AttributeError: If attempting to set a cached property directly. 

151 """ 

152 if name not in type(self)._DERIVED and name not in type(self)._INVALIDATES: 152 ↛ 153line 152 didn't jump to line 153 because the condition on line 152 was never true

153 return super().__setattr__(name, value) 

154 

155 if name in type(self)._DERIVED and name in self.__slots__: 

156 raise AttributeError(f"'{name}' is a cached property and cannot be reassigned") 

157 

158 for invalidation_candidate in type(self)._INVALIDATES.get(name, ()): 

159 try: 

160 delattr(self, invalidation_candidate) 

161 except AttributeError: 

162 pass # If the attribute doesn't exist, we can ignore it 

163 

164 return super().__setattr__(name, value)