Coverage for python/lsst/pex/config/dictField.py: 24%

136 statements  

« prev     ^ index     » next       coverage.py v6.4, created at 2022-06-02 11:08 +0000

1# This file is part of pex_config. 

2# 

3# Developed for the LSST Data Management System. 

4# This product includes software developed by the LSST Project 

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

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

7# for details of code ownership. 

8# 

9# This software is dual licensed under the GNU General Public License and also 

10# under a 3-clause BSD license. Recipients may choose which of these licenses 

11# to use; please see the files gpl-3.0.txt and/or bsd_license.txt, 

12# respectively. If you choose the GPL option then the following text applies 

13# (but note that there is still no warranty even if you opt for BSD instead): 

14# 

15# This program is free software: you can redistribute it and/or modify 

16# it under the terms of the GNU General Public License as published by 

17# the Free Software Foundation, either version 3 of the License, or 

18# (at your option) any later version. 

19# 

20# This program is distributed in the hope that it will be useful, 

21# but WITHOUT ANY WARRANTY; without even the implied warranty of 

22# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the 

23# GNU General Public License for more details. 

24# 

25# You should have received a copy of the GNU General Public License 

26# along with this program. If not, see <http://www.gnu.org/licenses/>. 

27 

28__all__ = ["DictField"] 

29 

30import collections.abc 

31import weakref 

32 

33from .callStack import getCallStack, getStackFrame 

34from .comparison import compareScalars, getComparisonName 

35from .config import ( 

36 Config, 

37 Field, 

38 FieldValidationError, 

39 UnexpectedProxyUsageError, 

40 _autocast, 

41 _joinNamePath, 

42 _typeStr, 

43) 

44 

45 

46class Dict(collections.abc.MutableMapping): 

47 """An internal mapping container. 

48 

49 This class emulates a `dict`, but adds validation and provenance. 

50 """ 

51 

52 def __init__(self, config, field, value, at, label, setHistory=True): 

53 self._field = field 

54 self._config_ = weakref.ref(config) 

55 self._dict = {} 

56 self._history = self._config._history.setdefault(self._field.name, []) 

57 self.__doc__ = field.doc 

58 if value is not None: 

59 try: 

60 for k in value: 

61 # do not set history per-item 

62 self.__setitem__(k, value[k], at=at, label=label, setHistory=False) 

63 except TypeError: 

64 msg = "Value %s is of incorrect type %s. Mapping type expected." % (value, _typeStr(value)) 

65 raise FieldValidationError(self._field, self._config, msg) 

66 if setHistory: 

67 self._history.append((dict(self._dict), at, label)) 

68 

69 @property 

70 def _config(self) -> Config: 

71 # Config Fields should never outlive their config class instance 

72 # assert that as such here 

73 assert self._config_() is not None 

74 return self._config_() 

75 

76 history = property(lambda x: x._history) 76 ↛ exitline 76 didn't run the lambda on line 76

77 """History (read-only). 

78 """ 

79 

80 def __getitem__(self, k): 

81 return self._dict[k] 

82 

83 def __len__(self): 

84 return len(self._dict) 

85 

86 def __iter__(self): 

87 return iter(self._dict) 

88 

89 def __contains__(self, k): 

90 return k in self._dict 

91 

92 def __setitem__(self, k, x, at=None, label="setitem", setHistory=True): 

93 if self._config._frozen: 

94 msg = "Cannot modify a frozen Config. Attempting to set item at key %r to value %s" % (k, x) 

95 raise FieldValidationError(self._field, self._config, msg) 

96 

97 # validate keytype 

98 k = _autocast(k, self._field.keytype) 

99 if type(k) != self._field.keytype: 

100 msg = "Key %r is of type %s, expected type %s" % (k, _typeStr(k), _typeStr(self._field.keytype)) 

101 raise FieldValidationError(self._field, self._config, msg) 

102 

103 # validate itemtype 

104 x = _autocast(x, self._field.itemtype) 

105 if self._field.itemtype is None: 

106 if type(x) not in self._field.supportedTypes and x is not None: 

107 msg = "Value %s at key %r is of invalid type %s" % (x, k, _typeStr(x)) 

108 raise FieldValidationError(self._field, self._config, msg) 

109 else: 

110 if type(x) != self._field.itemtype and x is not None: 

111 msg = "Value %s at key %r is of incorrect type %s. Expected type %s" % ( 

112 x, 

113 k, 

114 _typeStr(x), 

115 _typeStr(self._field.itemtype), 

116 ) 

117 raise FieldValidationError(self._field, self._config, msg) 

118 

119 # validate item using itemcheck 

120 if self._field.itemCheck is not None and not self._field.itemCheck(x): 

121 msg = "Item at key %r is not a valid value: %s" % (k, x) 

