Coverage for /pythoncovmergedfiles/medio/medio/usr/local/lib/python3.8/site-packages/tables/exceptions.py: 75%

77 statements  

« prev     ^ index     » next       coverage.py v7.2.5, created at 2023-05-10 06:15 +0000

1"""Declare exceptions and warnings that are specific to PyTables.""" 

2 

3import os 

4import warnings 

5import traceback 

6 

7 

8__all__ = [ 

9 "ClosedFileError", 

10 "ClosedNodeError", 

11 "DataTypeWarning", 

12 "ExperimentalFeatureWarning", 

13 "FileModeError", 

14 "FiltersWarning", 

15 "FlavorError", 

16 "FlavorWarning", 

17 "HDF5ExtError", 

18 "NaturalNameWarning", 

19 "NoSuchNodeError", 

20 "NodeError", 

21 "OldIndexWarning", 

22 "PerformanceWarning", 

23 "UnclosedFileWarning", 

24 "UndoRedoError", 

25 "UndoRedoWarning", 

26] 

27 

28 

29__docformat__ = 'reStructuredText' 

30"""The format of documentation strings in this module.""" 

31 

32 

33class HDF5ExtError(RuntimeError): 

34 """A low level HDF5 operation failed. 

35 

36 This exception is raised the low level PyTables components used for 

37 accessing HDF5 files. It usually signals that something is not 

38 going well in the HDF5 library or even at the Input/Output level. 

39 

40 Errors in the HDF5 C library may be accompanied by an extensive 

41 HDF5 back trace on standard error (see also 

42 :func:`tables.silence_hdf5_messages`). 

43 

44 .. versionchanged:: 2.4 

45 

46 Parameters 

47 ---------- 

48 message 

49 error message 

50 h5bt 

51 This parameter (keyword only) controls the HDF5 back trace 

52 handling. Any keyword arguments other than h5bt is ignored. 

53 

54 * if set to False the HDF5 back trace is ignored and the 

55 :attr:`HDF5ExtError.h5backtrace` attribute is set to None 

56 * if set to True the back trace is retrieved from the HDF5 

57 library and stored in the :attr:`HDF5ExtError.h5backtrace` 

58 attribute as a list of tuples 

59 * if set to "VERBOSE" (default) the HDF5 back trace is 

60 stored in the :attr:`HDF5ExtError.h5backtrace` attribute 

61 and also included in the string representation of the 

62 exception 

63 * if not set (or set to None) the default policy is used 

64 (see :attr:`HDF5ExtError.DEFAULT_H5_BACKTRACE_POLICY`) 

65 

66 """ 

67 

68 # NOTE: in order to avoid circular dependencies between modules the 

69 # _dump_h5_backtrace method is set at initialization time in 

70 # the utilsExtenion. 

71 _dump_h5_backtrace = None 

72 

73 DEFAULT_H5_BACKTRACE_POLICY = "VERBOSE" 

74 """Default policy for HDF5 backtrace handling 

75 

76 * if set to False the HDF5 back trace is ignored and the 

77 :attr:`HDF5ExtError.h5backtrace` attribute is set to None 

78 * if set to True the back trace is retrieved from the HDF5 

79 library and stored in the :attr:`HDF5ExtError.h5backtrace` 

80 attribute as a list of tuples 

81 * if set to "VERBOSE" (default) the HDF5 back trace is 

82 stored in the :attr:`HDF5ExtError.h5backtrace` attribute 

83 and also included in the string representation of the 

84 exception 

85 

86 This parameter can be set using the 

87 :envvar:`PT_DEFAULT_H5_BACKTRACE_POLICY` environment variable. 

88 Allowed values are "IGNORE" (or "FALSE"), "SAVE" (or "TRUE") and 

89 "VERBOSE" to set the policy to False, True and "VERBOSE" 

90 respectively. The special value "DEFAULT" can be used to reset 

91 the policy to the default value 

92 

93 .. versionadded:: 2.4 

94 """ 

95 

96 @classmethod 

97 def set_policy_from_env(cls): 

98 envmap = { 

99 "IGNORE": False, 

100 "FALSE": False, 

101 "SAVE": True, 

102 "TRUE": True, 

103 "VERBOSE": "VERBOSE", 

104 "DEFAULT": "VERBOSE", 

105 } 

106 oldvalue = cls.DEFAULT_H5_BACKTRACE_POLICY 

