Coverage for src/wonka/base.py: 100%

61 statements  

« prev     ^ index     » next       coverage.py v7.14.1, created at 2026-10-30 22:54 +0000

1"""Base classes and type aliases for `wonka`. 

2 

3Contents: 

4 Factory (`abc.ABC`): interface for basic `wonka` creation classes. A 

5 `create` class method is required for subclasses. 

6 Manager (`Iterable`, `abc.ABC`): iterable interface for complex construction 

7 managers. A `manage` instance method is required for subclasses. For 

8 compatibility as a `wonka` constructor, a `create` method is included 

9 which calls the `manage` method with all args and kwargs. 

10 Producer (`abc.ABC`): mixin interface for classes that alter created items 

11 before returning them. A `produce` class method is required for 

12 subclasses. 

13 Cluster (`abc.ABC`): interface for collections of `wonka` constructors. 

14 `add` and `delete` methods are required for subclasses. 

15 Constructor (`TypeAlias`): type alias for a wonka-compatible constructor 

16 type. By default, it includes a `Factory` subclass, a `Factory` subclass 

17 instance, and a `Manager` subclass instance. 

18 ConstructorDict (`TypeAlias`): type alias for a mapping of `str` names to 

19 constructors. 

20 GenericDict (`TypeAlias`): type alias for a mapping with any keys and 

21 values, such as a registry. 

22 Kwargs (`TypeAlias`): type alias for the values of `**kwargs`. 

23 Parameters (`TypeAlias`): type alias for the keyword arguments passed or 

24 added to a created item. 

25 

26""" 

27 

28from __future__ import annotations 

29 

30import abc 

31import copy 

32import dataclasses 

33from collections.abc import ( 

34 Hashable, 

35 Iterable, 

36 Iterator, 

37 Mapping, 

38 MutableMapping, 

39) 

40from typing import Any, Self, TypeAlias 

41 

42GenericDict: TypeAlias = MutableMapping[Hashable, Any] 

43Kwargs: TypeAlias = Any 

44Parameters: TypeAlias = Mapping[str, Any] 

45 

46 

47@dataclasses.dataclass 

48class Factory(abc.ABC): 

49 """Base for `wonka` constructors. 

50 

51 A `wonka` `Factory` can be subclassed into any constructor design (not just 

52 those that fit the classical factory design pattern). So, for example, the 

53 `wonka` package itself includes `Factory` subclasses that fit the prototype 

54 (`Scribe`), registry (`Registrar` and `Subclasser`), and traditional factory 

55 (`Delegate` and `Sourcerer`) design patterns. Further, a `Manager` class 

56 instance may act as the director in a builder design pattern. 

57 

58 One of the goals of `wonka`, though, is not to be wedded to or worried about 

59 the underlying design pattern. Instead, all constructors follow the simple, 

60 universal, and easily extensible interface of `Factory`. 

61 

62 If you want to add code that modifies output of a `Factory`'s `create` class 

63 method, you can either include that in the subclass `create` method or mix 

64 in a `Producer` class. Details on how to use `Producer` subclasses are 

65 included in its documentation. 

66 

67 """ 

68 

69 """ Required Methods """ 

70 

71 @classmethod 

72 @abc.abstractmethod 

73 def create(cls, item: Any, **kwargs: Kwargs) -> Any: 

74 """Returns a created or modified item. 

75 

76 Args: 

77 item: data for creation of an item or an item to be modified. 

78 **kwargs: allows subclass to take other keyword arguments. 

79 

80 Returns: 

81 Created item. 

82 

83 """ 

84 

85 

86@dataclasses.dataclass 

87class Manager(Iterable[Any], abc.ABC): 

88 """Base for managing complex class or object construction. 

89 

90 Args: 

91 contents: an iterable containing `Factory` subclasses or `Manager` 

92 subclass instances. 

93 

94 """ 

95 

96 contents: Iterable[Any] 

97 

98 """ Required Methods """ 

99 

100 @abc.abstractmethod 

101 def manage(self, item: Any, **kwargs: Kwargs) -> Any: 

102 """Manages construction and/or modification based on `item`. 

103 

104 Args: 

105 item: item to be passed to factories in `contents`. 

106 **kwargs: allows subclass to take other keyword arguments. 

107 

108 Returns: 

109 Constructed item. 

110 

111 """ 

112 

113 """ Public Methods """ 

114 

115 def create(self, item: Any, **kwargs: Kwargs) -> Any: 

116 """Calls `manage` method. 

117 

118 This method is included as a convenience so that an instance of a 

119 `Manager` can be used as a drop-in for a `Factory` subclass. `Manager` 

120 cannot easily be made a subclass for `Factory` because it will often 

121 need to rely on instance data for construction. So, every `Manager` 

122 subclass should be designed such that an instance of that subclass could 

123 be substituted for a `Factory` subclass. This allows other `Manager` 

124 subclass instances to be stored in `contents` as part of an iterable 

125 workflow. 

126 

127 Args: 

128 item: item to be passed to factories in `contents`. 

129 **kwargs: allows subclass to take other keyword arguments. 

130 

131 Returns: 

132 Constructed item. 

133 

134 """ 

