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

Shortcuts on this page

r m x p   toggle line displays

j k   next/prev highlighted chunk

0   (zero) top of page

1   (one) first highlighted chunk

133 statements  

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 Config, Field, FieldValidationError, _autocast, _joinNamePath, _typeStr 

36 

37 

38class Dict(collections.abc.MutableMapping): 

39 """An internal mapping container. 

40 

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

42 """ 

43 

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

45 self._field = field 

46 self._config_ = weakref.ref(config) 

47 self._dict = {} 

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

49 self.__doc__ = field.doc 

50 if value is not None: 

51 try: 

52 for k in value: 

53 # do not set history per-item 

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

55 except TypeError: 

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

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

58 if setHistory: 

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

60 

61 @property 

62 def _config(self) -> Config: 

63 # Config Fields should never outlive their config class instance 

64 # assert that as such here 

65 assert self._config_() is not None 

66 return self._config_() 

67 

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

69 """History (read-only). 

70 """ 

71 

72 def __getitem__(self, k): 

73 return self._dict[k] 

74 

75 def __len__(self): 

76 return len(self._dict) 

77 

78 def __iter__(self): 

79 return iter(self._dict) 

80 

81 def __contains__(self, k): 

82 return k in self._dict 

83 

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

85 if self._config._frozen: 

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

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

88 

89 # validate keytype 

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

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

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

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

94 

95 # validate itemtype 

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

97 if self._field.itemtype is None: 

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

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

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

101 else: 

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

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

104 x, 

105 k, 

106 _typeStr(x), 

107 _typeStr(self._field.itemtype), 

108 ) 

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

110 

111 # validate item using itemcheck 

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

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

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

115 

116 if at is None: 

117 at = getCallStack() 

118 

119 self._dict[k] = x 

120 if setHistory: 

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

122 

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

124 if self._config._frozen: 

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

126 

127 del self._dict[k] 

128 if setHistory: 

129 if at is None: 

130 at = getCallStack() 

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

132 

133 def __repr__(self): 

134 return repr(self._dict) 

135 

136 def __str__(self): 

137 return str(self._dict) 

138 

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

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

141 # This allows properties to work. 

142 object.__setattr__(self, attr, value) 

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

144 # This allows specific private attributes to work. 

145 object.__setattr__(self, attr, value) 

146 else: 

147 # We throw everything else. 

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

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

150 

151 

152class DictField(Field): 

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

154 and values. 

155 

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

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

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

159 values. 

160 

161 Parameters 

162 ---------- 

163 doc : `str` 

164 A documentation string that describes the configuration field. 

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

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

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

168 Type of the mapping values. 

169 default : `dict`, optional 

170 The default mapping. 

171 optional : `bool`, optional 

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

173 dictCheck : callable 

174 A function that validates the dictionary as a whole. 

175 itemCheck : callable 

176 A function that validates individual mapping values. 

177 deprecated : None or `str`, optional 

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

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

180 

181 See also 

182 -------- 

183 ChoiceField 

184 ConfigChoiceField 

185 ConfigDictField 

186 ConfigField 

187 ConfigurableField 

188 Field 

189 ListField 

190 RangeField 

191 RegistryField 

192 

193 Examples 

194 -------- 

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

196 

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

198 >>> class MyConfig(Config): 

199 ... field = DictField( 

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

201 ... keytype=str, itemtype=int, 

202 ... default={}) 

203 ... 

204 >>> config = MyConfig() 

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

206 >>> print(config.field) 

207 {'myKey': 42} 

208 """ 

209 

210 DictClass = Dict 

211 

212 def __init__( 

213 self, 

214 doc, 

215 keytype, 

216 itemtype, 

217 default=None, 

218 optional=False, 

219 dictCheck=None, 

220 itemCheck=None, 

221 deprecated=None, 

222 ): 

223 source = getStackFrame() 

224 self._setup( 

225 doc=doc, 

226 dtype=Dict, 

227 default=default, 

228 check=None, 

229 optional=optional, 

230 source=source, 

231 deprecated=deprecated, 

232 ) 

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

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

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

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

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

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

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

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

241 

242 self.keytype = keytype 

243 self.itemtype = itemtype 

244 self.dictCheck = dictCheck 

245 self.itemCheck = itemCheck 

246 

247 def validate(self, instance): 

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

249 

250 Parameters 

251 ---------- 

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

253 The configuration that contains this field. 

254 

255 Returns 

256 ------- 

257 isValid : `bool` 

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

259 *Notes*). Otherwise `False`. 

260 

261 Notes 

262 ----- 

263 This method validates values according to the following criteria: 

264 

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

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

267 user callback functon. 

268 

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

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

271 checks are not repeated by this method. 

272 """ 

273 Field.validate(self, instance) 

274 value = self.__get__(instance) 

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

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

277 raise FieldValidationError(self, instance, msg) 

278 

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

280 if instance._frozen: 

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

282 raise FieldValidationError(self, instance, msg) 

283 

284 if at is None: 

285 at = getCallStack() 

286 if value is not None: 

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

288 else: 

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

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

291 

292 instance._storage[self.name] = value 

293 

294 def toDict(self, instance): 

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

296 

297 Parameters 

298 ---------- 

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

300 The configuration that contains this field. 

301 

302 Returns 

303 ------- 

304 result : `dict` or `None` 

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

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

307 regular Python `dict`. 

308 """ 

309 value = self.__get__(instance) 

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

311 

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

313 """Compare two fields for equality. 

314 

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

316 

317 Parameters 

318 ---------- 

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

320 Left-hand side config instance to compare. 

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

322 Right-hand side config instance to compare. 

323 shortcut : `bool` 

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

325 rtol : `float` 

326 Relative tolerance for floating point comparisons. 

327 atol : `float` 

328 Absolute tolerance for floating point comparisons. 

329 output : callable 

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

331 report inequalities. 

332 

333 Returns 

334 ------- 

335 isEqual : bool 

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

337 

338 Notes 

339 ----- 

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

341 """ 

342 d1 = getattr(instance1, self.name) 

343 d2 = getattr(instance2, self.name) 

344 name = getComparisonName( 

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

346 ) 

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

348 return False 

349 if d1 is None and d2 is None: 

350 return True 

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

352 return False 

353 equal = True 

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

355 v2 = d2[k] 

356 result = compareScalars( 

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

358 ) 

359 if not result and shortcut: 

360 return False 

361 equal = equal and result 

362 return equal