107 envvalue = os.environ.get("PT_DEFAULT_H5_BACKTRACE_POLICY", "DEFAULT") 

108 try: 

109 newvalue = envmap[envvalue.upper()] 

110 except KeyError: 

111 warnings.warn("Invalid value for the environment variable " 

112 "'PT_DEFAULT_H5_BACKTRACE_POLICY'. The default " 

113 "policy for HDF5 back trace management in PyTables " 

114 "will be: '%s'" % oldvalue) 

115 else: 

116 cls.DEFAULT_H5_BACKTRACE_POLICY = newvalue 

117 

118 return oldvalue 

119 

120 def __init__(self, *args, **kargs): 

121 

122 super().__init__(*args) 

123 

124 self._h5bt_policy = kargs.get('h5bt', self.DEFAULT_H5_BACKTRACE_POLICY) 

125 

126 if self._h5bt_policy and self._dump_h5_backtrace is not None: 

127 self.h5backtrace = self._dump_h5_backtrace() 

128 """HDF5 back trace. 

129 

130 Contains the HDF5 back trace as a (possibly empty) list of 

131 tuples. Each tuple has the following format:: 

132 

133 (filename, line number, function name, text) 

134 

135 Depending on the value of the *h5bt* parameter passed to the 

136 initializer the h5backtrace attribute can be set to None. 

137 This means that the HDF5 back trace has been simply ignored 

138 (not retrieved from the HDF5 C library error stack) or that 

139 there has been an error (silently ignored) during the HDF5 back 

140 trace retrieval. 

141 

142 .. versionadded:: 2.4 

143 

144 See Also 

145 -------- 

146 traceback.format_list : :func:`traceback.format_list` 

147 

148 """ 

149 

150 # XXX: check _dump_h5_backtrace failures 

151 else: 

152 self.h5backtrace = None 

153 

154 def __str__(self): 

155 """Returns a sting representation of the exception. 

156 

157 The actual result depends on policy set in the initializer 

158 :meth:`HDF5ExtError.__init__`. 

159 

160 .. versionadded:: 2.4 

161 

162 """ 

163 

164 verbose = bool(self._h5bt_policy in ('VERBOSE', 'verbose')) 

165 

166 if verbose and self.h5backtrace: 

167 bt = "\n".join([ 

168 "HDF5 error back trace\n", 

169 self.format_h5_backtrace(), 

170 "End of HDF5 error back trace" 

171 ]) 

172 

173 if len(self.args) == 1 and isinstance(self.args[0], str): 

174 msg = super().__str__() 

175 msg = f"{bt}\n\n{msg}" 

176 elif self.h5backtrace[-1][-1]: 

177 msg = f"{bt}\n\n{self.h5backtrace[-1][-1]}" 

178 else: 

179 msg = bt 

180 else: 

181 msg = super().__str__() 

182 

183 return msg 

184 

185 def format_h5_backtrace(self, backtrace=None): 

186 """Convert the HDF5 trace back represented as a list of tuples. 

187 (see :attr:`HDF5ExtError.h5backtrace`) into a string. 

188 

189 .. versionadded:: 2.4 

190 

191 """ 

192 if backtrace is None: 

193 backtrace = self.h5backtrace 

194 

195 if backtrace is None: 

196 return 'No HDF5 back trace available' 

197 else: 

198 return ''.join(traceback.format_list(backtrace)) 

199 

200 

201# Initialize the policy for HDF5 back trace handling 

202HDF5ExtError.set_policy_from_env() 

203 

204 

205# The following exceptions are concretions of the ``ValueError`` exceptions 

206# raised by ``file`` objects on certain operations. 

207 

208class ClosedNodeError(ValueError): 

209 """The operation can not be completed because the node is closed. 

210 

211 For instance, listing the children of a closed group is not allowed. 

212 

213 """ 

214 

215 pass 

216 

217 

218class ClosedFileError(ValueError): 

219 """The operation can not be completed because the hosting file is closed. 

220 

221 For instance, getting an existing node from a closed file is not 

222 allowed. 

223 

224 """ 

225 

226 pass 

227 

228 

229class FileModeError(ValueError): 

230 """The operation can not be carried out because the mode in which the 

231 hosting file is opened is not adequate. 

232 

233 For instance, removing an existing leaf from a read-only file is not 

234 allowed. 

235 

236 """ 

