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

46 statements  

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

1"""Factory classes that utilize explicit or implicit registries. 

2 

3Contents: 

4 Registrar (`base.Factory`): builds classes and/or instances from a registry 

5 stored in the `registry` class attribute. 

6 AutoRegistrar (`Registrar`, `abc.ABC`): `Registrar` that automatically 

7 registers its subclasses. 

8 Subclasser (`base.Factory`, `abc.ABC`): builds classes and/or instances 

9 from the `__subclasses__` method and a dynamically created registry 

10 based upon it. 

11 

12""" 

13 

14from __future__ import annotations 

15 

16import abc 

17import copy 

18import dataclasses 

19from typing import TYPE_CHECKING, Any, ClassVar 

20 

21from . import base, options, shared 

22 

23if TYPE_CHECKING: 

24 from collections.abc import Hashable, Mapping 

25 

26 

27@dataclasses.dataclass 

28class Registrar(base.Factory): 

29 """Builds an item from a registry. 

30 

31 Attributes: 

32 registry: stores classes and/or instances to be used in item 

33 construction. Defaults to an empty `dict`. 

34 

35 """ 

36 

37 registry: ClassVar[base.GenericDict] = {} 

38 

39 """ Class Methods """ 

40 

41 @classmethod 

42 def create( 

43 cls, 

44 item: Hashable, 

45 parameters: base.Parameters | None = None, 

46 **kwargs: base.Kwargs) -> Any: 

47 """Creates an item based on `item` and possibly `parameters`. 

48 

49 Args: 

50 item: name corresponding to a key in `registry`. 

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

52 Defaults to `None`. 

53 **kwargs: allows subclass to take kwargs. 

54 

55 Raises: 

56 KeyError: if a corresponding item in `registry` does not exist for 

57 `item`. 

58 

59 Returns: 

60 Created item. 

61 

62 """ 

63 item = _get_from_registry(item = item, registry = cls.registry) 

64 return shared.finalize(item = item, parameters = parameters) 

65 

66 

67@dataclasses.dataclass 

68class AutoRegistrar(Registrar, abc.ABC): 

69 """`Registrar` that automatically registers its subclasses. 

70 

71 Attributes: 

72 registry: stores classes and/or instances to be used in item 

73 construction. Defaults to an empty `dict`. 

74 

75 """ 

76 

77 registry: ClassVar[base.GenericDict] = {} 

78 

79 """ Initialization Methods """ 

80 

81 @classmethod 

82 def __init_subclass__(cls, **kwargs: Any) -> None: 

83 """Automatically registers subclasses. 

84 

85 Each direct subclass of `AutoRegistrar` that does not define its own 

86 `registry` gets a new one so that unrelated class families do not share 

87 (and pollute) a single registry. Deeper subclasses register in the 

88 registry they inherit. 

89 

90 Args: 

91 **kwargs: keyword arguments passed to the parent class 

92 `__init_subclass__` method. 

93 

94 """ 

95 super().__init_subclass__(**kwargs) 

96 if cls.registry is AutoRegistrar.registry: 

97 cls.registry = {} 

98 cls.registry[options._KEY_NAMER(cls)] = cls 

99 

100 

101@dataclasses.dataclass 

102class Subclasser(base.Factory, abc.ABC): 

103 """Builds a subclass without requiring a storage attribute. 

104 

105 Unlike some other factories, this one does not require any class attributes. 

106 Instead, it relies on pre-existing data and lazily adds keys to create 

107 a registry facade. 

108 

109 This factory uses the subclasses stored in `__subclasses__` class method 

110 that is automatically created with every class. It creates a `dict` on the 

111 fly with key names based on `options._KEY_NAMER`. Because of this, 

112 `Subclasser` should ordinarily be used as a mixin (although it could simply 

113 be subclassed, if you prefer). 

114 

115 """ 

116 

117 """ Class Methods """ 

118 

119 @classmethod 

120 def create( 

121 cls, 

122 item: Hashable, 

123 parameters: base.Parameters | None = None, 

124 **kwargs: base.Kwargs) -> Any: 

125 """Creates an item based on `item` and possibly `parameters`. 

126 

127 A subclass in the `__subclasses__` class method is selected based on the 

128 naming convention in `options._KEY_NAMER`. 

129 

130 Args: 

131 item: name of the subclass to create. 

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

133 Defaults to `None`. 

134 **kwargs: allows subclass to take kwargs. 

135 

136 Raises: 

137 KeyError: if a corresponding subclass does not exist for `item`. 

138 

139 Returns: 

140 Created item. 

141 

142 """ 

143 keyer = options._KEY_NAMER 

144 registry = {keyer(s): s for s in _get_all_subclasses(cls)} 

145 item = _get_from_registry(item = item, registry = registry) 

146 return shared.finalize(item = item, parameters = parameters) 

147 

148 

149""" Private Functions """ 

150 

151 

152def _get_all_subclasses(item: type[Any]) -> list[type[Any]]: 

153 """Returns a list of all subclasses of `item`, including indirect ones. 

154 

155 Each subclass appears once, in the order in which it is first found by a 

156 depth-first search of `__subclasses__`. 

157 

158 Args: 

159 item: class for which to find subclasses. 

160 

161 Returns: 

162 List of all subclasses of `item`. 

163 

164 """ 

165 subclasses: dict[type[Any], None] = {} 

166 for subclass in item.__subclasses__(): 

167 subclasses[subclass] = None 

168 subclasses.update(dict.fromkeys(_get_all_subclasses(subclass))) 

169 return list(subclasses) 

170 

171 

172def _get_from_registry(item: Hashable, registry: Mapping[Any, Any]) -> Any: 

173 """Returns a copy of a stored item in `registry` with the key of `item`. 

174 

175 Args: 

176 item: key for item sought in `registry`. 

177 registry: registry where the sought item is stored. 

178 

179 Raises: 

180 KeyError: if `item` does not match any key in `registry`. 

181 

182 Returns: 

183 A deep copy of an item stored in `registry`. 

184 

185 """ 

186 try: 

187 return copy.deepcopy(registry[item]) 

188 except KeyError as error: 

189 message = f'{item} was not found in the registry' 

190 raise KeyError(message) from error