122 raise FieldValidationError(self._field, self._config, msg) 

123 

124 if at is None: 

125 at = getCallStack() 

126 

127 self._dict[k] = x 

128 if setHistory: 

129 self._history.append((dict(self._dict), at, label)) 

130 

131 def __delitem__(self, k, at=None, label="delitem", setHistory=True): 

132 if self._config._frozen: 

133 raise FieldValidationError(self._field, self._config, "Cannot modify a frozen Config") 

134 

135 del self._dict[k] 

136 if setHistory: 

137 if at is None: 

138 at = getCallStack() 

139 self._history.append((dict(self._dict), at, label)) 

140 

141 def __repr__(self): 

142 return repr(self._dict) 

143 

144 def __str__(self): 

145 return str(self._dict) 

146 

147 def __setattr__(self, attr, value, at=None, label="assignment"): 

148 if hasattr(getattr(self.__class__, attr, None), "__set__"): 

149 # This allows properties to work. 

150 object.__setattr__(self, attr, value) 

151 elif attr in self.__dict__ or attr in ["_field", "_config_", "_history", "_dict", "__doc__"]: 

152 # This allows specific private attributes to work. 

153 object.__setattr__(self, attr, value) 

154 else: 

155 # We throw everything else. 

156 msg = "%s has no attribute %s" % (_typeStr(self._field), attr) 

157 raise FieldValidationError(self._field, self._config, msg) 

158 

159 def __reduce__(self): 

160 raise UnexpectedProxyUsageError( 

161 f"Proxy container for config field {self._field.name} cannot " 

162 "be pickled; it should be converted to a built-in container before " 

163 "being assigned to other objects or variables." 

164 ) 

165 

166 

167class DictField(Field): 

168 """A configuration field (`~lsst.pex.config.Field` subclass) that maps keys 

169 and values. 

170 

171 The types of both items and keys are restricted to these builtin types: 

172 `int`, `float`, `complex`, `bool`, and `str`). All keys share the same type 

173 and all values share the same type. Keys can have a different type from 

174 values. 

175 

176 Parameters 

177 ---------- 

178 doc : `str` 

179 A documentation string that describes the configuration field. 

180 keytype : {`int`, `float`, `complex`, `bool`, `str`} 

181 The type of the mapping keys. All keys must have this type. 

182 itemtype : {`int`, `float`, `complex`, `bool`, `str`} 

183 Type of the mapping values. 

184 default : `dict`, optional 

185 The default mapping. 

186 optional : `bool`, optional 

187 If `True`, the field doesn't need to have a set value. 

188 dictCheck : callable 

189 A function that validates the dictionary as a whole. 

190 itemCheck : callable 

191 A function that validates individual mapping values. 

192 deprecated : None or `str`, optional 

193 A description of why this Field is deprecated, including removal date. 

194 If not None, the string is appended to the docstring for this Field. 

195 

196 See also 

197 -------- 

198 ChoiceField 

199 ConfigChoiceField 

200 ConfigDictField 

201 ConfigField 

202 ConfigurableField 

203 Field 

204 ListField 

205 RangeField 

206 RegistryField 

207 

208 Examples 

209 -------- 

210 This field maps has `str` keys and `int` values: 

211 

212 >>> from lsst.pex.config import Config, DictField 

213 >>> class MyConfig(Config): 

214 ... field = DictField( 

215 ... doc="Example string-to-int mapping field.", 

216 ... keytype=str, itemtype=int, 

217 ... default={}) 

218 ... 

219 >>> config = MyConfig() 

220 >>> config.field['myKey'] = 42 

221 >>> print(config.field) 

222 {'myKey': 42} 

223 """ 

224 

225 DictClass = Dict 

226 

227 def __init__( 

228 self, 

229 doc, 

230 keytype, 

231 itemtype, 

232 default=None, 

233 optional=False, 

234 dictCheck=None, 

235 itemCheck=None, 

236 deprecated=None, 

237 ): 

238 source = getStackFrame() 

239 self._setup( 

240 doc=doc, 

241 dtype=Dict, 

242 default=default, 

243 check=None, 

244 optional=optional, 

245 source=source, 

246 deprecated=deprecated, 

247 ) 

248 if keytype not in self.supportedTypes: 248 ↛ 249line 248 didn't jump to line 249, because the condition on line 248 was never true

249 raise ValueError("'keytype' %s is not a supported type" % _typeStr(keytype)) 

250 elif itemtype is not None and itemtype not in self.supportedTypes: 250 ↛ 251line 250 didn't jump to line 251, because the condition on line 250 was never true

251 raise ValueError("'itemtype' %s is not a supported type" % _typeStr(itemtype)) 

