SciFile-Core 0.0.1__py3-none-any.whl
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- scifile_core/__init__.py +111 -0
- scifile_core/_content.py +490 -0
- scifile_core/_diagnostic.py +322 -0
- scifile_core/_exception.py +221 -0
- scifile_core/_io.py +705 -0
- scifile_core/_mapping.py +139 -0
- scifile_core/_model.py +1056 -0
- scifile_core/_number.py +41 -0
- scifile_core/_optional.py +40 -0
- scifile_core/py.typed +0 -0
- scifile_core/testing.py +653 -0
- scifile_core/wording.py +454 -0
- scifile_core-0.0.1.dist-info/METADATA +6 -0
- scifile_core-0.0.1.dist-info/RECORD +16 -0
- scifile_core-0.0.1.dist-info/WHEEL +5 -0
- scifile_core-0.0.1.dist-info/top_level.txt +1 -0
|
@@ -0,0 +1,322 @@
|
|
|
1
|
+
"""Diagnostics: the problems that reading or checking a file finds."""
|
|
2
|
+
|
|
3
|
+
from __future__ import annotations
|
|
4
|
+
|
|
5
|
+
import enum
|
|
6
|
+
import json
|
|
7
|
+
import math
|
|
8
|
+
from collections.abc import Mapping
|
|
9
|
+
from dataclasses import dataclass
|
|
10
|
+
from typing import TYPE_CHECKING, Self
|
|
11
|
+
|
|
12
|
+
from scifile_core._optional import imported_numpy
|
|
13
|
+
|
|
14
|
+
if TYPE_CHECKING:
|
|
15
|
+
from collections.abc import Iterable
|
|
16
|
+
|
|
17
|
+
PARSER = "parser"
|
|
18
|
+
"""Source of the diagnostics that reading a file records."""
|
|
19
|
+
|
|
20
|
+
VERIFIER = "verifier"
|
|
21
|
+
"""Source of the diagnostics that checking the rules of a format records."""
|
|
22
|
+
|
|
23
|
+
|
|
24
|
+
class DiagnosticSeverity(enum.IntEnum):
|
|
25
|
+
"""How much a problem affects the data of a file.
|
|
26
|
+
|
|
27
|
+
The levels from `INFO` to `CRITICAL` are those of CIFFile. A level
|
|
28
|
+
compares with an `int`, so that ``severity >= 3`` and
|
|
29
|
+
``severity >= DiagnosticSeverity.ERROR`` are the same.
|
|
30
|
+
"""
|
|
31
|
+
|
|
32
|
+
NONE = 0
|
|
33
|
+
"""The highest severity of no diagnostics, which no diagnostic has; it is
|
|
34
|
+
false, as 0 is."""
|
|
35
|
+
|
|
36
|
+
INFO = 1
|
|
37
|
+
"""A minor problem that does not affect the data."""
|
|
38
|
+
|
|
39
|
+
WARNING = 2
|
|
40
|
+
"""A problem that may affect how the data are read; they stay usable."""
|
|
41
|
+
|
|
42
|
+
ERROR = 3
|
|
43
|
+
"""A problem that affects the integrity of the data."""
|
|
44
|
+
|
|
45
|
+
CRITICAL = 4
|
|
46
|
+
"""A problem that prevents the file from being read."""
|
|
47
|
+
|
|
48
|
+
|
|
49
|
+
class DiagnosticType(enum.Enum):
|
|
50
|
+
"""Base of the types of diagnostics of a package.
|
|
51
|
+
|
|
52
|
+
The value of each member is its label and its default severity,
|
|
53
|
+
as in ``VALUE_INVALID = ("value_invalid", DiagnosticSeverity.ERROR)``.
|
|
54
|
+
A package's ``DiagnosticType`` subclasses this class.
|
|
55
|
+
"""
|
|
56
|
+
|
|
57
|
+
_value_: tuple[str, DiagnosticSeverity]
|
|
58
|
+
|
|
59
|
+
@property
|
|
60
|
+
def label(self) -> str:
|
|
61
|
+
"""Name of the type, as diagnostics and messages spell it."""
|
|
62
|
+
return self._value_[0]
|
|
63
|
+
|
|
64
|
+
@property
|
|
65
|
+
def severity(self) -> DiagnosticSeverity:
|
|
66
|
+
"""Severity of a diagnostic of this type, unless one is given."""
|
|
67
|
+
return self._value_[1]
|
|
68
|
+
|
|
69
|
+
|
|
70
|
+
class SharedDiagnosticType(DiagnosticType):
|
|
71
|
+
"""Types of diagnostics that several formats share.
|
|
72
|
+
|
|
73
|
+
A package's ``DiagnosticType`` repeats each of these members that it uses,
|
|
74
|
+
with the same name, label and severity, as in
|
|
75
|
+
``FIELD_UNKNOWN = SharedDiagnosticType.FIELD_UNKNOWN.value``,
|
|
76
|
+
so that one problem has one label in every package.
|
|
77
|
+
"""
|
|
78
|
+
|
|
79
|
+
UNDECODABLE_TEXT = ("undecodable_text", DiagnosticSeverity.ERROR)
|
|
80
|
+
"""Text holds bytes that the encoding of the read cannot decode."""
|
|
81
|
+
|
|
82
|
+
FILE_INCOMPLETE = ("file_incomplete", DiagnosticSeverity.CRITICAL)
|
|
83
|
+
"""The file ends before the data that it declares."""
|
|
84
|
+
|
|
85
|
+
TRAILING_DATA = ("trailing_data", DiagnosticSeverity.WARNING)
|
|
86
|
+
"""The file, or a line, goes on after the data that it declares or takes."""
|
|
87
|
+
|
|
88
|
+
MARKER_MISSING = ("marker_missing", DiagnosticSeverity.WARNING)
|
|
89
|
+
"""The marker that identifies the format is absent or differs."""
|
|
90
|
+
|
|
91
|
+
FIELD_MISSING = ("field_missing", DiagnosticSeverity.ERROR)
|
|
92
|
+
"""A required field, such as a header key, is absent."""
|
|
93
|
+
|
|
94
|
+
FIELD_DUPLICATE = ("field_duplicate", DiagnosticSeverity.ERROR)
|
|
95
|
+
"""A field that may occur once occurs again."""
|
|
96
|
+
|
|
97
|
+
FIELD_UNKNOWN = ("field_unknown", DiagnosticSeverity.WARNING)
|
|
98
|
+
"""A field is not one that the format defines."""
|
|
99
|
+
|
|
100
|
+
FIELD_ORDER = ("field_order", DiagnosticSeverity.ERROR)
|
|
101
|
+
"""A field is out of the order that the format prescribes."""
|
|
102
|
+
|
|
103
|
+
HEADER_GAP = ("header_gap", DiagnosticSeverity.ERROR)
|
|
104
|
+
"""A line that holds no field, such as a blank line, a comment or an
|
|
105
|
+
ignored line, sits inside a header that the format reads by position.
|
|
106
|
+
|
|
107
|
+
The diagnostic is on the line of the field that follows the gap, which
|
|
108
|
+
a reader by position takes for another field. The line of the gap gets
|
|
109
|
+
only the diagnostic of its own problem, if it has one.
|
|
110
|
+
"""
|
|
111
|
+
|
|
112
|
+
VALUE_INVALID = ("value_invalid", DiagnosticSeverity.ERROR)
|
|
113
|
+
"""A value cannot be read, or breaks a rule of the format."""
|
|
114
|
+
|
|
115
|
+
COUNT_MISMATCH = ("count_mismatch", DiagnosticSeverity.ERROR)
|
|
116
|
+
"""The number of values differs from the number that the file declares."""
|
|
117
|
+
|
|
118
|
+
FEATURE_UNSUPPORTED = ("feature_unsupported", DiagnosticSeverity.ERROR)
|
|
119
|
+
"""The format defines a feature that the package does not keep."""
|
|
120
|
+
|
|
121
|
+
|
|
122
|
+
@dataclass(frozen=True, slots=True, kw_only=True)
|
|
123
|
+
class Diagnostic:
|
|
124
|
+
"""A problem that reading or checking a file found.
|
|
125
|
+
|
|
126
|
+
The names of the fields are those of the columns of CIFFile's
|
|
127
|
+
``ERROR_SCHEMA`` where the two agree; the location is the field, line and
|
|
128
|
+
byte offset of a flat file instead of CIFFile's block, frame and
|
|
129
|
+
category.
|
|
130
|
+
|
|
131
|
+
Attributes
|
|
132
|
+
----------
|
|
133
|
+
type
|
|
134
|
+
Type of the problem.
|
|
135
|
+
severity
|
|
136
|
+
How much the problem affects the data; never `DiagnosticSeverity.NONE`.
|
|
137
|
+
source
|
|
138
|
+
What found the problem: ``"parser"``, ``"verifier"``, or a source of the
|
|
139
|
+
package's own.
|
|
140
|
+
details
|
|
141
|
+
Message for a reader.
|
|
142
|
+
field
|
|
143
|
+
Field of the file that holds the problem, as the specification of
|
|
144
|
+
the format spells it, such as a header key; a value without a key
|
|
145
|
+
is given by the name of the model's field.
|
|
146
|
+
line
|
|
147
|
+
Line of a text file that holds the problem, counted from 1.
|
|
148
|
+
offset
|
|
149
|
+
Byte at which the problem starts, counted from 0: of a binary file,
|
|
150
|
+
or of the bytes of a text file after gzip is decompressed, as for
|
|
151
|
+
undecodable text.
|
|
152
|
+
context
|
|
153
|
+
JSON object with what helps to fix the problem, such as the rejected
|
|
154
|
+
value and what was expected: ``{"value": -1, "expected": ">= 0"}``.
|
|
155
|
+
"""
|
|
156
|
+
|
|
157
|
+
type: DiagnosticType
|
|
158
|
+
severity: DiagnosticSeverity
|
|
159
|
+
source: str
|
|
160
|
+
details: str
|
|
161
|
+
field: str | None = None
|
|
162
|
+
line: int | None = None
|
|
163
|
+
offset: int | None = None
|
|
164
|
+
context: str | None = None
|
|
165
|
+
|
|
166
|
+
def __post_init__(self) -> None:
|
|
167
|
+
"""Reject `DiagnosticSeverity.NONE`, the severity of no diagnostic.
|
|
168
|
+
|
|
169
|
+
Raises
|
|
170
|
+
------
|
|
171
|
+
InputError
|
|
172
|
+
If the severity is `DiagnosticSeverity.NONE`.
|
|
173
|
+
"""
|
|
174
|
+
if self.severity == DiagnosticSeverity.NONE:
|
|
175
|
+
from scifile_core._exception import InputError # noqa: PLC0415 - _exception imports this module
|
|
176
|
+
|
|
177
|
+
raise InputError(
|
|
178
|
+
parameter="severity",
|
|
179
|
+
argument=self.severity,
|
|
180
|
+
message="is the severity of no diagnostic",
|
|
181
|
+
)
|
|
182
|
+
|
|
183
|
+
def to_dict(self) -> dict[str, str | int | None]:
|
|
184
|
+
"""Return the diagnostic as a row of plain values.
|
|
185
|
+
|
|
186
|
+
The type is given by its label and the severity by its number,
|
|
187
|
+
so that a list of rows makes a table, as in
|
|
188
|
+
``polars.DataFrame([d.to_dict() for d in model.diagnostics])``.
|
|
189
|
+
|
|
190
|
+
Returns
|
|
191
|
+
-------
|
|
192
|
+
The fields of the diagnostic.
|
|
193
|
+
"""
|
|
194
|
+
return {
|
|
195
|
+
"source": self.source,
|
|
196
|
+
"severity": int(self.severity),
|
|
197
|
+
"type": self.type.label,
|
|
198
|
+
"field": self.field,
|
|
199
|
+
"line": self.line,
|
|
200
|
+
"offset": self.offset,
|
|
201
|
+
"details": self.details,
|
|
202
|
+
"context": self.context,
|
|
203
|
+
}
|
|
204
|
+
|
|
205
|
+
|
|
206
|
+
def create_diagnostic( # noqa: PLR0913 - one keyword for each field of a diagnostic
|
|
207
|
+
diagnostic_type: DiagnosticType,
|
|
208
|
+
details: str,
|
|
209
|
+
*,
|
|
210
|
+
source: str = PARSER,
|
|
211
|
+
severity: DiagnosticSeverity | None = None,
|
|
212
|
+
field: str | None = None,
|
|
213
|
+
line: int | None = None,
|
|
214
|
+
offset: int | None = None,
|
|
215
|
+
context: Mapping[str, object] | None = None,
|
|
216
|
+
) -> Diagnostic:
|
|
217
|
+
"""Create a diagnostic whose severity is that of its type.
|
|
218
|
+
|
|
219
|
+
A package builds each diagnostic that it reports with this function,
|
|
220
|
+
which a user of the package has no need of.
|
|
221
|
+
|
|
222
|
+
Parameters
|
|
223
|
+
----------
|
|
224
|
+
diagnostic_type
|
|
225
|
+
Type of the problem.
|
|
226
|
+
details
|
|
227
|
+
Message for a reader.
|
|
228
|
+
source
|
|
229
|
+
What found the problem.
|
|
230
|
+
severity
|
|
231
|
+
Severity that replaces the default of the type.
|
|
232
|
+
field
|
|
233
|
+
Field of the file that holds the problem.
|
|
234
|
+
line
|
|
235
|
+
Line of a text file that holds the problem, counted from 1.
|
|
236
|
+
offset
|
|
237
|
+
Byte at which the problem starts, counted from 0.
|
|
238
|
+
context
|
|
239
|
+
What helps to fix the problem, such as ``{"value": ...,
|
|
240
|
+
"expected": ...}``. It is written as a JSON object: a NumPy
|
|
241
|
+
value as the Python value that it holds, a float that is not
|
|
242
|
+
finite as a string such as ``"nan"``, a key as a string, a
|
|
243
|
+
sequence as a list, and another value that JSON has no form for
|
|
244
|
+
as its `str`.
|
|
245
|
+
|
|
246
|
+
Returns
|
|
247
|
+
-------
|
|
248
|
+
The diagnostic.
|
|
249
|
+
|
|
250
|
+
Raises
|
|
251
|
+
------
|
|
252
|
+
InputError
|
|
253
|
+
If the severity, given or of the type, is `DiagnosticSeverity.NONE`.
|
|
254
|
+
"""
|
|
255
|
+
return Diagnostic(
|
|
256
|
+
type=diagnostic_type,
|
|
257
|
+
severity=diagnostic_type.severity if severity is None else severity,
|
|
258
|
+
source=source,
|
|
259
|
+
details=details,
|
|
260
|
+
field=field,
|
|
261
|
+
line=line,
|
|
262
|
+
offset=offset,
|
|
263
|
+
context=None if context is None else _json(context),
|
|
264
|
+
)
|
|
265
|
+
|
|
266
|
+
|
|
267
|
+
class Diagnostics(tuple[Diagnostic, ...]):
|
|
268
|
+
"""The diagnostics of a model or a read, in order.
|
|
269
|
+
|
|
270
|
+
It is a tuple in every respect but one, the property `max_severity`: it
|
|
271
|
+
equals a tuple of the same diagnostics and hashes as one, and a slice or
|
|
272
|
+
a sum of it is a plain tuple.
|
|
273
|
+
"""
|
|
274
|
+
|
|
275
|
+
__slots__ = ()
|
|
276
|
+
|
|
277
|
+
def __new__(cls, diagnostics: Iterable[Diagnostic] = ()) -> Self:
|
|
278
|
+
"""Create the sequence.
|
|
279
|
+
|
|
280
|
+
Parameters
|
|
281
|
+
----------
|
|
282
|
+
diagnostics
|
|
283
|
+
The diagnostics, in order.
|
|
284
|
+
"""
|
|
285
|
+
return super().__new__(cls, diagnostics)
|
|
286
|
+
|
|
287
|
+
@property
|
|
288
|
+
def max_severity(self) -> DiagnosticSeverity:
|
|
289
|
+
"""Highest severity of the diagnostics, or `DiagnosticSeverity.NONE`."""
|
|
290
|
+
return max(
|
|
291
|
+
(diagnostic.severity for diagnostic in self),
|
|
292
|
+
default=DiagnosticSeverity.NONE,
|
|
293
|
+
)
|
|
294
|
+
|
|
295
|
+
|
|
296
|
+
def _json(context: Mapping[str, object]) -> str:
|
|
297
|
+
"""Return a context as a JSON object that every parser of JSON reads."""
|
|
298
|
+
return json.dumps(_plain(context), allow_nan=False)
|
|
299
|
+
|
|
300
|
+
|
|
301
|
+
def _plain(value: object) -> object:
|
|
302
|
+
"""Return a value as one that JSON has a form for.
|
|
303
|
+
|
|
304
|
+
A NumPy value becomes the Python value that it holds, a float that is not
|
|
305
|
+
finite the string of its value, such as ``"nan"``, a mapping an object
|
|
306
|
+
with string keys, a sequence a list, and anything else its `str`.
|
|
307
|
+
"""
|
|
308
|
+
kind = type(value)
|
|
309
|
+
if kind is str or kind is int or kind is bool or value is None:
|
|
310
|
+
return value
|
|
311
|
+
np = imported_numpy()
|
|
312
|
+
if np is not None and isinstance(value, np.generic | np.ndarray):
|
|
313
|
+
value = value.tolist()
|
|
314
|
+
if isinstance(value, float) and not math.isfinite(value):
|
|
315
|
+
return str(value)
|
|
316
|
+
if value is None or isinstance(value, bool | int | float | str):
|
|
317
|
+
return value
|
|
318
|
+
if isinstance(value, Mapping):
|
|
319
|
+
return {str(key): _plain(item) for key, item in value.items()}
|
|
320
|
+
if isinstance(value, list | tuple):
|
|
321
|
+
return [_plain(item) for item in value]
|
|
322
|
+
return str(value)
|
|
@@ -0,0 +1,221 @@
|
|
|
1
|
+
"""The exceptions of the SciFile packages.
|
|
2
|
+
|
|
3
|
+
Each package subclasses these with its own `Error`, `InputError` and
|
|
4
|
+
`ReadError`, so that ``except scifile_core.Error`` catches every package.
|
|
5
|
+
"""
|
|
6
|
+
|
|
7
|
+
from __future__ import annotations
|
|
8
|
+
|
|
9
|
+
import math
|
|
10
|
+
import reprlib
|
|
11
|
+
from collections.abc import Sized
|
|
12
|
+
from typing import TYPE_CHECKING, Self
|
|
13
|
+
|
|
14
|
+
from scifile_core._diagnostic import Diagnostics
|
|
15
|
+
from scifile_core._optional import imported_numpy
|
|
16
|
+
|
|
17
|
+
if TYPE_CHECKING:
|
|
18
|
+
from collections.abc import Callable, Iterable
|
|
19
|
+
|
|
20
|
+
from scifile_core._diagnostic import Diagnostic
|
|
21
|
+
|
|
22
|
+
_MAX_SHOWN_CHARACTERS = 256
|
|
23
|
+
"""Longest single-line string that a message shows in full."""
|
|
24
|
+
|
|
25
|
+
_MAX_SHOWN_ITEMS = 64
|
|
26
|
+
"""Most items of a collection that a message shows."""
|
|
27
|
+
|
|
28
|
+
_SHORT = reprlib.Repr(
|
|
29
|
+
maxlevel=3,
|
|
30
|
+
maxtuple=_MAX_SHOWN_ITEMS,
|
|
31
|
+
maxlist=_MAX_SHOWN_ITEMS,
|
|
32
|
+
maxarray=_MAX_SHOWN_ITEMS,
|
|
33
|
+
maxdict=_MAX_SHOWN_ITEMS,
|
|
34
|
+
maxset=_MAX_SHOWN_ITEMS,
|
|
35
|
+
maxfrozenset=_MAX_SHOWN_ITEMS,
|
|
36
|
+
maxdeque=_MAX_SHOWN_ITEMS,
|
|
37
|
+
maxstring=_MAX_SHOWN_CHARACTERS,
|
|
38
|
+
maxlong=_MAX_SHOWN_CHARACTERS,
|
|
39
|
+
maxother=_MAX_SHOWN_CHARACTERS,
|
|
40
|
+
)
|
|
41
|
+
"""The `repr` of a collection, with the collections in it shortened."""
|
|
42
|
+
|
|
43
|
+
|
|
44
|
+
class Error(Exception):
|
|
45
|
+
"""Base of every exception of the SciFile packages.
|
|
46
|
+
|
|
47
|
+
Attributes
|
|
48
|
+
----------
|
|
49
|
+
message
|
|
50
|
+
Message of the exception.
|
|
51
|
+
"""
|
|
52
|
+
|
|
53
|
+
def __init__(self, message: str) -> None:
|
|
54
|
+
"""Create the exception.
|
|
55
|
+
|
|
56
|
+
Parameters
|
|
57
|
+
----------
|
|
58
|
+
message
|
|
59
|
+
Message of the exception.
|
|
60
|
+
"""
|
|
61
|
+
super().__init__(message)
|
|
62
|
+
self.message = message
|
|
63
|
+
|
|
64
|
+
def __reduce__(
|
|
65
|
+
self,
|
|
66
|
+
) -> tuple[
|
|
67
|
+
Callable[..., Self],
|
|
68
|
+
tuple[type[Self], tuple[object, ...], dict[str, object]],
|
|
69
|
+
]:
|
|
70
|
+
"""Pickle the exception with its attributes.
|
|
71
|
+
|
|
72
|
+
An exception is unpickled without its constructor, whose parameters
|
|
73
|
+
differ from its arguments, so that it can cross the processes of
|
|
74
|
+
``multiprocessing``.
|
|
75
|
+
"""
|
|
76
|
+
return (_restore, (type(self), self.args, dict(vars(self))))
|
|
77
|
+
|
|
78
|
+
|
|
79
|
+
class InputError(Error, ValueError):
|
|
80
|
+
"""An argument that a function cannot accept.
|
|
81
|
+
|
|
82
|
+
The message names the parameter and the argument, without embedding a
|
|
83
|
+
large input: bytes are shown by their count, and a string with a line
|
|
84
|
+
break or more than 256 characters by its length.
|
|
85
|
+
|
|
86
|
+
Attributes
|
|
87
|
+
----------
|
|
88
|
+
parameter
|
|
89
|
+
Name of the parameter.
|
|
90
|
+
argument
|
|
91
|
+
The argument that was given.
|
|
92
|
+
"""
|
|
93
|
+
|
|
94
|
+
def __init__(self, parameter: str, argument: object, message: str) -> None:
|
|
95
|
+
"""Create the exception.
|
|
96
|
+
|
|
97
|
+
Parameters
|
|
98
|
+
----------
|
|
99
|
+
parameter
|
|
100
|
+
Name of the parameter.
|
|
101
|
+
argument
|
|
102
|
+
The argument that was given.
|
|
103
|
+
message
|
|
104
|
+
Why the argument cannot be accepted, as a clause that follows the
|
|
105
|
+
argument, such as ``"is no known text encoding"``.
|
|
106
|
+
"""
|
|
107
|
+
self.parameter = parameter
|
|
108
|
+
self.argument = argument
|
|
109
|
+
super().__init__(
|
|
110
|
+
f"Invalid argument {describe(argument)} for parameter"
|
|
111
|
+
f" {parameter!r}: {message}"
|
|
112
|
+
)
|
|
113
|
+
|
|
114
|
+
|
|
115
|
+
class ReadError(Error):
|
|
116
|
+
"""A file that leaves nothing to build a model from.
|
|
117
|
+
|
|
118
|
+
Only ``read`` raises it; a problem that leaves a model is a diagnostic
|
|
119
|
+
of the model instead.
|
|
120
|
+
|
|
121
|
+
Attributes
|
|
122
|
+
----------
|
|
123
|
+
diagnostics
|
|
124
|
+
Every diagnostic of the read so far.
|
|
125
|
+
"""
|
|
126
|
+
|
|
127
|
+
def __init__(
|
|
128
|
+
self, message: str, *, diagnostics: Iterable[Diagnostic]
|
|
129
|
+
) -> None:
|
|
130
|
+
"""Create the exception.
|
|
131
|
+
|
|
132
|
+
Parameters
|
|
133
|
+
----------
|
|
134
|
+
message
|
|
135
|
+
Message of the exception.
|
|
136
|
+
diagnostics
|
|
137
|
+
Every diagnostic of the read so far, in order.
|
|
138
|
+
"""
|
|
139
|
+
super().__init__(message)
|
|
140
|
+
self.diagnostics = Diagnostics(diagnostics)
|
|
141
|
+
|
|
142
|
+
|
|
143
|
+
def describe(argument: object) -> str:
|
|
144
|
+
"""Return how a message shows a value that it may not embed in full.
|
|
145
|
+
|
|
146
|
+
Parameters
|
|
147
|
+
----------
|
|
148
|
+
argument
|
|
149
|
+
The value.
|
|
150
|
+
|
|
151
|
+
Returns
|
|
152
|
+
-------
|
|
153
|
+
`<n bytes>` for bytes, `<str of n characters>` for a string with a line
|
|
154
|
+
break or whose `repr` has more than 256 characters, the type with the
|
|
155
|
+
shape or length of a collection of more than 64 items, such as
|
|
156
|
+
`<ndarray of shape (40, 40, 40)>` or `<list of 1000 items>`, and
|
|
157
|
+
otherwise the value's `repr`, if it has at most 256 characters, or its
|
|
158
|
+
type, such as `<int>` for an integer of more digits than Python writes.
|
|
159
|
+
The `repr` of a collection shortens the collections in it, as `reprlib`
|
|
160
|
+
does, so that it is never built in full. A NumPy scalar other than a
|
|
161
|
+
date or a time is shown as the Python value that it holds.
|
|
162
|
+
"""
|
|
163
|
+
np = imported_numpy()
|
|
164
|
+
if (
|
|
165
|
+
np is not None
|
|
166
|
+
and isinstance(argument, np.generic)
|
|
167
|
+
and not isinstance(argument, np.datetime64 | np.timedelta64)
|
|
168
|
+
):
|
|
169
|
+
argument = argument.item()
|
|
170
|
+
if isinstance(argument, bytes | bytearray | memoryview):
|
|
171
|
+
with memoryview(argument) as view:
|
|
172
|
+
return f"<{view.nbytes} bytes>"
|
|
173
|
+
if isinstance(argument, str):
|
|
174
|
+
long = len(argument) > _MAX_SHOWN_CHARACTERS
|
|
175
|
+
if long or "\n" in argument or "\r" in argument:
|
|
176
|
+
return f"<str of {len(argument)} characters>"
|
|
177
|
+
elif _items(argument) > _MAX_SHOWN_ITEMS:
|
|
178
|
+
return _summary(argument)
|
|
179
|
+
try:
|
|
180
|
+
shown = (
|
|
181
|
+
_SHORT.repr(argument)
|
|
182
|
+
if isinstance(argument, Sized) and not isinstance(argument, str)
|
|
183
|
+
else repr(argument)
|
|
184
|
+
)
|
|
185
|
+
except ValueError:
|
|
186
|
+
# An integer of more digits than Python converts to text.
|
|
187
|
+
shown = None
|
|
188
|
+
if shown is not None and len(shown) <= _MAX_SHOWN_CHARACTERS:
|
|
189
|
+
return shown
|
|
190
|
+
if isinstance(argument, str):
|
|
191
|
+
return f"<str of {len(argument)} characters>"
|
|
192
|
+
return _summary(argument)
|
|
193
|
+
|
|
194
|
+
|
|
195
|
+
def _items(argument: object) -> int:
|
|
196
|
+
"""Return the number of items of a collection, or 0 for another value."""
|
|
197
|
+
shape = getattr(argument, "shape", None)
|
|
198
|
+
if isinstance(shape, tuple):
|
|
199
|
+
return math.prod(shape)
|
|
200
|
+
return len(argument) if isinstance(argument, Sized) else 0
|
|
201
|
+
|
|
202
|
+
|
|
203
|
+
def _summary(argument: object) -> str:
|
|
204
|
+
"""Return the type of a value with its shape or its length."""
|
|
205
|
+
name = type(argument).__name__
|
|
206
|
+
shape = getattr(argument, "shape", None)
|
|
207
|
+
if isinstance(shape, tuple):
|
|
208
|
+
return f"<{name} of shape {shape}>"
|
|
209
|
+
if isinstance(argument, Sized):
|
|
210
|
+
count = len(argument)
|
|
211
|
+
return f"<{name} of {count} item{'' if count == 1 else 's'}>"
|
|
212
|
+
return f"<{name}>"
|
|
213
|
+
|
|
214
|
+
|
|
215
|
+
def _restore[E: Error](
|
|
216
|
+
cls: type[E], args: tuple[object, ...], state: dict[str, object]
|
|
217
|
+
) -> E:
|
|
218
|
+
"""Rebuild a pickled exception from its arguments and attributes."""
|
|
219
|
+
error = cls.__new__(cls, *args)
|
|
220
|
+
vars(error).update(state)
|
|
221
|
+
return error
|