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/_model.py ADDED
@@ -0,0 +1,1056 @@
1
+ """The base classes of the models, the field types and the write options."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import dataclasses
6
+ import operator
7
+ from types import MappingProxyType
8
+ from typing import (
9
+ TYPE_CHECKING,
10
+ Any,
11
+ ClassVar,
12
+ NamedTuple,
13
+ Protocol,
14
+ Self,
15
+ cast,
16
+ overload,
17
+ runtime_checkable,
18
+ )
19
+
20
+ from scifile_core._content import (
21
+ digests,
22
+ frozen,
23
+ frozen_value,
24
+ frozen_values,
25
+ is_plain,
26
+ same_values,
27
+ tuple_maker,
28
+ )
29
+ from scifile_core._diagnostic import Diagnostic, Diagnostics
30
+ from scifile_core._exception import InputError
31
+ from scifile_core._io import deliver_bytes, deliver_text
32
+ from scifile_core._mapping import map_of, maps_alive, written_file
33
+
34
+ if TYPE_CHECKING:
35
+ import os
36
+ from collections.abc import (
37
+ Callable,
38
+ Collection,
39
+ Iterable,
40
+ Mapping,
41
+ )
42
+ from collections.abc import Set as AbstractSet
43
+
44
+ from _typeshed import DataclassInstance
45
+ from numpy.typing import NDArray
46
+
47
+ from scifile_core._io import BinaryTarget, TextTarget
48
+ from scifile_core._mapping import FileMap
49
+
50
+ _LAYOUTS: dict[type[_Model], _Layout] = {}
51
+ """The fields of each class, looked up once."""
52
+
53
+
54
+ @dataclasses.dataclass(frozen=True, slots=True, kw_only=True)
55
+ class WriteConfig:
56
+ """Base of the write options of a package.
57
+
58
+ A package's ``WriteConfig`` subclasses this class as a frozen dataclass
59
+ whose fields are the options, each with a default:
60
+
61
+ .. code-block:: python
62
+
63
+ @dataclass(frozen=True, slots=True, kw_only=True)
64
+ class WriteConfig(WriteConfig):
65
+ _input_error = InputError
66
+ decimals: int = 3
67
+ """
68
+
69
+ _input_error: ClassVar[type[InputError]] = InputError
70
+ """The exception that a rejected option raises; a package sets its own."""
71
+
72
+ def replace(self, **changes: object) -> Self:
73
+ """Return a copy with some options changed.
74
+
75
+ Parameters
76
+ ----------
77
+ **changes
78
+ New values of options, by name.
79
+
80
+ Returns
81
+ -------
82
+ The copy.
83
+
84
+ Raises
85
+ ------
86
+ InputError
87
+ If a name is no option, or a value is no valid option; the
88
+ package's own `InputError`.
89
+ """
90
+ names = {option.name for option in dataclasses.fields(self)}
91
+ unknown = sorted(set(changes) - names)
92
+ if unknown:
93
+ message = f"names no option of {type(self).__name__}: {unknown}"
94
+ raise self._input_error(
95
+ parameter="changes", argument=changes, message=message
96
+ )
97
+ return dataclasses.replace(self, **changes)
98
+
99
+
100
+ class _Model:
101
+ """Base of the models of files and of the types of their fields.
102
+
103
+ It holds what `FileModel` and `FieldModel` share: validation, frozen
104
+ arrays, equality and hash of the content, copies and pickling. Its
105
+ methods are private, and each public class calls them from methods of
106
+ its own, so that the reference documents each class by itself, and
107
+ neither a model nor a field type is documented as the other.
108
+ """
109
+
110
+ __slots__ = ("_hash",)
111
+
112
+ _input_error: ClassVar[type[InputError]] = InputError
113
+ """The exception that a rejected argument raises; a package sets its own."""
114
+
115
+ _hash: int
116
+
117
+ def _validate(self) -> None:
118
+ """Validate and normalize the fields.
119
+
120
+ A subclass raises its `_input_error` for a value that it cannot
121
+ hold, and may replace a field with ``object.__setattr__``, such as a
122
+ tuple with an array, before the arrays are frozen.
123
+ """
124
+
125
+ @classmethod
126
+ def _keep_replace(cls) -> None:
127
+ """Give a new subclass the `__replace__` of `copy.replace`.
128
+
129
+ The dataclass decorator adds its own `__replace__` to a class that
130
+ has none, which would take any name; a class that has one keeps it,
131
+ so that `copy.replace` checks the names as `replace` does.
132
+ """
133
+ if "__replace__" not in vars(cls):
134
+ cast("Any", cls).__replace__ = _replace
135
+
136
+ def _settle(self) -> None:
137
+ """Validate the fields of a new value, then freeze its arrays."""
138
+ self._validate()
139
+ layout = _layout(type(self))
140
+ values = layout.values(self)
141
+ frozen = frozen_values(values)
142
+ if frozen is not values:
143
+ for name, value, kept in zip(
144
+ layout.fields, frozen, values, strict=True
145
+ ):
146
+ if value is not kept:
147
+ object.__setattr__(self, name, value)
148
+
149
+ def _changed(self, changes: Mapping[str, object]) -> Self:
150
+ """Return a validated copy with some fields changed.
151
+
152
+ Raises
153
+ ------
154
+ InputError
155
+ The package's input error, if a name is no field or a value is
156
+ invalid.
157
+ """
158
+ unknown = sorted(set(changes) - set(_layout(type(self)).init))
159
+ if unknown:
160
+ message = f"names no field of {type(self).__name__}: {unknown}"
161
+ raise self._input_error(
162
+ parameter="changes", argument=dict(changes), message=message
163
+ )
164
+ return cast("Self", dataclasses.replace(_dataclass(self), **changes))
165
+
166
+ def _init_fields(self) -> dict[str, Any]:
167
+ """Return the fields that the constructor takes, by name."""
168
+ return {name: getattr(self, name) for name in _layout(type(self)).init}
169
+
170
+ def _all_fields(self) -> dict[str, object]:
171
+ """Return every field, by name, as pickling keeps them."""
172
+ layout = _layout(type(self))
173
+ return dict(zip(layout.fields, layout.values(self), strict=True))
174
+
175
+ def _same(self, other: _Model) -> bool:
176
+ """Compare the content with that of another value of the same class."""
177
+ values = _layout(type(self)).values
178
+ return other is self or same_values(values(self), values(other))
179
+
180
+ def _content_hash(self) -> int:
181
+ """Return a hash of the content, computed once."""
182
+ cached: int | None = getattr(self, "_hash", None)
183
+ if cached is None:
184
+ values = digests(_layout(type(self)).values(self))
185
+ cached = hash((type(self).__qualname__, values))
186
+ object.__setattr__(self, "_hash", cached)
187
+ return cached
188
+
189
+
190
+ def _replace(
191
+ model: FileModel | FieldModel, /, **changes: object
192
+ ) -> FileModel | FieldModel:
193
+ """Return a copy with some fields changed, as `copy.replace` asks.
194
+
195
+ The copy is that of the method `replace`, which checks the names.
196
+ """
197
+ return model.replace(**changes)
198
+
199
+
200
+ class FileModel(_Model):
201
+ """Base of the models of the SciFile packages.
202
+
203
+ A model is a frozen, slotted dataclass that subclasses `TextFileModel` or
204
+ `BinaryFileModel`, with ``eq=False`` so that it keeps the equality and the
205
+ hash of this class:
206
+
207
+ .. code-block:: python
208
+
209
+ @dataclass(frozen=True, slots=True, eq=False)
210
+ class File(TextFileModel[WriteConfig]):
211
+ _input_error = InputError
212
+ _field_keys = MappingProxyType({"SPACING": frozenset({"spacing"})})
213
+ ...
214
+
215
+ Its fields are the values of the file, named as the format names them.
216
+ Arrays, also those in a tuple or a named tuple, are stored read-only; a
217
+ tuple of another class is kept as it is, since its constructor is
218
+ unknown, so that its arrays must be read-only already. An array that its
219
+ giver can still change, itself or through the memory that it belongs
220
+ to, is copied, and the copy is locked: its flag cannot be set writable
221
+ again. A read-only array over read-only memory is kept without a copy,
222
+ such as one that ``read`` made from bytes or a file mapped read-only, or
223
+ one that owns its memory: whoever gives such an array must not make it
224
+ writable again. A field whose value has parts of its own holds a
225
+ `FieldModel`, which freezes its own arrays.
226
+
227
+ Equality compares the content: arrays element-wise, with NaN equal to
228
+ NaN and NaT equal to NaT, their dtypes regardless of byte order, and
229
+ other fields with ``==``, with a float NaN equal to NaN, a NaT equal to
230
+ NaT, and a NumPy scalar other than a date or a time equal to the Python
231
+ value that it holds. Elements of objects and of structures compare as
232
+ Python and NumPy compare them, so that a NaN among them equals no NaN.
233
+ The diagnostics are no content. The hash agrees with equality, and is
234
+ computed once.
235
+
236
+ A subclass uses these protected members, which are the interface between
237
+ SciFile-Core and a package:
238
+
239
+ - the class variable ``_input_error``, the package's `InputError`, which
240
+ the model raises;
241
+ - ``_validate``, which rejects and normalizes the fields;
242
+ - ``_rules``, which checks the rules of the format, and reads
243
+ ``_parsed`` for the diagnostics of the parser;
244
+ - ``_field_keys`` and ``_fields_of``, which give the fields that a
245
+ diagnostic of the parser concerns;
246
+ - ``_write_config`` and ``_chunks`` of `TextFileModel` and
247
+ `BinaryFileModel`, which give the default write options and write the
248
+ file.
249
+ """
250
+
251
+ __slots__ = ("_diagnostics", "_maps", "_parsed")
252
+
253
+ _field_keys: ClassVar[Mapping[str, frozenset[str]]] = MappingProxyType({})
254
+ """The fields of the model that each ``field`` of a diagnostic concerns.
255
+
256
+ A package maps each ``field`` that its reader and its rules give a
257
+ diagnostic to the names of the model's fields that the diagnostic
258
+ concerns, in a mapping that cannot change, as
259
+ ``MappingProxyType({"SPACING": frozenset({"spacing"})})``.
260
+ """
261
+
262
+ _parsed: tuple[Diagnostic, ...]
263
+ """The diagnostics of the parser, in order; `()` for a new model."""
264
+
265
+ _diagnostics: Diagnostics
266
+ """The diagnostics, which `diagnostics` fills on its first access."""
267
+
268
+ _maps: tuple[tuple[FileMap, bool], ...]
269
+ """The maps of files that arrays of the fields lie in, each with whether
270
+ every such array can be copied; `_detached` fills it on the first write
271
+ while a map is in use."""
272
+
273
+ def __init_subclass__(cls, **kwargs: object) -> None:
274
+ """Make ``copy.replace`` of a subclass check the names, as `replace`.
275
+
276
+ Parameters
277
+ ----------
278
+ **kwargs
279
+ Keywords of the class statement, which go on to the base class.
280
+ """
281
+ super().__init_subclass__(**kwargs)
282
+ cls._keep_replace()
283
+
284
+ def __post_init__(self) -> None:
285
+ """Validate the fields, then freeze the arrays.
286
+
287
+ A subclass validates and normalizes its fields in ``_validate``,
288
+ not here. A new model has no diagnostics of the parser.
289
+ """
290
+ self._settle()
291
+ object.__setattr__(self, "_parsed", ())
292
+
293
+ @property
294
+ def diagnostics(self) -> Diagnostics:
295
+ """Diagnostics of the parser, then those of the rules of the format.
296
+
297
+ The rules are checked on the first access, and the result is kept
298
+ for the next. Two threads that fill it at once compute equal
299
+ diagnostics, of which one is kept.
300
+ """
301
+ cached: Diagnostics | None = getattr(self, "_diagnostics", None)
302
+ if cached is None:
303
+ cached = Diagnostics((*self._parsed, *self._rules()))
304
+ object.__setattr__(self, "_diagnostics", cached)
305
+ return cached
306
+
307
+ def _rules(self) -> Iterable[Diagnostic]:
308
+ """Check the rules of the format, beyond what a model can hold.
309
+
310
+ A subclass yields a diagnostic, with the source `"verifier"`, for each
311
+ broken rule. A rule that skips a problem that the parser reported
312
+ reads ``_parsed``; reading `diagnostics` here would recurse.
313
+ """
314
+ return ()
315
+
316
+ def _fields_of(self, diagnostic: Diagnostic) -> frozenset[str] | None:
317
+ """Return the fields that a diagnostic of the parser concerns.
318
+
319
+ `replace` keeps a diagnostic of the parser unless it changes one of
320
+ these fields. A subclass overrides this method for a diagnostic that
321
+ concerns other fields than those of its ``field`` in
322
+ ``_field_keys``.
323
+
324
+ Parameters
325
+ ----------
326
+ diagnostic
327
+ A diagnostic of the parser.
328
+
329
+ Returns
330
+ -------
331
+ `None` if the diagnostic has no ``field``, for a diagnostic of the
332
+ whole file; else the names that ``_field_keys`` gives for its
333
+ ``field``; else, for a ``field`` that ``_field_keys`` lacks, every
334
+ field of the model, so that any change drops it.
335
+ """
336
+ key = diagnostic.field
337
+ if key is None:
338
+ return None
339
+ fields = self._field_keys.get(key)
340
+ if fields is None:
341
+ return frozenset(_layout(type(self)).init)
342
+ return fields
343
+
344
+ def replace(self, **changes: object) -> Self:
345
+ """Return a copy with some fields changed.
346
+
347
+ Parameters
348
+ ----------
349
+ **changes
350
+ New values of fields, by name.
351
+
352
+ Returns
353
+ -------
354
+ The new model, validated. It keeps each diagnostic of the parser
355
+ that concerns none of the names of ``changes``, whether or not a
356
+ value differs, and checks the rules again on the first access of
357
+ `diagnostics`. The arrays that are not changed are shared.
358
+
359
+ Raises
360
+ ------
361
+ InputError
362
+ The package's input error, if a name is no field of the model or
363
+ a value is invalid.
364
+ """
365
+ changed = self._changed(changes)
366
+ if self._parsed:
367
+ kept = tuple(
368
+ diagnostic
369
+ for diagnostic in self._parsed
370
+ if (fields := self._fields_of(diagnostic)) is None
371
+ or fields.isdisjoint(changes)
372
+ )
373
+ object.__setattr__(changed, "_parsed", kept)
374
+ return changed
375
+
376
+ def to_dict(self) -> dict[str, Any]:
377
+ """Return the fields, as the class constructor takes them.
378
+
379
+ Returns
380
+ -------
381
+ The value of each field, by name, so that
382
+ ``type(model)(**model.to_dict()) == model``.
383
+ """
384
+ return self._init_fields()
385
+
386
+ def __eq__(self, other: object) -> bool:
387
+ """Compare the content of two models of the same class.
388
+
389
+ Parameters
390
+ ----------
391
+ other
392
+ The object to compare, equal only if of the same class.
393
+ """
394
+ if type(other) is not type(self):
395
+ return NotImplemented
396
+ return self._same(cast("Self", other))
397
+
398
+ def __hash__(self) -> int:
399
+ """Return a hash of the content, which equality agrees with."""
400
+ return self._content_hash()
401
+
402
+ def __reduce__(
403
+ self,
404
+ ) -> tuple[
405
+ Callable[..., Self],
406
+ tuple[type[Self], dict[str, object], tuple[Diagnostic, ...]],
407
+ ]:
408
+ """Pickle the fields and the diagnostics of the parser.
409
+
410
+ A model is unpickled without validating it again, and its arrays are
411
+ made read-only without a copy. Its rules are checked again on the
412
+ first access of `diagnostics`.
413
+ """
414
+ return (_restore, (type(self), self._all_fields(), self._parsed))
415
+
416
+
417
+ class FieldModel(_Model):
418
+ """Base of the types of the fields of the models.
419
+
420
+ A field whose value has parts of its own, such as the parameters of an
421
+ atom type or a pairwise potential, holds a field type: a frozen, slotted,
422
+ keyword-only dataclass that subclasses this class, with ``eq=False`` so
423
+ that it keeps the equality and the hash of this class:
424
+
425
+ .. code-block:: python
426
+
427
+ @dataclass(frozen=True, slots=True, kw_only=True, eq=False)
428
+ class Variable(FieldModel):
429
+ _input_error = InputError
430
+ file: str
431
+ skip: int = 6
432
+ def _validate(self) -> None:
433
+ if self.skip < 0:
434
+ raise self._input_error(
435
+ parameter="skip",
436
+ argument=self.skip,
437
+ message="must be 0 or more",
438
+ )
439
+
440
+ A field type is the model of the value of a field, as `FileModel` is the
441
+ model of a file, and behaves as a model does, without diagnostics. Its
442
+ arrays, also those in a tuple or a named tuple, are frozen as those of a
443
+ model are. Two values are equal if they are of the same class and their
444
+ fields have the same content, as the fields of a model compare: with
445
+ NaN equal to NaN, NaT equal to NaT, a NumPy scalar equal to the Python
446
+ value that it holds, and arrays element-wise. The hash agrees with
447
+ equality, and is computed once, so that a model whose fields hold field
448
+ types compares and hashes them by their content.
449
+
450
+ A subclass uses these protected members:
451
+
452
+ - the class variable ``_input_error``, the package's `InputError`, which
453
+ the constructor and `replace` raise;
454
+ - ``_validate``, which rejects and normalizes the fields, and may set a
455
+ field with ``object.__setattr__``.
456
+
457
+ It defines no `__post_init__`, which would skip the validation and the
458
+ freezing of this class, and no `__eq__` or `__hash__`.
459
+ """
460
+
461
+ __slots__ = ()
462
+
463
+ def __init_subclass__(cls, **kwargs: object) -> None:
464
+ """Make ``copy.replace`` of a subclass check the names, as `replace`.
465
+
466
+ Parameters
467
+ ----------
468
+ **kwargs
469
+ Keywords of the class statement, which go on to the base class.
470
+ """
471
+ super().__init_subclass__(**kwargs)
472
+ cls._keep_replace()
473
+
474
+ def __post_init__(self) -> None:
475
+ """Validate the fields, then freeze the arrays.
476
+
477
+ A subclass validates and normalizes its fields in ``_validate``,
478
+ not here.
479
+ """
480
+ self._settle()
481
+
482
+ def replace(self, **changes: object) -> Self:
483
+ """Return a copy with some fields changed.
484
+
485
+ Parameters
486
+ ----------
487
+ **changes
488
+ New values of fields, by name.
489
+
490
+ Returns
491
+ -------
492
+ The new value, validated. The arrays that are not changed are
493
+ shared.
494
+
495
+ Raises
496
+ ------
497
+ InputError
498
+ The package's input error, if a name is no field or a value is
499
+ invalid.
500
+ """
501
+ return self._changed(changes)
502
+
503
+ def to_dict(self) -> dict[str, Any]:
504
+ """Return the fields, as the class constructor takes them.
505
+
506
+ Returns
507
+ -------
508
+ The value of each field, by name, so that
509
+ ``type(value)(**value.to_dict()) == value``.
510
+ """
511
+ return self._init_fields()
512
+
513
+ def __eq__(self, other: object) -> bool:
514
+ """Compare the content of two values of the same class.
515
+
516
+ Parameters
517
+ ----------
518
+ other
519
+ The object to compare, equal only if of the same class.
520
+ """
521
+ if type(other) is not type(self):
522
+ return NotImplemented
523
+ return self._same(cast("Self", other))
524
+
525
+ def __hash__(self) -> int:
526
+ """Return a hash of the content, which equality agrees with."""
527
+ return self._content_hash()
528
+
529
+ def __reduce__(
530
+ self,
531
+ ) -> tuple[Callable[..., Self], tuple[type[Self], dict[str, object]]]:
532
+ """Pickle the fields.
533
+
534
+ A value is unpickled without validating it again, and its arrays are
535
+ made read-only without a copy.
536
+ """
537
+ return (_restore, (type(self), self._all_fields()))
538
+
539
+
540
+ class TextFileModel[W: WriteConfig](FileModel):
541
+ """Base of the models of text formats.
542
+
543
+ A subclass implements ``_write_config``, which returns the default
544
+ options, and ``_chunks``, which writes the file in chunks.
545
+ ``str(model)`` is the file with the default options.
546
+ """
547
+
548
+ __slots__ = ()
549
+
550
+ @overload
551
+ def write(
552
+ self,
553
+ target: None = None,
554
+ *,
555
+ config: W | None = None,
556
+ encoding: str = "utf-8",
557
+ **overrides: object,
558
+ ) -> str: ...
559
+
560
+ @overload
561
+ def write(
562
+ self,
563
+ target: Callable[[str], object] | str | os.PathLike[str],
564
+ *,
565
+ config: W | None = None,
566
+ encoding: str = "utf-8",
567
+ **overrides: object,
568
+ ) -> None: ...
569
+
570
+ def write(
571
+ self,
572
+ target: TextTarget = None,
573
+ *,
574
+ config: W | None = None,
575
+ encoding: str = "utf-8",
576
+ **overrides: object,
577
+ ) -> str | None:
578
+ """Write the file.
579
+
580
+ Parameters
581
+ ----------
582
+ target
583
+ `None` returns the text.
584
+ A callable receives it in non-empty chunks, in order.
585
+ A path (a string or `os.PathLike`) receives it as a file, as
586
+ `deliver_text` writes one. A path or the method ``write`` of a
587
+ stream of the file that arrays of the model are mapped from, as
588
+ `map_file` maps one, receives the text of a copy of them, since
589
+ the file may be written in place.
590
+ config
591
+ Write options; the package's ``WriteConfig``.
592
+ encoding
593
+ Encoding of a file that a path receives.
594
+ **overrides
595
+ Options that replace those of ``config``, by name.
596
+
597
+ Returns
598
+ -------
599
+ The text if ``target`` is `None`, otherwise `None`.
600
+
601
+ Raises
602
+ ------
603
+ InputError
604
+ The package's input error, if an option, the encoding or the
605
+ target is invalid, or the target writes the file that arrays of
606
+ the model are mapped from, which has been cut short since.
607
+ PermissionError
608
+ If the target is a file that cannot be written.
609
+ """
610
+ options = configure(
611
+ self._write_config(),
612
+ config,
613
+ overrides,
614
+ input_error=self._input_error,
615
+ )
616
+ return deliver_text(
617
+ _detached(self, target)._chunks(options), # noqa: SLF001 - this model's hook, on a copy that leaves the target's file
618
+ target,
619
+ encoding=encoding,
620
+ input_error=self._input_error,
621
+ )
622
+
623
+ def _write_config(self) -> W:
624
+ """Return the default write options of this model."""
625
+ raise NotImplementedError
626
+
627
+ def _chunks(self, config: W) -> Iterable[str]:
628
+ """Write the file in chunks, with some options."""
629
+ raise NotImplementedError
630
+
631
+ def __str__(self) -> str:
632
+ """Return the file, written with the default options."""
633
+ return self.write()
634
+
635
+
636
+ class BinaryFileModel[W: WriteConfig](FileModel):
637
+ """Base of the models of binary formats.
638
+
639
+ A subclass implements ``_write_config``, which returns the default
640
+ options, and ``_chunks``, which writes the file in chunks.
641
+ ``bytes(model)`` is the file with the default options.
642
+ """
643
+
644
+ __slots__ = ()
645
+
646
+ @overload
647
+ def write(
648
+ self,
649
+ target: None = None,
650
+ *,
651
+ config: W | None = None,
652
+ **overrides: object,
653
+ ) -> bytes: ...
654
+
655
+ @overload
656
+ def write(
657
+ self,
658
+ target: Callable[[bytes], object] | str | os.PathLike[str],
659
+ *,
660
+ config: W | None = None,
661
+ **overrides: object,
662
+ ) -> None: ...
663
+
664
+ def write(
665
+ self,
666
+ target: BinaryTarget = None,
667
+ *,
668
+ config: W | None = None,
669
+ **overrides: object,
670
+ ) -> bytes | None:
671
+ """Write the file.
672
+
673
+ Parameters
674
+ ----------
675
+ target
676
+ `None` returns the bytes.
677
+ A callable receives them in non-empty chunks, in order.
678
+ A path (a string or `os.PathLike`) receives them as a file, as
679
+ `deliver_bytes` writes one. A path or the method ``write`` of a
680
+ stream of the file that arrays of the model are mapped from, as
681
+ `map_file` maps one, receives the bytes of a copy of them, since
682
+ the file may be written in place.
683
+ config
684
+ Write options; the package's ``WriteConfig``.
685
+ **overrides
686
+ Options that replace those of ``config``, by name.
687
+
688
+ Returns
689
+ -------
690
+ The bytes if ``target`` is `None`, otherwise `None`.
691
+
692
+ Raises
693
+ ------
694
+ InputError
695
+ The package's input error, if an option or the target is
696
+ invalid, or the target writes the file that arrays of the model
697
+ are mapped from, which has been cut short since.
698
+ PermissionError
699
+ If the target is a file that cannot be written.
700
+ """
701
+ options = configure(
702
+ self._write_config(),
703
+ config,
704
+ overrides,
705
+ input_error=self._input_error,
706
+ )
707
+ return deliver_bytes(
708
+ _detached(self, target)._chunks(options), # noqa: SLF001 - this model's hook, on a copy that leaves the target's file
709
+ target,
710
+ input_error=self._input_error,
711
+ )
712
+
713
+ def _write_config(self) -> W:
714
+ """Return the default write options of this model."""
715
+ raise NotImplementedError
716
+
717
+ def _chunks(self, config: W) -> Iterable[bytes]:
718
+ """Write the file in chunks, with some options."""
719
+ raise NotImplementedError
720
+
721
+ def __bytes__(self) -> bytes:
722
+ """Return the file, written with the default options."""
723
+ return self.write()
724
+
725
+
726
+ def with_parsed[M: FileModel](model: M, diagnostics: Iterable[Diagnostic]) -> M:
727
+ """Return a copy of a model with the diagnostics of a parser.
728
+
729
+ A package's ``read`` attaches the diagnostics of parsing with this
730
+ function. The copy shares the fields and the hash of the model, without
731
+ validating them again, and checks the rules on the first access of
732
+ `FileModel.diagnostics`.
733
+
734
+ Parameters
735
+ ----------
736
+ model
737
+ The model.
738
+ diagnostics
739
+ The diagnostics of the parser, in order, which replace those of the
740
+ model.
741
+
742
+ Returns
743
+ -------
744
+ The copy.
745
+ """
746
+ copy = object.__new__(type(model))
747
+ for name in _field_names(type(model)):
748
+ object.__setattr__(copy, name, getattr(model, name))
749
+ object.__setattr__(copy, "_parsed", tuple(diagnostics))
750
+ cached = getattr(model, "_hash", None)
751
+ if cached is not None:
752
+ object.__setattr__(copy, "_hash", cached)
753
+ return copy
754
+
755
+
756
+ def _detached[M: FileModel](model: M, target: object) -> M:
757
+ """Return a model, or a copy of it that holds no array of a target's file.
758
+
759
+ A path, or the method ``write`` of a stream, may write the file that an
760
+ array of the model is mapped from, under any of its names, as its device
761
+ and inode tell. The file may then be written in place, which would
762
+ change the array while it is written, or cut short, after which a read
763
+ of the array ends the process. The copy holds a copy of each such array,
764
+ also in a tuple, a named tuple or a field type, and shares the rest;
765
+ nothing is copied for any other target. Nothing is looked for while no
766
+ map of `map_file` is in use, and the maps of a model are looked for
767
+ once, since it cannot change.
768
+
769
+ Raises
770
+ ------
771
+ InputError
772
+ The package's input error, if the file is shorter than its map
773
+ already, so that the arrays are lost, or if a list, or a tuple of a
774
+ class whose constructor is unknown, holds such an array, which then
775
+ cannot be copied.
776
+ """
777
+ if target is None or not maps_alive():
778
+ return model
779
+ maps: tuple[tuple[FileMap, bool], ...] | None = getattr(
780
+ model, "_maps", None
781
+ )
782
+ if maps is None:
783
+ found: dict[int, tuple[FileMap, bool]] = {}
784
+ _find_maps(_layout(type(model)).values(model), found, copyable=True)
785
+ maps = tuple(found.values())
786
+ object.__setattr__(model, "_maps", maps)
787
+ if not maps:
788
+ return model
789
+ written = written_file(target)
790
+ if written is None:
791
+ return model
792
+ file = (written.st_dev, written.st_ino)
793
+ inside = [pair for pair in maps if (pair[0].device, pair[0].inode) == file]
794
+ if not inside:
795
+ return model
796
+ if any(written.st_size < len(found) for found, _ in inside):
797
+ raise model._input_error( # noqa: SLF001 - the model's own error
798
+ parameter="target",
799
+ argument=target,
800
+ message="writes to the file that arrays of the model are mapped"
801
+ " from, which has been cut short, so that they are lost",
802
+ )
803
+ if not all(copyable for _, copyable in inside):
804
+ raise model._input_error( # noqa: SLF001 - the model's own error
805
+ parameter="target",
806
+ argument=target,
807
+ message="writes to the file that arrays of the model are mapped"
808
+ " from, which a list or a tuple of an unknown class holds, so"
809
+ " that they cannot be copied",
810
+ )
811
+ layout = _layout(type(model))
812
+ targeted = {id(found) for found, _ in inside}
813
+ copy = object.__new__(type(model))
814
+ for name, value in zip(layout.fields, layout.values(model), strict=True):
815
+ object.__setattr__(copy, name, _detached_value(value, targeted))
816
+ object.__setattr__(copy, "_parsed", model._parsed) # noqa: SLF001 - copied whole
817
+ return copy
818
+
819
+
820
+ def _find_maps(
821
+ values: Collection[object],
822
+ found: dict[int, tuple[FileMap, bool]],
823
+ *,
824
+ copyable: bool,
825
+ ) -> None:
826
+ """Record the maps that the arrays of some values lie in, by their `id`.
827
+
828
+ Each map comes with whether every array of it can be copied: one in a
829
+ list, or in a tuple of a class whose constructor is unknown, cannot.
830
+ """
831
+ if is_plain(values):
832
+ return
833
+ for value in values:
834
+ if isinstance(value, tuple):
835
+ inner = copyable and tuple_maker(value) is not None
836
+ _find_maps(value, found, copyable=inner)
837
+ elif isinstance(value, list):
838
+ _find_maps(value, found, copyable=False)
839
+ elif isinstance(value, FieldModel):
840
+ fields = _layout(type(value)).values(value)
841
+ _find_maps(fields, found, copyable=copyable)
842
+ else:
843
+ mapped = map_of(value)
844
+ if mapped is not None:
845
+ key = id(mapped)
846
+ was = found.get(key, (mapped, True))[1]
847
+ found[key] = (mapped, was and copyable)
848
+
849
+
850
+ def _detached_value(value: object, inside: AbstractSet[int]) -> object:
851
+ """Return a field value with a copy of each array that lies in a map.
852
+
853
+ The maps are given by their `id`. The arrays of a tuple, a named tuple
854
+ and a field type are copied too; `_detached` rejects a list, or a tuple
855
+ of a class whose constructor is unknown, that holds such an array.
856
+ """
857
+ if isinstance(value, tuple):
858
+ return _detached_items(value, inside)
859
+ if isinstance(value, FieldModel):
860
+ return _detached_field_type(value, inside)
861
+ found = map_of(value)
862
+ if found is None or id(found) not in inside:
863
+ return value
864
+ return frozen(cast("NDArray[Any]", value).copy(order="K"), fresh=True)
865
+
866
+
867
+ def _detached_items(
868
+ value: tuple[object, ...], inside: AbstractSet[int]
869
+ ) -> object:
870
+ """Return a tuple with a copy of each array that lies in a map."""
871
+ make = tuple_maker(value)
872
+ if make is None:
873
+ return value
874
+ items = [_detached_value(item, inside) for item in value]
875
+ if all(new is old for new, old in zip(items, value, strict=True)):
876
+ return value
877
+ return make(items)
878
+
879
+
880
+ def _detached_field_type(
881
+ value: FieldModel, inside: AbstractSet[int]
882
+ ) -> FieldModel:
883
+ """Return a field type with a copy of each array that lies in a map.
884
+
885
+ The copy shares the other fields, without validating them again.
886
+ """
887
+ layout = _layout(type(value))
888
+ old = layout.values(value)
889
+ new = [_detached_value(item, inside) for item in old]
890
+ if all(item is was for item, was in zip(new, old, strict=True)):
891
+ return value
892
+ copy = object.__new__(type(value))
893
+ for name, item in zip(layout.fields, new, strict=True):
894
+ object.__setattr__(copy, name, item)
895
+ return copy
896
+
897
+
898
+ def configure[W](
899
+ default: W,
900
+ config: W | None,
901
+ overrides: Mapping[str, object],
902
+ *,
903
+ input_error: type[InputError] | None = None,
904
+ ) -> W:
905
+ """Return the write options of a call.
906
+
907
+ Write options are a dataclass, whose options are the fields that its
908
+ constructor takes, as with `WriteConfig`, or another object that has
909
+ ``replace(**changes)``, which returns a copy with changed options, and
910
+ ``FIELD_NAMES``, the names of its options.
911
+
912
+ Parameters
913
+ ----------
914
+ default
915
+ The default options.
916
+ config
917
+ The options that the caller gave, or `None` for the defaults.
918
+ overrides
919
+ Options that replace those of ``config``, by name.
920
+ input_error
921
+ The exception that a rejected argument raises, the package's own;
922
+ `None` for `InputError`.
923
+
924
+ Returns
925
+ -------
926
+ The options.
927
+
928
+ Raises
929
+ ------
930
+ InputError
931
+ If ``config`` is of another class than the defaults, or an override
932
+ names no option.
933
+ TypeError
934
+ If the options are no dataclass, and lack ``replace`` or
935
+ ``FIELD_NAMES``.
936
+ """
937
+ input_error = input_error or InputError
938
+ if config is not None and type(config) is not type(default):
939
+ message = f"is no {type(default).__name__}"
940
+ raise input_error(parameter="config", argument=config, message=message)
941
+ options = default if config is None else config
942
+ if not overrides:
943
+ return options
944
+ unknown = sorted(set(overrides) - set(_option_names(options)))
945
+ if unknown:
946
+ message = f"names no option of {type(options).__name__}: {unknown}"
947
+ raise input_error(
948
+ parameter="overrides", argument=dict(overrides), message=message
949
+ )
950
+ if dataclasses.is_dataclass(options):
951
+ return cast("W", dataclasses.replace(_dataclass(options), **overrides))
952
+ return cast("W", cast("_Options", options).replace(**overrides))
953
+
954
+
955
+ @runtime_checkable
956
+ class _Options(Protocol):
957
+ """Write options that are no dataclass, but can be configured."""
958
+
959
+ FIELD_NAMES: Collection[str]
960
+ """The names of the options."""
961
+
962
+ def replace(self, **changes: object) -> Self:
963
+ """Return a copy with some options changed."""
964
+
965
+
966
+ def _option_names(options: object) -> Iterable[str]:
967
+ """Return the names of the write options that a caller can set."""
968
+ if dataclasses.is_dataclass(options) and not isinstance(options, type):
969
+ fields = dataclasses.fields(options)
970
+ return (field.name for field in fields if field.init)
971
+ if isinstance(options, _Options):
972
+ return options.FIELD_NAMES
973
+ message = (
974
+ f"{type(options).__name__} is no dataclass, and has no replace and"
975
+ " FIELD_NAMES"
976
+ )
977
+ raise TypeError(message)
978
+
979
+
980
+ def _dataclass(value: object) -> DataclassInstance:
981
+ """Return a value as the dataclass that it is.
982
+
983
+ Raises
984
+ ------
985
+ TypeError
986
+ If the value is no dataclass instance.
987
+ """
988
+ if not dataclasses.is_dataclass(value) or isinstance(value, type):
989
+ message = f"{type(value).__name__} is no dataclass"
990
+ raise TypeError(message)
991
+ return value
992
+
993
+
994
+ class _Layout(NamedTuple):
995
+ """The fields of a class."""
996
+
997
+ fields: tuple[str, ...]
998
+ """The names of every field."""
999
+
1000
+ init: tuple[str, ...]
1001
+ """The names of the fields that the constructor takes."""
1002
+
1003
+ values: Callable[[object], tuple[object, ...]]
1004
+ """What returns the values of every field of a value, in order."""
1005
+
1006
+
1007
+ def _layout(cls: type[_Model]) -> _Layout:
1008
+ """Return the fields of a class, which are looked up once."""
1009
+ layout = _LAYOUTS.get(cls)
1010
+ if layout is None:
1011
+ fields = dataclasses.fields(cast("type[DataclassInstance]", cls))
1012
+ names = tuple(field.name for field in fields)
1013
+ init = tuple(field.name for field in fields if field.init)
1014
+ layout = _Layout(names, init, _getter(names))
1015
+ _LAYOUTS[cls] = layout
1016
+ return layout
1017
+
1018
+
1019
+ def _getter(names: tuple[str, ...]) -> Callable[[object], tuple[object, ...]]:
1020
+ """Return what gets the values of some attributes as a tuple."""
1021
+ if len(names) > 1:
1022
+ return cast(
1023
+ "Callable[[object], tuple[object, ...]]",
1024
+ operator.attrgetter(*names),
1025
+ )
1026
+ if names:
1027
+ get = operator.attrgetter(names[0])
1028
+ return lambda value: (get(value),)
1029
+ return lambda _: ()
1030
+
1031
+
1032
+ def _field_names(cls: type[_Model]) -> tuple[str, ...]:
1033
+ """Return the names of the fields of a class."""
1034
+ return _layout(cls).fields
1035
+
1036
+
1037
+ def _restore[M: _Model](
1038
+ cls: type[M],
1039
+ fields: Mapping[str, object],
1040
+ parsed: tuple[Diagnostic, ...] | None = None,
1041
+ ) -> M:
1042
+ """Assemble a value from valid fields, without validating them again.
1043
+
1044
+ The fields come from pickling or copying a value, and the diagnostics of
1045
+ the parser, which a model has and a field type has not, are kept; the
1046
+ diagnostics of the rules are not, and a model checks its rules again.
1047
+ An array that owns its memory is new and held by nobody else, and is
1048
+ frozen without a copy; an array over memory that its giver can change,
1049
+ as with the out-of-band buffers of pickle, is copied.
1050
+ """
1051
+ value = object.__new__(cls)
1052
+ for name, field in fields.items():
1053
+ object.__setattr__(value, name, frozen_value(field, fresh=True))
1054
+ if parsed is not None:
1055
+ object.__setattr__(value, "_parsed", parsed)
1056
+ return value