135 return self.manage(item, **kwargs) 

136 

137 """ Dunder Methods """ 

138 

139 def __iter__(self) -> Iterator[Any]: 

140 """Returns iterator of `contents`. 

141 

142 `Manager` is agnostic as to the type of iterable that is used in order 

143 to accommodate simple sequences, complex graphs, nested trees, or any 

144 other workflow design. As a general practice, though, any mapping should 

145 probably return `items()` so that the interface for iteration never 

146 requires any appended method call. But nothing in `wonka` precludes a 

147 different rule or practice. 

148 

149 Returns: 

150 Iterator of `contents`. 

151 

152 """ 

153 return iter(self.contents) 

154 

155 

156@dataclasses.dataclass 

157class Producer(abc.ABC): 

158 """Base mixin for modifying items. 

159 

160 A `Producer`'s `produce` method will automatically be called if it is 

161 mixed-in with any of the `Factory` classes in `wonka`. If you want a custom 

162 `Factory` subclass to similarly automatically check for a `produce` method, 

163 the easiest way to do that is to simply call the `finalize` function as your 

164 return value for the `Factory`'s `create` method as follows: 

165 

166 ```python 

167 return wonka.finalize(item = item, parameters = parameters) 

168 ``` 

169 

170 """ 

171 

172 """ Required Methods """ 

173 

174 @classmethod 

175 @abc.abstractmethod 

176 def produce(cls, item: Any, parameters: Parameters | None = None) -> Any: 

177 """Modifies `item` and possibly incorporates `parameters`. 

178 

179 Args: 

180 item: item to be modified. 

181 parameters: keyword arguments to pass or add to a created instance. 

182 Defaults to `None`. 

183 

184 Returns: 

185 Modified item. 

186 

187 """ 

188 

189 

190Constructor: TypeAlias = Factory | type[Factory] | Manager 

191ConstructorDict: TypeAlias = MutableMapping[str, Constructor] 

192 

193 

194@dataclasses.dataclass 

195class Cluster(abc.ABC): 

196 """Base for collections of factories. 

197 

198 Args: 

199 contents: stored `dict` of `wonka` factories. Defaults to an empty 

200 `dict`. 

201 

202 """ 

203 

204 contents: ConstructorDict = dataclasses.field(default_factory = dict) 

205 

206 """ Required Methods """ 

207 

208 @abc.abstractmethod 

209 def add( 

210 self, 

211 item: ConstructorDict | Constructor, 

212 **kwargs: Kwargs) -> None: 

213 """Adds `item` to the `contents` attribute. 

214 

215 Args: 

216 item: factory or factories to add. 

217 **kwargs: allows subclass to take other keyword arguments. 

218 

219 """ 

220 

221 @abc.abstractmethod 

222 def delete(self, item: str, **kwargs: Kwargs) -> None: 

223 """Deletes `item` in `contents`. 

224 

225 Args: 

226 item: key in `contents` to delete the key/value pair. 

227 **kwargs: allows subclass to take other keyword arguments. 

228 

229 """ 

230 

231 """ Dunder Methods """ 

232 

233 def __getitem__(self, key: str) -> Constructor: 

234 """Returns value for `key` in `contents`. 

235 

236 Args: 

237 key: key in `contents` for which a value is sought. 

238 

239 Returns: 

240 Value stored in `contents`. 

241 

242 """ 

243 return self.contents[key] 

244 

245 def __setitem__(self, key: str, value: Constructor) -> None: 

246 """Sets `key` in `contents` to `value`. 

247 

248 Args: 

249 key: key to set in `contents`. 

250 value: value to be paired with `key` in `contents`. 

251 

252 """ 

253 self.contents[key] = value 

254 

255 def __delitem__(self, item: str) -> None: 

256 """Deletes `item` from `contents`. 

257 

258 Args: 

259 item: key to delete in `contents`. 

260 

261 """ 

262 self.delete(item = item) 

263 

264 def __add__(self, other: ConstructorDict | Constructor) -> Self: 

265 """Returns a deep copy with `other` combined using the `add` method. 

266 

267 Args: 

268 other: item to add to the copy's `contents` using the `add` method. 

269 

270 Returns: 

271 A new instance. The original instance is not modified. 

272 

273 """ 

274 new_cluster = copy.deepcopy(self) 

275 new_cluster.add(item = other) 

276 return new_cluster 

277 

278 def __iadd__(self, other: ConstructorDict | Constructor) -> Self: 

279 """Combines argument with `contents` using the `add` method. 

280 

281 Args: 

282 other: item to add to `contents` using the `add` method. 

283 

284 Returns: 

285 The instance, modified in place. 

286 

287 """ 

288 self.add(item = other) 

289 return self 

290 

291 def __iter__(self) -> Iterator[str]: 

292 """Returns iterator of `contents`. 

293 

294 Returns: 

295 Iterator of the keys in `contents`. 

296 

297 """ 

298 return iter(self.contents) 

299 

300 def __len__(self) -> int: 

301 """Returns length of `contents`. 

302 

303 Returns: 

304 Length of `contents`. 

305 

306 """ 

307 return len(self.contents)