252 if dictCheck is not None and not hasattr(dictCheck, "__call__"): 252 ↛ 253line 252 didn't jump to line 253, because the condition on line 252 was never true

253 raise ValueError("'dictCheck' must be callable") 

254 if itemCheck is not None and not hasattr(itemCheck, "__call__"): 254 ↛ 255line 254 didn't jump to line 255, because the condition on line 254 was never true

255 raise ValueError("'itemCheck' must be callable") 

256 

257 self.keytype = keytype 

258 self.itemtype = itemtype 

259 self.dictCheck = dictCheck 

260 self.itemCheck = itemCheck 

261 

262 def validate(self, instance): 

263 """Validate the field's value (for internal use only). 

264 

265 Parameters 

266 ---------- 

267 instance : `lsst.pex.config.Config` 

268 The configuration that contains this field. 

269 

270 Returns 

271 ------- 

272 isValid : `bool` 

273 `True` is returned if the field passes validation criteria (see 

274 *Notes*). Otherwise `False`. 

275 

276 Notes 

277 ----- 

278 This method validates values according to the following criteria: 

279 

280 - A non-optional field is not `None`. 

281 - If a value is not `None`, is must pass the `ConfigField.dictCheck` 

282 user callback functon. 

283 

284 Individual item checks by the `ConfigField.itemCheck` user callback 

285 function are done immediately when the value is set on a key. Those 

286 checks are not repeated by this method. 

287 """ 

288 Field.validate(self, instance) 

289 value = self.__get__(instance) 

290 if value is not None and self.dictCheck is not None and not self.dictCheck(value): 

291 msg = "%s is not a valid value" % str(value) 

292 raise FieldValidationError(self, instance, msg) 

293 

294 def __set__(self, instance, value, at=None, label="assignment"): 

295 if instance._frozen: 

296 msg = "Cannot modify a frozen Config. Attempting to set field to value %s" % value 

297 raise FieldValidationError(self, instance, msg) 

298 

299 if at is None: 

300 at = getCallStack() 

301 if value is not None: 

302 value = self.DictClass(instance, self, value, at=at, label=label) 

303 else: 

304 history = instance._history.setdefault(self.name, []) 

305 history.append((value, at, label)) 

306 

307 instance._storage[self.name] = value 

308 

309 def toDict(self, instance): 

310 """Convert this field's key-value pairs into a regular `dict`. 

311 

312 Parameters 

313 ---------- 

314 instance : `lsst.pex.config.Config` 

315 The configuration that contains this field. 

316 

317 Returns 

318 ------- 

319 result : `dict` or `None` 

320 If this field has a value of `None`, then this method returns 

321 `None`. Otherwise, this method returns the field's value as a 

322 regular Python `dict`. 

323 """ 

324 value = self.__get__(instance) 

325 return dict(value) if value is not None else None 

326 

327 def _compare(self, instance1, instance2, shortcut, rtol, atol, output): 

328 """Compare two fields for equality. 

329 

330 Used by `lsst.pex.ConfigDictField.compare`. 

331 

332 Parameters 

333 ---------- 

334 instance1 : `lsst.pex.config.Config` 

335 Left-hand side config instance to compare. 

336 instance2 : `lsst.pex.config.Config` 

337 Right-hand side config instance to compare. 

338 shortcut : `bool` 

339 If `True`, this function returns as soon as an inequality if found. 

340 rtol : `float` 

341 Relative tolerance for floating point comparisons. 

342 atol : `float` 

343 Absolute tolerance for floating point comparisons. 

344 output : callable 

345 A callable that takes a string, used (possibly repeatedly) to 

346 report inequalities. 

347 

348 Returns 

349 ------- 

350 isEqual : bool 

351 `True` if the fields are equal, `False` otherwise. 

352 

353 Notes 

354 ----- 

355 Floating point comparisons are performed by `numpy.allclose`. 

356 """ 

357 d1 = getattr(instance1, self.name) 

358 d2 = getattr(instance2, self.name) 

359 name = getComparisonName( 

360 _joinNamePath(instance1._name, self.name), _joinNamePath(instance2._name, self.name) 

361 ) 

362 if not compareScalars("isnone for %s" % name, d1 is None, d2 is None, output=output): 

363 return False 

364 if d1 is None and d2 is None: 

365 return True 

366 if not compareScalars("keys for %s" % name, set(d1.keys()), set(d2.keys()), output=output): 

367 return False 

368 equal = True 

369 for k, v1 in d1.items(): 

370 v2 = d2[k] 

371 result = compareScalars( 

372 "%s[%r]" % (name, k), v1, v2, dtype=self.itemtype, rtol=rtol, atol=atol, output=output 

373 ) 

374 if not result and shortcut: 

375 return False 

376 equal = equal and result 

377 return equal