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
« 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."""
3import os
4import warnings
5import traceback
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]
29__docformat__ = 'reStructuredText'
30"""The format of documentation strings in this module."""
33class HDF5ExtError(RuntimeError):
34 """A low level HDF5 operation failed.
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.
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`).
44 .. versionchanged:: 2.4
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.
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`)
66 """
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
73 DEFAULT_H5_BACKTRACE_POLICY = "VERBOSE"
74 """Default policy for HDF5 backtrace handling
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
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
93 .. versionadded:: 2.4
94 """
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
118 return oldvalue
120 def __init__(self, *args, **kargs):
122 super().__init__(*args)
124 self._h5bt_policy = kargs.get('h5bt', self.DEFAULT_H5_BACKTRACE_POLICY)
126 if self._h5bt_policy and self._dump_h5_backtrace is not None:
127 self.h5backtrace = self._dump_h5_backtrace()
128 """HDF5 back trace.
130 Contains the HDF5 back trace as a (possibly empty) list of
131 tuples. Each tuple has the following format::
133 (filename, line number, function name, text)
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.
142 .. versionadded:: 2.4
144 See Also
145 --------
146 traceback.format_list : :func:`traceback.format_list`
148 """
150 # XXX: check _dump_h5_backtrace failures
151 else:
152 self.h5backtrace = None
154 def __str__(self):
155 """Returns a sting representation of the exception.
157 The actual result depends on policy set in the initializer
158 :meth:`HDF5ExtError.__init__`.
160 .. versionadded:: 2.4
162 """
164 verbose = bool(self._h5bt_policy in ('VERBOSE', 'verbose'))
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 ])
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__()
183 return msg
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.
189 .. versionadded:: 2.4
191 """
192 if backtrace is None:
193 backtrace = self.h5backtrace
195 if backtrace is None:
196 return 'No HDF5 back trace available'
197 else:
198 return ''.join(traceback.format_list(backtrace))
201# Initialize the policy for HDF5 back trace handling
202HDF5ExtError.set_policy_from_env()
205# The following exceptions are concretions of the ``ValueError`` exceptions
206# raised by ``file`` objects on certain operations.
208class ClosedNodeError(ValueError):
209 """The operation can not be completed because the node is closed.
211 For instance, listing the children of a closed group is not allowed.
213 """
215 pass
218class ClosedFileError(ValueError):
219 """The operation can not be completed because the hosting file is closed.
221 For instance, getting an existing node from a closed file is not
222 allowed.
224 """
226 pass
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.
233 For instance, removing an existing leaf from a read-only file is not
234 allowed.
236 """
238 pass
241class NodeError(AttributeError, LookupError):
242 """Invalid hierarchy manipulation operation requested.
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.
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.
256 """
258 pass
261class NoSuchNodeError(NodeError):
262 """An operation was requested on a node that does not exist.
264 This exception is raised when an operation gets a path name or a
265 ``(where, name)`` pair leading to a nonexistent node.
267 """
269 pass
272class UndoRedoError(Exception):
273 """Problems with doing/redoing actions with Undo/Redo feature.
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.
279 """
281 pass
284class UndoRedoWarning(Warning):
285 """Issued when an action not supporting Undo/Redo is run.
287 This warning is only shown when the Undo/Redo mechanism is enabled.
289 """
291 pass
294class NaturalNameWarning(Warning):
295 """Issued when a non-pythonic name is given for a node.
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 """
303 pass
306class PerformanceWarning(Warning):
307 """Warning for operations which may cause a performance drop.
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).
313 """
315 pass
318class FlavorError(ValueError):
319 """Unsupported or unavailable flavor or flavor conversion.
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.
325 """
327 pass
330class FlavorWarning(Warning):
331 """Unsupported or unavailable flavor conversion.
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).
338 See the `FlavorError` class for more information.
340 """
342 pass
345class FiltersWarning(Warning):
346 """Unavailable filters.
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.
352 """
354 pass
357class OldIndexWarning(Warning):
358 """Unsupported index format.
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.
364 """
366 pass
369class DataTypeWarning(Warning):
370 """Unsupported data type.
372 This warning is issued when an unsupported HDF5 data type is found
373 (normally in a file created with other tool than PyTables).
375 """
377 pass
380class ExperimentalFeatureWarning(Warning):
381 """Generic warning for experimental features.
383 This warning is issued when using a functionality that is still
384 experimental and that users have to use with care.
386 """
387 pass
390class UnclosedFileWarning(Warning):
391 """Warning raised when there are still open files at program exit
393 Pytables will close remaining open files at exit, but raise
394 this warning.
395 """
396 pass