-
Notifications
You must be signed in to change notification settings - Fork 17
Expand file tree
/
Copy path_descriptors.py
More file actions
3446 lines (3010 loc) · 114 KB
/
Copy path_descriptors.py
File metadata and controls
3446 lines (3010 loc) · 114 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
# SPDX-FileCopyrightText: Copyright DB InfraGO AG
# SPDX-License-Identifier: Apache-2.0
from __future__ import annotations
__all__ = [
"Accessor",
"Alias",
"Allocation",
"AlternateAccessor",
"Association",
"AttributeMatcherAccessor",
"Backref",
"BrokenModelError",
"Containment",
"DeepProxyAccessor",
"DeprecatedAccessor",
"DirectProxyAccessor",
"Filter",
"IndexAccessor",
"InvalidModificationError",
"MissingValueError",
"NewObject",
"NonUniqueMemberError",
"Optional",
"ParentAccessor",
"PhysicalAccessor",
"PhysicalLinkEndsAccessor",
"Relationship",
"Single",
"SpecificationAccessor",
"TypecastAccessor",
"WritableAccessor",
"build_xtype",
"xtype_handler",
]
import abc
import collections.abc as cabc
import contextlib
import itertools
import logging
import operator
import sys
import types
import typing as t
import warnings
import markupsafe
import typing_extensions as te
from lxml import etree
import capellambse
from capellambse import helpers
from . import T, T_co, U, U_co
if sys.version_info >= (3, 13):
from warnings import deprecated
else:
from typing_extensions import deprecated
_NotSpecifiedType = t.NewType("_NotSpecifiedType", object)
_NOT_SPECIFIED = _NotSpecifiedType(object())
"Used to detect unspecified optional arguments"
LOGGER = logging.getLogger(__name__)
@deprecated(
"@xtype_handler is deprecated and no longer used,"
" inherit from ModelElement instead"
)
def xtype_handler(
arch: str | None = None, /, *xtypes: str
) -> cabc.Callable[[type[T]], type[T]]:
"""Register a class as handler for a specific ``xsi:type``.
No longer used. Instead, declare a :class:`capellambse.model.Namespace`
containing your classes and register it as entrypoint.
"""
del arch, xtypes
return lambda i: i
@deprecated("xsi:type strings are deprecated")
def build_xtype(class_: type[_obj.ModelObject]) -> str:
ns: _obj.Namespace | None = getattr(class_, "__capella_namespace__", None)
if ns is None:
raise ValueError(f"Cannot determine namespace of class {class_!r}")
return f"{ns.alias}:{class_.__name__}"
class BrokenModelError(RuntimeError):
"""Raised when the model is invalid."""
class MissingValueError(BrokenModelError):
"""Raised when an enforced Single value is absent."""
obj = property(lambda self: self.args[0])
attr = property(lambda self: self.args[1])
def __str__(self) -> str:
if len(self.args) != 2:
return super().__str__()
return (
f"Missing required value for {self.attr!r}"
f" on {self.obj._short_repr_()}"
)
class InvalidModificationError(RuntimeError):
"""Raised when a modification would result in an invalid model."""
class NonUniqueMemberError(ValueError):
"""Raised when a duplicate member is inserted into a list."""
parent = property(lambda self: self.args[0])
attr = property(lambda self: self.args[1])
target = property(lambda self: self.args[2])
def __str__(self) -> str:
if len(self.args) != 3:
return super().__str__()
return (
f"Cannot insert: {self.attr!r} of {self.parent._short_repr_()}"
f" already contains a reference to {self.target._short_repr_()}"
)
class NewObject:
"""A marker which will create a new model object when inserted.
This object can be assigned to an attribute of a model object, and
will be replaced with a new object of the correct type by the
attribute's accessor.
For the time being, client code should treat this as opaque object.
"""
def __init__(self, /, type_hint: str = "", **kw: t.Any) -> None:
self._type_hint = type_hint
self._kw = kw
def __repr__(self) -> str:
kw = ", ".join(f"{k}={v!r}" for k, v in self._kw.items())
return f"<new object {self._type_hint!r} ({kw})>"
class Accessor(t.Generic[U_co], metaclass=abc.ABCMeta):
"""Super class for all Accessor types."""
__name__: str
__objclass__: type[t.Any]
def __init__(self) -> None:
super().__init__()
self.__doc__ = (
f"A {type(self).__name__} that was not properly configured."
" Ensure that ``__set_name__`` gets called after construction."
)
@t.overload
def __get__(self, obj: None, objtype: type[t.Any]) -> te.Self: ...
@t.overload
def __get__(
self, obj: _obj.ModelObject, objtype: type[t.Any] | None = ...
) -> U_co: ...
@abc.abstractmethod
def __get__(
self,
obj: _obj.ModelObject | None,
objtype: type[t.Any] | None = None,
) -> te.Self | U_co:
pass
def __set__(self, obj: t.Any, value: t.Any) -> None:
raise TypeError(f"Cannot set {self} on {type(obj).__name__}")
def __delete__(self, obj: t.Any) -> None:
raise TypeError(f"Cannot delete from {self!r} on {type(obj).__name__}")
def __set_name__(self, owner: type[t.Any], name: str) -> None:
self.__objclass__ = owner
self.__name__ = name
friendly_name = name.replace("_", " ")
self.__doc__ = f"The {friendly_name} of this {owner.__name__}."
if isinstance(self, Single):
return
super_acc = None
for cls in owner.__mro__[1:]:
super_acc = cls.__dict__.get(name)
if super_acc is not None:
break
if isinstance(super_acc, Single):
super_acc = super_acc.wrapped
if super_acc is not None and type(super_acc) is type(self):
self._resolve_super_attributes(super_acc)
else:
self._resolve_super_attributes(None)
def __repr__(self) -> str:
return f"<{type(self).__name__} {self._qualname!r}>"
@property
def _qualname(self) -> str:
"""Generate the qualified name of this descriptor."""
if not hasattr(self, "__objclass__"):
return f"(unknown {type(self).__name__} - call __set_name__)"
return f"{self.__objclass__.__name__}.{self.__name__}"
def _resolve_super_attributes(
self, super_acc: Accessor[t.Any] | None
) -> None:
pass
class Alias(Accessor["U"], t.Generic[U]):
"""Provides an alias to another attribute.
Parameters
----------
target
The target to redirect to.
dirhide
If True, hide this alias from `dir()` calls.
"""
__slots__ = ("dirhide", "target")
def __init__(self, target: str, /, *, dirhide: bool = True) -> None:
if "." in target:
raise ValueError(f"Unsupported alias target: {target!r}")
super().__init__()
self.target = target
self.dirhide = dirhide
@t.overload
def __get__(self, obj: None, objtype: type[t.Any]) -> te.Self: ...
@t.overload
def __get__(
self,
obj: _obj.ModelObject,
objtype: type[t.Any] | None = ...,
) -> U: ...
def __get__(
self,
obj: _obj.ModelObject | None,
objtype: type[t.Any] | None = None,
) -> te.Self | U:
if obj is None:
return self
return getattr(obj, self.target)
def __set__(
self, obj: _obj.ModelObject, value: U | cabc.Iterable[U]
) -> None:
setattr(obj, self.target, value)
def __delete__(self, obj: _obj.ModelObject) -> None:
delattr(obj, self.target)
def __set_name__(self, owner: type[t.Any], name: str) -> None:
if not hasattr(owner, self.target):
raise TypeError(
f"Cannot create alias {owner.__name__}.{name}:"
f" Target {self.target!r} is not defined"
" (make sure to define the Alias after the target, not before)"
)
alt = getattr(owner, self.target)
if isinstance(alt, DeprecatedAccessor) or (
isinstance(alt, property) and hasattr(alt.fget, "__deprecated__")
):
warnings.warn(
(
f"Alias {owner.__name__}.{name}:"
f" Target {self.target!r} is deprecated"
),
DeprecationWarning,
stacklevel=2,
)
super().__set_name__(owner, name)
def __repr__(self) -> str:
return (
f"<{type(self).__name__} {self._qualname!r}"
f" to {self.target!r}{' (hidden)' * self.dirhide}>"
)
class DeprecatedAccessor(Accessor[T_co]):
"""Provides a deprecated alias to another attribute."""
__slots__ = ("alternative",)
def __init__(self, alternative: str, /) -> None:
super().__init__()
self.alternative = alternative
@t.overload
def __get__(self, obj: None, objtype: type[t.Any]) -> te.Self: ...
@t.overload
def __get__(
self,
obj: _obj.ModelObject,
objtype: type[t.Any] | None = ...,
) -> T_co: ...
def __get__(
self,
obj: _obj.ModelObject | None,
objtype: type[t.Any] | None = None,
) -> te.Self | T_co:
if obj is None:
return self
self.__warn()
return getattr(obj, self.alternative)
def __set__(self, obj: _obj.ModelObject, value: t.Any) -> None:
self.__warn()
setattr(obj, self.alternative, value)
def __delete__(self, obj: _obj.ModelObject) -> None:
self.__warn()
delattr(obj, self.alternative)
def __set_name__(self, owner: type[t.Any], name: str) -> None:
if not hasattr(owner, self.alternative):
raise TypeError(
f"Cannot deprecate {owner.__name__}.{name}:"
f" Alternative {self.alternative!r} is not defined"
" (make sure to define the DeprecatedAccessor"
" after the alternative, not before)"
)
alt = getattr(owner, self.alternative)
if isinstance(alt, DeprecatedAccessor) or (
isinstance(alt, property) and hasattr(alt.fget, "__deprecated__")
):
raise TypeError(
f"Cannot deprecate {owner.__name__}.{name}:"
f" Alternative {self.alternative!r} is also deprecated"
)
super().__set_name__(owner, name)
def __warn(self) -> None:
msg = f"{self._qualname} is deprecated, use {self.alternative} instead"
warnings.warn(msg, FutureWarning, stacklevel=3)
def __repr__(self) -> str:
return (
f"<{type(self).__name__} {self._qualname!r},"
f" use {self.alternative!r} instead>"
)
class Optional(Accessor[T_co | "_obj.ElementList[T_co]" | None ], t.Generic[T_co]):
"""An Accessor wrapper that makes result optional.
This Accessor is used to wrap other Accessors and make faults optional.
It catches wrapped accessor faults, hides them and intentionally
returns empty result effectively preventing runtime errors when accessing
optional model elements (i.e. extensions)
Parameters
----------
wrapped
The accessor to wrap. This accessor must return a list (i.e. it
is not possible to nest *Single* descriptors). The instance
passed here should also not be used anywhere else.
optional
Marker of optional element, when set - hides the errors
Defaults to True.
Examples
--------
>>> class Foo(capellacore.CapellaElement):
... bar = Optional["Bar"](Containment("bar", (NS, "Bar")))
"""
def __init__(
self,
wrapped: Accessor[T_co | _obj.ElementList[T_co] | None ],
optional: bool = False
) -> None:
"""Create a new optional descriptor."""
self.wrapped: t.Final = wrapped
self.optional: t.Final = optional
@t.overload
def __get__(self, obj: None, objtype: type[t.Any]) -> te.Self: ...
@t.overload
def __get__(
self, obj: _obj.ModelObject, objtype: type[t.Any] | None = None
) -> T_co | None: ...
def __get__(
self, obj: _obj.ModelObject | None, objtype: t.Any | None = None
) -> te.Self | T_co | None:
"""Retrieve the value of the attribute."""
if obj is None:
return self
objs: t.Any = None
try:
objs = self.wrapped.__get__(obj, type(obj))
finally:
self.__objs = objs
return objs
def __set__(
self, obj: _obj.ModelObject, value: _obj.ModelObject | None
) -> None:
"""Set the value of the attribute."""
if self.__objs:
self.wrapped.__set__(obj, [value])
def __delete__(self, obj: _obj.ModelObject) -> None:
"""Delete the attribute."""
if self.objs:
self.wrapped.__delete__(obj)
def __set_name__(self, owner: type[_obj.ModelObject], name: str) -> None:
"""Set the name and owner of the descriptor."""
self.wrapped.__set_name__(owner, name)
super().__set_name__(owner, name)
def __repr__(self) -> str:
wrapped = repr(self.wrapped).replace(" " + repr(self._qualname), "")
return f"<Optional {self._qualname!r} of {wrapped}>"
def purge_references(
self, obj: _obj.ModelObject, target: _obj.ModelObject
) -> contextlib.AbstractContextManager[None]:
if hasattr(self.wrapped, "purge_references"):
return self.wrapped.purge_references(obj, target)
return contextlib.nullcontext(None)
class Single(Accessor[T_co | None], t.Generic[T_co]):
"""An Accessor wrapper that ensures there is exactly one value.
This Accessor is used to wrap other Accessors that return multiple
values, such as :class:`Containment`, :class:`Association` or
:class:`Allocation`. Instead of returning a list, Single ensures
that the list from the wrapped accessor contains exactly one
element, and returns that element directly.
Parameters
----------
wrapped
The accessor to wrap. This accessor must return a list (i.e. it
is not possible to nest *Single* descriptors). The instance
passed here should also not be used anywhere else.
enforce
Whether to enforce that there is exactly one value.
If enforce False and the list obtained from the wrapped accessor
is empty, this accessor returns None; if there is at least one
element in it, the first element is returned.
If enforce is True, a list which doesn't have exactly one
element will cause a :class:`MissingValueError` to be raised,
which is a subclass of :class:`BrokenModelError`.
Defaults to False.
Examples
--------
>>> class Foo(capellacore.CapellaElement):
... bar = Single["Bar"](Containment("bar", (NS, "Bar")))
"""
def __init__(
self,
wrapped: Accessor[_obj.ElementList[T_co]],
enforce: bool = False,
) -> None:
"""Create a new single-value descriptor."""
self.wrapped: t.Final = wrapped
self.enforce: t.Final = enforce
@t.overload
def __get__(self, obj: None, objtype: type[t.Any]) -> te.Self: ...
@t.overload
def __get__(
self, obj: _obj.ModelObject, objtype: type[t.Any] | None = None
) -> T_co | None: ...
def __get__(
self, obj: _obj.ModelObject | None, objtype: t.Any | None = None
) -> te.Self | T_co | None:
"""Retrieve the value of the attribute."""
if obj is None:
return self
objs: t.Any = self.wrapped.__get__(obj, type(obj))
if not isinstance(objs, _obj.ElementList):
raise RuntimeError(
f"Expected a list from wrapped accessor on {self._qualname},"
f" got {type(objs).__name__}"
)
if objs:
return objs[0]
if self.enforce:
raise MissingValueError(obj, self.__name__)
return None
def __set__(
self, obj: _obj.ModelObject, value: _obj.ModelObject | None
) -> None:
"""Set the value of the attribute."""
self.wrapped.__set__(obj, [value])
def __delete__(self, obj: _obj.ModelObject) -> None:
"""Delete the attribute."""
if self.enforce:
o = getattr(obj, "_short_repr_", obj.__repr__)()
raise InvalidModificationError(
f"Cannot delete required attribute {self._qualname!r} from {o}"
)
self.wrapped.__delete__(obj)
def __set_name__(self, owner: type[_obj.ModelObject], name: str) -> None:
"""Set the name and owner of the descriptor."""
self.wrapped.__set_name__(owner, name)
super().__set_name__(owner, name)
def __repr__(self) -> str:
if self.enforce:
level = "exactly one"
else:
level = "the first"
wrapped = repr(self.wrapped).replace(" " + repr(self._qualname), "")
return f"<Single {self._qualname!r}, {level} of {wrapped}>"
def purge_references(
self, obj: _obj.ModelObject, target: _obj.ModelObject
) -> contextlib.AbstractContextManager[None]:
if hasattr(self.wrapped, "purge_references"):
return self.wrapped.purge_references(obj, target)
return contextlib.nullcontext(None)
class Relationship(Accessor["_obj.ElementList[T_co]"], t.Generic[T_co]):
list_type: type[_obj.ElementListCouplingMixin]
list_extra_args: cabc.Mapping[str, t.Any]
single_attr: str | None
def __init__(
self,
*,
mapkey: str | None,
mapvalue: str | None,
fixed_length: int,
single_attr: str | None,
legacy_by_type: bool = False,
) -> None:
self.list_extra_args = {
"fixed_length": fixed_length,
"legacy_by_type": legacy_by_type,
"mapkey": mapkey,
"mapvalue": mapvalue,
}
self.single_attr = single_attr
self.list_type = make_coupled_list_type(self)
@t.overload
def __get__(self, obj: None, objtype: type[t.Any]) -> te.Self: ...
@t.overload
def __get__(
self, obj: _obj.ModelObject, objtype: type[t.Any] | None = ...
) -> _obj.ElementList[T_co]: ...
@abc.abstractmethod
def __get__(
self,
obj: _obj.ModelObject | None,
objtype: type[t.Any] | None = None,
) -> te.Self | _obj.ElementList[T_co]:
pass
@abc.abstractmethod
def __set__(
self,
obj: _obj.ModelObject,
value: cabc.Iterable[T_co | NewObject],
) -> None:
pass
def __delete__(self, obj: _obj.ModelObject) -> None:
self.__set__(obj, [])
@abc.abstractmethod
def insert(
self,
elmlist: _obj.ElementListCouplingMixin,
index: int,
value: T_co | NewObject,
*,
bounds: tuple[_obj.ClassName, ...] = (),
) -> T_co:
"""Insert the ``value`` object into the model.
The object must be inserted at an appropriate place, so that, if
``elmlist`` were to be created afresh, ``value`` would show up
at index ``index``.
Returns the value that was just inserted. This is useful if the
incoming value was a :class:`NewObject`, in which case the
return value is the newly created object.
"""
@abc.abstractmethod
def delete(
self,
elmlist: _obj.ElementListCouplingMixin,
obj: _obj.ModelObject,
) -> None:
"""Delete the ``obj`` from the model."""
def purge_references(
self, obj: _obj.ModelObject, target: _obj.ModelObject
) -> contextlib.AbstractContextManager[None]:
"""Purge references to the given object from the model.
This method is called while deleting physical objects, in order
to get rid of references to that object (and its descendants).
Reference purging is done in two steps, which is why this method
returns a context manager.
The first step, executed by the ``__enter__`` method, collects
references to the target and ensures that deleting them would
result in a valid model. If any validity constraints would be
violated, an exception is raised to indicate as such, and the
whole operation is aborted.
Once all ``__enter__`` methods have been called, the target
object is deleted from the model. Then all ``__exit__`` methods
are called, which triggers the actual deletion of all previously
discovered references.
As per the context manager protocol, ``__exit__`` will always be
called after ``__enter__``, even if the operation is to be
aborted. The ``__exit__`` method must therefore inspect whether
an exception was passed in or not in order to know whether the
operation succeeded.
In order to not confuse other context managers and keep the
model consistent, ``__exit__`` must not raise any further
exceptions. Exceptions should instead be logged to stderr, for
example by using the :py:meth:`logging.Logger.exception`
facility.
The ``purge_references`` method will only be called for Accessor
instances that actually contain a reference.
Parameters
----------
obj
The model object to purge references from.
target
The object that is to be deleted; references to this object
will be purged.
Returns
-------
contextlib.AbstractContextManager
A context manager that deals with purging references in a
transactional manner.
Raises
------
InvalidModificationError
Raised by the returned context manager's ``__enter__``
method if the attempted modification would result in an
invalid model. Note that it is generally preferred to allow
the operation and take the necessary steps to keep the model
consistent, if possible. This can be achieved for example by
deleting dependent objects along with the original deletion
target.
Exception
Any exception may be raised before ``__enter__`` returns in
order to abort the transaction and prevent the ``obj`` from
being deleted. No exceptions must be raised by ``__exit__``.
Examples
--------
A simple implementation for purging a single object reference
could look like this:
.. code-block:: python
@contextlib.contextmanager
def purge_references(self, obj, target):
assert self.__get__(obj, type(obj)) == target
yield
try:
self.__delete__(obj)
except Exception:
LOGGER.exception("Could not purge a dangling reference")
"""
del obj, target
return contextlib.nullcontext(None)
def _resolve_super_attributes(
self, super_acc: Accessor[t.Any] | None
) -> None:
assert isinstance(super_acc, Relationship | None)
super()._resolve_super_attributes(super_acc)
if super_acc is None:
return
if self.list_extra_args["fixed_length"] is None:
self.list_extra_args["fixed_length"] = super_acc.list_extra_args[ # type: ignore[index]
"fixed_length"
]
if self.list_extra_args["mapkey"] is None:
self.list_extra_args["mapkey"] = super_acc.list_extra_args[ # type: ignore[index]
"mapkey"
]
if self.list_extra_args["mapvalue"] is None:
self.list_extra_args["mapvalue"] = super_acc.list_extra_args[ # type: ignore[index]
"mapvalue"
]
if self.single_attr is None:
self.single_attr = super_acc.single_attr
@deprecated("WritableAccessor is deprecated, use Relationship instead")
class WritableAccessor(
Accessor["T_co | _obj.ElementList[T_co] | None"],
t.Generic[T_co],
):
"""An Accessor that also provides write support on lists it returns."""
aslist: type[_obj.ElementListCouplingMixin] | None
class_: type[T_co]
list_extra_args: cabc.Mapping[str, t.Any]
single_attr: str | None
def __init__(
self,
*args: t.Any,
aslist: type[_obj.ElementList] | None,
single_attr: str | None = None,
**kw: t.Any,
) -> None:
super().__init__(*args, **kw)
self.single_attr = single_attr
if aslist is not None:
self.aslist = type(
"Coupled" + aslist.__name__,
(_obj.ElementListCouplingMixin, aslist),
{"_accessor": self},
)
self.aslist.__module__ = __name__
else:
self.aslist = None
def __set__(
self,
obj: _obj.ModelObject,
value: T_co | NewObject | cabc.Iterable[T_co | NewObject],
) -> None:
raise TypeError(f"Cannot set {self} on {type(obj).__name__}")
def create(
self,
elmlist: _obj.ElementListCouplingMixin,
typehint: str | None = None,
/,
**kw: t.Any,
) -> T_co:
"""Create and return a new element of type ``elmclass``.
Parameters
----------
elmlist
The (coupled) :py:class:`~capellambse.model.ElementList` to
insert the new object into.
typehint
Hints for finding the correct type of element to create. Can
either be a full or shortened ``xsi:type`` string, or an
abbreviation defined by the specific Accessor instance.
kw
Initialize the properties of the new object. Depending on
the object's type, some attributes may be required.
"""
del elmlist, typehint, kw
raise TypeError(f"Cannot create objects on {self}")
def create_singleattr(
self, elmlist: _obj.ElementListCouplingMixin, arg: t.Any, /
) -> T_co:
"""Create an element that only has a single attribute of interest."""
if self.single_attr is None:
raise TypeError(
"Cannot create object from string, a dictionary is required"
)
return self.create(elmlist, **{self.single_attr: arg})
def insert(
self,
elmlist: _obj.ElementListCouplingMixin,
index: int,
value: _obj.ModelObject | NewObject,
) -> None:
"""Insert the ``value`` object into the model.
The object must be inserted at an appropriate place, so that, if
``elmlist`` were to be created afresh, ``value`` would show up
at index ``index``.
"""
raise NotImplementedError(f"Cannot insert objects into {self}")
def delete(
self,
elmlist: _obj.ElementListCouplingMixin,
obj: _obj.ModelObject,
) -> None:
"""Delete the ``obj`` from the model."""
raise NotImplementedError(f"Cannot delete object from {self}")
def _create(
self,
parent: _obj.ModelObject,
xmltag: str | None,
typehint: str | None,
/,
**kw: t.Any,
) -> T_co:
if typehint:
elmclass, _ = self._match_xtype(typehint)
else:
elmclass, _ = self._guess_xtype()
assert elmclass is not None
want_id: str | None = None
if "uuid" in kw:
want_id = kw.pop("uuid")
pelem = parent._element
with parent._model._loader.new_uuid(pelem, want=want_id) as obj_id:
return elmclass(parent._model, pelem, xmltag, uuid=obj_id, **kw)
def _make_list(
self,
parent_obj: _obj.ModelObject,
elements: list[etree._Element],
) -> T_co | _obj.ElementList[T_co] | None:
assert hasattr(self, "class_")
assert hasattr(self, "list_extra_args")
if self.aslist is None:
return no_list(self, parent_obj._model, elements, self.class_)
return self.aslist(
parent_obj._model,
elements,
self.class_,
parent=parent_obj,
**self.list_extra_args,
)
def _match_xtype(self, hint: str, /) -> tuple[type[T_co], str]:
"""Find the right class for the given ``xsi:type``."""
if not isinstance(hint, str):
raise TypeError(
f"Expected str as first type, got {type(hint).__name__!r}"
)
(cls,) = t.cast("tuple[type[T_co]]", _obj.find_wrapper(hint))
return (cls, build_xtype(cls)) # type: ignore[deprecated]
def _guess_xtype(self) -> tuple[type[T_co], str]:
try:
super_guess = super()._guess_xtype # type: ignore[misc]
except AttributeError:
pass
else:
return super_guess()
raise TypeError(f"{self._qualname} requires a type hint")
def purge_references(
self, obj: _obj.ModelObject, target: _obj.ModelObject
) -> contextlib.AbstractContextManager[None]:
"""Purge references to the given object from the model.
This method is called while deleting physical objects, in order
to get rid of references to that object (and its descendants).
Reference purging is done in two steps, which is why this method
returns a context manager.
The first step, executed by the ``__enter__`` method, collects
references to the target and ensures that deleting them would
result in a valid model. If any validity constraints would be
violated, an exception is raised to indicate as such, and the
whole operation is aborted.
Once all ``__enter__`` methods have been called, the target
object is deleted from the model. Then all ``__exit__`` methods
are called, which triggers the actual deletion of all previously
discovered references.
As per the context manager protocol, ``__exit__`` will always be
called after ``__enter__``, even if the operation is to be
aborted. The ``__exit__`` method must therefore inspect whether
an exception was passed in or not in order to know whether the
operation succeeded.
In order to not confuse other context managers and keep the
model consistent, ``__exit__`` must not raise any further
exceptions. Exceptions should instead be logged to stderr, for
example by using the :py:meth:`logging.Logger.exception`
facility.
The ``purge_references`` method will only be called for Accessor
instances that actually contain a reference.
Parameters
----------
obj
The model object to purge references from.
target
The object that is to be deleted; references to this object
will be purged.
Returns
-------
contextlib.AbstractContextManager
A context manager that deals with purging references in a
transactional manner.
Raises
------
InvalidModificationError
Raised by the returned context manager's ``__enter__``
method if the attempted modification would result in an
invalid model. Note that it is generally preferred to allow
the operation and take the necessary steps to keep the model
consistent, if possible. This can be achieved for example by
deleting dependent objects along with the original deletion
target.
Exception
Any exception may be raised before ``__enter__`` returns in
order to abort the transaction and prevent the ``obj`` from
being deleted. No exceptions must be raised by ``__exit__``.
Examples
--------
A simple implementation for purging a single object reference
could look like this:
.. code-block:: python
@contextlib.contextmanager
def purge_references(self, obj, target):
assert self.__get__(obj, type(obj)) == target
yield
try:
self.__delete__(obj)
except Exception:
LOGGER.exception("Could not purge a dangling reference")
"""
raise NotImplementedError(
f"{type(self).__name__} does not support purging references"
)
@deprecated("PhysicalAccessor is deprecated, use Relationship instead")
class PhysicalAccessor(
Accessor["T_co | _obj.ElementList[T_co] | None"],
t.Generic[T_co],
):
"""Helper super class for accessors that work with real elements."""
__slots__ = (
"aslist",
"class_",
"list_extra_args",
"xtypes",
)
aslist: type[_obj.ElementList] | None
class_: type[T_co]