237 

238 pass 

239 

240 

241class NodeError(AttributeError, LookupError): 

242 """Invalid hierarchy manipulation operation requested. 

243 

244 This exception is raised when the user requests an operation on the 

245 hierarchy which can not be run because of the current layout of the 

246 tree. This includes accessing nonexistent nodes, moving or copying 

247 or creating over an existing node, non-recursively removing groups 

248 with children, and other similarly invalid operations. 

249 

250 A node in a PyTables database cannot be simply overwritten by 

251 replacing it. Instead, the old node must be removed explicitely 

252 before another one can take its place. This is done to protect 

253 interactive users from inadvertedly deleting whole trees of data by 

254 a single erroneous command. 

255 

256 """ 

257 

258 pass 

259 

260 

261class NoSuchNodeError(NodeError): 

262 """An operation was requested on a node that does not exist. 

263 

264 This exception is raised when an operation gets a path name or a 

265 ``(where, name)`` pair leading to a nonexistent node. 

266 

267 """ 

268 

269 pass 

270 

271 

272class UndoRedoError(Exception): 

273 """Problems with doing/redoing actions with Undo/Redo feature. 

274 

275 This exception indicates a problem related to the Undo/Redo 

276 mechanism, such as trying to undo or redo actions with this 

277 mechanism disabled, or going to a nonexistent mark. 

278 

279 """ 

280 

281 pass 

282 

283 

284class UndoRedoWarning(Warning): 

285 """Issued when an action not supporting Undo/Redo is run. 

286 

287 This warning is only shown when the Undo/Redo mechanism is enabled. 

288 

289 """ 

290 

291 pass 

292 

293 

294class NaturalNameWarning(Warning): 

295 """Issued when a non-pythonic name is given for a node. 

296 

297 This is not an error and may even be very useful in certain 

298 contexts, but one should be aware that such nodes cannot be 

299 accessed using natural naming (instead, ``getattr()`` must be 

300 used explicitly). 

301 """ 

302 

303 pass 

304 

305 

306class PerformanceWarning(Warning): 

307 """Warning for operations which may cause a performance drop. 

308 

309 This warning is issued when an operation is made on the database 

310 which may cause it to slow down on future operations (i.e. making 

311 the node tree grow too much). 

312 

313 """ 

314 

315 pass 

316 

317 

318class FlavorError(ValueError): 

319 """Unsupported or unavailable flavor or flavor conversion. 

320 

321 This exception is raised when an unsupported or unavailable flavor 

322 is given to a dataset, or when a conversion of data between two 

323 given flavors is not supported nor available. 

324 

325 """ 

326 

327 pass 

328 

329 

330class FlavorWarning(Warning): 

331 """Unsupported or unavailable flavor conversion. 

332 

333 This warning is issued when a conversion of data between two given 

334 flavors is not supported nor available, and raising an error would 

335 render the data inaccessible (e.g. on a dataset of an unavailable 

336 flavor in a read-only file). 

337 

338 See the `FlavorError` class for more information. 

339 

340 """ 

341 

342 pass 

343 

344 

345class FiltersWarning(Warning): 

346 """Unavailable filters. 

347 

348 This warning is issued when a valid filter is specified but it is 

349 not available in the system. It may mean that an available default 

350 filter is to be used instead. 

351 

352 """ 

353 

354 pass 

355 

356 

357class OldIndexWarning(Warning): 

358 """Unsupported index format. 

359 

360 This warning is issued when an index in an unsupported format is 

361 found. The index will be marked as invalid and will behave as if 

362 doesn't exist. 

363 

364 """ 

365 

366 pass 

367 

368 

369class DataTypeWarning(Warning): 

370 """Unsupported data type. 

371 

372 This warning is issued when an unsupported HDF5 data type is found 

373 (normally in a file created with other tool than PyTables). 

374 

375 """ 

376 

377 pass 

378 

379 

380class ExperimentalFeatureWarning(Warning): 

381 """Generic warning for experimental features. 

382 

383 This warning is issued when using a functionality that is still 

384 experimental and that users have to use with care. 

385 

386 """ 

387 pass 

388 

389 

390class UnclosedFileWarning(Warning): 

391 """Warning raised when there are still open files at program exit 

392 

393 Pytables will close remaining open files at exit, but raise  

394 this warning. 

395 """ 

396 pass