Skip to content

arcanus.association

Association types and field helpers for modeling relationships.

arcanus.association

DefferedAssociation

A type used as a sentinel for already loaded association values, for deffering the blessing

Source code in arcanus/association.py
@final
class DefferedAssociation:
    """A type used as a sentinel for already loaded association values, for deffering the blessing"""

    def __copy__(self) -> Self: ...

Association

Bases: Generic[A]

Source code in arcanus/association.py
class Association(Generic[A]):
    __args__: tuple[type, ...]
    __instance__: Transmuter | None
    __loaded__: bool
    # Each concrete association narrows this to its container type (list[T],
    # set[T], dict[K, T], …); the base only promises "some payload store".
    __payloads__: Any

    field_name: str

    @classmethod
    def __get_pydantic_generic_schema__(
        cls,
        generic_type: Type[A],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        raise NotImplementedError()

    @classmethod
    def __get_pydantic_serialize_schema__(
        cls,
        generic_type: Type[A],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.SerSchema | None:
        """
        The default serialization schema for associations is to serialize the loaded value if the association is loaded, otherwise serialize the payloads.
        """
        # Concrete subclasses break reference cycles via ancestor-path tree projection
        # (see _AsAncestor): a back-edge pointing at an ancestor on the current dump
        # stack is cut, because a finite JSON tree cannot represent a cycle. This base
        # method is abstract; every concrete association overrides it.
        raise NotImplementedError()

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source_type: Type[Association[A]], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        args = get_args(source_type)

        if not args:
            raise TypeError(f"Generic type must be provided to the {source_type}.")

        generic_type = args[0]

        def validate(
            value: Any,
            handler: core_schema.ValidatorFunctionWrapHandler,
            info: core_schema.ValidationInfo,
        ) -> Association[A]:
            # if not info.field_name:
            #     raise ValueError(
            #         f"The association type {source_type} must be used as a model field."
            #     )

            # materia = active_materia.get()
            # value = materia.association_before_validator(cls, value, info)

            if value is DefferedAssociation:
                instance = cls()
            elif type(value) is cls:
                instance = value
                instance.__payloads__ = handler(instance.__payloads__)
            else:
                instance = cls(handler(value))

            instance.__args__ = (generic_type,)
            instance.field_name = info.field_name  # pyright: ignore[reportAttributeAccessIssue]
            # instance = materia.association_after_validator(instance, info)

            return instance

        return core_schema.with_default_schema(
            core_schema.with_info_wrap_validator_function(
                validate,
                cls.__get_pydantic_generic_schema__(generic_type, handler),
            ),
            default_factory=cls,
            serialization=cls.__get_pydantic_serialize_schema__(generic_type, handler),
        )

    @property
    def __instance_provider__(self) -> Optional[Any]:
        """Owner instance' provider, owner of this association's provider."""
        instance = self.__instance__
        if instance is not None:
            # Bypass Transmuter.__getattribute__'s per-access isinstance(Association)
            # check: __transmuter_provided__ is always a plain instance attribute set
            # via object.__setattr__, never an Association, so prepare() is irrelevant.
            return object.__getattribute__(instance, "__transmuter_provided__")
        return None

    @property
    def __provided__(self) -> Any | None:
        raise NotImplementedError()

    @cached_property
    def __validator__(self) -> TypeAdapter[A]:
        return get_cached_adapter(self.__args__[0])

    @cached_property
    def used_name(self) -> str:
        return (
            alias
            if self.__instance__ and (alias := self.field_info.alias)
            else self.field_name
        )

    def __init__(self, payloads: A | None = None):
        self.__instance__ = None
        self.__loaded__ = False
        self.__payloads__ = payloads

    def __await__(self):
        raise NotImplementedError("This association is not awaitable.")

    def _load(self) -> Any:
        raise NotImplementedError(
            "This association does not support synchronous loading."
        )

    async def _aload(self) -> Any:
        raise NotImplementedError(
            "This association does not support asynchronous loading."
        )

    def prepare(self, instance: Transmuter, field_name: str):
        if self.__instance__ is not None:
            return

        self.field_name = field_name
        self.field_info = type(instance).__pydantic_fields__[field_name]

        self.__instance__ = instance

        annotation = self.field_info.annotation
        if isinstance(annotation, ForwardRef):
            resolved_hints = get_type_hints(type(instance))
            actual_type = resolved_hints[field_name]
            self.__args__ = (get_args(actual_type)[0],)
        else:
            self.__args__ = (get_args(annotation)[0],)

    def bless(self, value: Any) -> Any:
        """Bless the value into the generic type."""
        return self.__validator__.validate_python(value)

    @staticmethod
    def ensure_mutable(
        func: Callable[Concatenate[AM, P], R],
    ) -> Callable[Concatenate[AM, P], R]:
        @wraps(func)
        def wrapper(self: AM, *args: P.args, **kwargs: P.kwargs) -> R:
            if self.field_info.frozen:
                raise ValidationError.from_exception_data(
                    type(self.__instance__).__name__
                    if self.__instance__
                    else "Association",
                    [
                        {
                            "type": "frozen_field",
                            "loc": (self.field_name,),
                            "input": self,
                        }
                    ],
                )
            return func(self, *args, **kwargs)

        return wrapper

    @property
    def loaded(self) -> bool:
        """Whether reading this association cannot fire a provider load."""
        if self.__loaded__ or self.__instance__ is None:
            return True
        return active_materia.get().association_loaded(self)

    def peek(self) -> A | None:
        """Return the association value without ever firing a load.

        Resolves normally when the value is already loaded (or loading is
        free for the active materia); returns ``None`` when resolving would
        require provider IO. Safe to call from synchronous code such as
        pydantic computed fields, serializers, and validators.
        """
        return self._load() if self.loaded else None

loaded property

loaded: bool

Whether reading this association cannot fire a provider load.

bless

bless(value: Any) -> Any

Bless the value into the generic type.

Source code in arcanus/association.py
def bless(self, value: Any) -> Any:
    """Bless the value into the generic type."""
    return self.__validator__.validate_python(value)

peek

peek() -> A | None

Return the association value without ever firing a load.

Resolves normally when the value is already loaded (or loading is free for the active materia); returns None when resolving would require provider IO. Safe to call from synchronous code such as pydantic computed fields, serializers, and validators.

Source code in arcanus/association.py
def peek(self) -> A | None:
    """Return the association value without ever firing a load.

    Resolves normally when the value is already loaded (or loading is
    free for the active materia); returns ``None`` when resolving would
    require provider IO. Safe to call from synchronous code such as
    pydantic computed fields, serializers, and validators.
    """
    return self._load() if self.loaded else None

RelationCollection

Bases: list[T], Association[T]

Source code in arcanus/association.py
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
class RelationCollection(list[T], Association[T]):
    # new items are held in __payloads__, loaded items are kept in the list itself
    __payloads__: list[T]

    @classmethod
    def __get_pydantic_generic_schema__(
        cls,
        generic_type: Type[T],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        return core_schema.list_schema(handler.generate_schema(generic_type))

    @classmethod
    def __get_pydantic_serialize_schema__(
        cls, generic_type: Type[T], handler: GetCoreSchemaHandler
    ) -> core_schema.SerSchema | None:
        def serialize(association: RelationCollection[T], serializer) -> Any:
            instance = association.__instance__
            fields_set = getattr(instance, "__pydantic_fields_set__", None)
            if fields_set is None or association.field_name not in fields_set:
                return serializer(list.copy(association) + association.__payloads__)
            with _AsAncestor(instance) as ancestors:
                return serializer(
                    [item for item in association.copy() if id(item) not in ancestors]
                )

        return core_schema.wrap_serializer_function_ser_schema(
            serialize,
            schema=core_schema.list_schema(handler.generate_schema(generic_type)),
            when_used="always",
        )

    def __init__(self, payloads: Iterable[T] | None = None):
        super().__init__()
        self.__instance__ = None
        self.__loaded__ = False
        self.__payloads__ = list(payloads) if payloads else []

    @property
    def __provided__(self) -> list[Any] | None:
        # The return type should be a duck typed list-like object provided by the current materia provider.
        # For example, with SQLAlchemyMateria, it would be a InstrumentedList[list[...]] which is actually a sqlalchemy descriptor.
        if not self.__instance_provider__:
            return None
        return getattr(self.__instance_provider__, self.used_name)

    @cached_property
    def __list_validator__(self) -> TypeAdapter[list[T]]:
        return get_cached_adapter(list[self.__args__[0]])

    @overload
    def bless(self, value: T) -> T: ...
    @overload
    def bless(self, value: Iterable[Any]) -> list[T]: ...
    def bless(self, value: Any | Iterable[Any]) -> T | Iterable[T]:
        """Bless the value into the generic type.

        Items that are already the target type skip pydantic entirely. Pydantic
        does fast-path instances (``revalidate_instances='never'``), but it still
        dispatches the per-item ``model_formulate`` wrap-validator and the
        TypeAdapter/list-schema machinery (~13µs for 50 valid items vs ~1µs for a
        plain isinstance sweep). The element type is always a concrete class, so
        the isinstance check needs no guard.
        """
        target = self.__args__[0]
        is_iterable = isinstance(value, Iterable) and not isinstance(
            value, get_origin(target) or target
        )

        if is_iterable:
            if all(isinstance(item, target) for item in value):
                return value
            return self.__list_validator__.validate_python(value)
        if isinstance(value, target):
            return value
        return self.__validator__.validate_python(value)

    def prepare(self, instance: Transmuter, field_name: str):
        super().prepare(instance, field_name)
        if self.__payloads__:
            # manualy enforce loading first to remove duplicates in payloads
            # objects already assigned to the relationship may be add to payloads during revalidation
            self._load()
            provided = self.__provided__
            if provided is not None:
                provided.extend(
                    item.__transmuter_provided__ for item in self.__payloads__
                )
            super().extend(self.__payloads__)
            self.__payloads__.clear()

    @staticmethod
    def ensure_loaded(
        func: Callable[Concatenate[RelationCollection[T], P], R],
    ) -> Callable[Concatenate[RelationCollection[T], P], R]:
        @wraps(func)
        def wrapper(
            self: RelationCollection[T], *args: P.args, **kwargs: P.kwargs
        ) -> R:
            self._load()
            return func(self, *args, **kwargs)

        return wrapper

    def _load(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # No backing provider (NoOpMateria, or a not-yet-persisted instance):
        # nothing can be lazily loaded, so memoize to skip this work — every
        # @ensure_loaded read/mutate (len, iter, append, …) would otherwise re-run
        # active_materia.get() + load_association + the provider lookup each time.
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        active_materia.get().load_association(self)

        # A: No provided, None
        # B: provided value is empty, []
        if not (self.__provided__):
            return self

        # TODO: Better way to avoid duplication relationship append ?
        self.__payloads__ = [
            payload
            for payload in self.__payloads__
            if payload.__transmuter_provided__ not in set(self.__provided__)
        ]

        if not len(self.__provided__) == super().__len__():
            # If the length of __provided__ is not equal to the length of self,
            # it means some items were not blessed into transmuter objects.
            super().clear()
            super().extend(self.bless(self.__provided__))
        self.__loaded__ = True

        return self

    async def _aload(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # No backing provider: nothing to lazily load — memoize (see _load).
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        # A: No provided, None
        # B: provided value is empty, []
        if not (provided := await active_materia.get().aload_association(self)):
            return self

        # TODO: Better way to avoid duplication relationship append ?
        self.__payloads__ = [
            payload
            for payload in self.__payloads__
            if payload.__transmuter_provided__ not in set(provided)
        ]

        if not len(provided) == super().__len__():
            # If the length of __provided__ is not equal to the length of self,
            # it means some items were not blessed into transmuter objects.
            super().clear()
            super().extend(self.bless(provided))
        self.__loaded__ = True

        return self

    def __await__(self):
        return self._aload().__await__()

    @overload
    def __getitem__(self, index: SupportsIndex) -> T: ...
    @overload
    def __getitem__(self, index: slice) -> list[T]: ...
    @ensure_loaded
    def __getitem__(self, index: SupportsIndex | slice) -> T | list[T]:
        return super().__getitem__(index)

    @ensure_loaded
    def __iter__(self):
        return super().__iter__()

    @ensure_loaded
    def __len__(self):
        return super().__len__()

    @ensure_loaded
    def __contains__(self, key: object) -> bool:
        return super().__contains__(key)

    @ensure_loaded
    def __bool__(self):
        return super().__len__() > 0

    @overload
    def __setitem__(self, key: SupportsIndex, value: T) -> None: ...
    @overload
    def __setitem__(self, key: slice, value: Iterable[T]) -> None: ...
    @ensure_loaded
    @Association.ensure_mutable
    def __setitem__(self, key: SupportsIndex | slice, value: T | Iterable[T]):
        provided = self.__provided__
        if isinstance(value, Iterable):
            items = self.bless(value)
            slc = cast(slice, key)
            if provided is not None:
                provided[slc] = [item.__transmuter_provided__ for item in items]
            super().__setitem__(slc, items)
        else:
            item = self.bless(value)
            idx = cast(SupportsIndex, key)
            if provided is not None:
                provided[idx] = item.__transmuter_provided__
            super().__setitem__(idx, item)

    @ensure_loaded
    @Association.ensure_mutable
    def __delitem__(self, key: SupportsIndex | slice):
        provided = self.__provided__
        if provided is not None:
            provided.__delitem__(key)
        super().__delitem__(key)

    @ensure_loaded
    def __add__(self, other: list[Any]):
        return self.copy() + self.bless(other)

    @ensure_loaded
    @Association.ensure_mutable
    def __iadd__(self, other: Iterable[T]):
        self.extend(other)
        return self

    def __mul__(self, other):
        raise NotImplementedError(
            "Left multiplication on relationship is not supported."
        )

    def __rmul__(self, other):
        raise NotImplementedError(
            "Right multiplication on relationship is not supported."
        )

    def __imul__(self, other):
        raise NotImplementedError(
            "Self multiplication on relationship is not supported."
        )

    @ensure_loaded
    def __eq__(self, other: object):
        return super().__eq__(other)

    @ensure_loaded
    def __ne__(self, other: object):
        return super().__ne__(other)

    @ensure_loaded
    def __lt__(self, other: list[T]):
        return super().__lt__(other)

    @ensure_loaded
    def __le__(self, other: list[T]):
        return super().__le__(other)

    @ensure_loaded
    def __gt__(self, other: list[T]):
        return super().__gt__(other)

    @ensure_loaded
    def __ge__(self, other: list[T]):
        return super().__ge__(other)

    # @ensure_loaded
    def __repr__(self):
        # return super().__repr__()
        args = getattr(self, "__args__", None)
        type_name = (
            getattr(args[0], "__name__", repr(args[0]))
            if args and len(args) > 0
            else "?"
        )
        return f"RelationCollection[{type_name}], instance={id(self.__instance__)}, size={super().__len__()}"

    @ensure_loaded
    def __str__(self):
        return super().__str__()

    @ensure_loaded
    def __reversed__(self):
        return super().__reversed__()

    @ensure_loaded
    @Association.ensure_mutable
    def append(self, value: T):
        value = self.bless(value)
        provided = self.__provided__
        if provided is not None:
            provided.append(value.__transmuter_provided__)
        super().append(value)

    @ensure_loaded
    @Association.ensure_mutable
    def extend(self, iterable: Iterable[T]):
        iterable = self.bless(iterable)
        provided = self.__provided__
        if provided is not None:
            provided.extend((item.__transmuter_provided__ for item in iterable))
        super().extend(iterable)

    @ensure_loaded
    @Association.ensure_mutable
    def clear(self):
        provided = self.__provided__
        if provided is not None:
            provided.clear()
        super().clear()

    @ensure_loaded
    def copy(self):
        return super().copy()

    @ensure_loaded
    def count(self, value: T) -> int:
        return super().count(value)

    @ensure_loaded
    def index(
        self, value: T, start: SupportsIndex = 0, stop: SupportsIndex | None = None
    ) -> int:
        if stop is None:
            return super().index(value, start)
        return super().index(value, start, stop)

    @ensure_loaded
    @Association.ensure_mutable
    def insert(self, index: SupportsIndex, object: T):
        object = self.bless(object)
        provided = self.__provided__
        if provided is not None:
            provided.insert(index, object.__transmuter_provided__)
        super().insert(index, object)

    @ensure_loaded
    @Association.ensure_mutable
    def pop(self, index: SupportsIndex = -1):
        item = super().pop(index)
        provided = self.__provided__
        if provided is not None:
            provided.remove(item.__transmuter_provided__)
        return item

    @ensure_loaded
    @Association.ensure_mutable
    def remove(self, value: T):
        # bless() is only needed to locate the value on the provider side; under
        # a no-op/absent provider it would be discarded, so skip it entirely.
        provided = self.__provided__
        if provided is not None:
            provided.remove(self.bless(value).__transmuter_provided__)
        super().remove(value)

    @ensure_loaded
    @Association.ensure_mutable
    def reverse(self):
        super().reverse()

    @ensure_loaded
    @Association.ensure_mutable
    def sort(
        self,
        *,
        key: Any = None,
        reverse: bool = False,
    ):
        super().sort(key=key, reverse=reverse)

bless

bless(value: T) -> T
bless(value: Iterable[Any]) -> list[T]
bless(value: Any | Iterable[Any]) -> T | Iterable[T]

Bless the value into the generic type.

Items that are already the target type skip pydantic entirely. Pydantic does fast-path instances (revalidate_instances='never'), but it still dispatches the per-item model_formulate wrap-validator and the TypeAdapter/list-schema machinery (~13µs for 50 valid items vs ~1µs for a plain isinstance sweep). The element type is always a concrete class, so the isinstance check needs no guard.

Source code in arcanus/association.py
def bless(self, value: Any | Iterable[Any]) -> T | Iterable[T]:
    """Bless the value into the generic type.

    Items that are already the target type skip pydantic entirely. Pydantic
    does fast-path instances (``revalidate_instances='never'``), but it still
    dispatches the per-item ``model_formulate`` wrap-validator and the
    TypeAdapter/list-schema machinery (~13µs for 50 valid items vs ~1µs for a
    plain isinstance sweep). The element type is always a concrete class, so
    the isinstance check needs no guard.
    """
    target = self.__args__[0]
    is_iterable = isinstance(value, Iterable) and not isinstance(
        value, get_origin(target) or target
    )

    if is_iterable:
        if all(isinstance(item, target) for item in value):
            return value
        return self.__list_validator__.validate_python(value)
    if isinstance(value, target):
        return value
    return self.__validator__.validate_python(value)

RelationSet

Bases: set[T], Association[T]

Source code in arcanus/association.py
 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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
class RelationSet(set[T], Association[T]):
    # new items are held in __payloads__, loaded items are kept in the set itself
    __payloads__: set[T]

    @classmethod
    def __get_pydantic_generic_schema__(
        cls,
        generic_type: Type[T],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        return core_schema.set_schema(handler.generate_schema(generic_type))

    @classmethod
    def __get_pydantic_serialize_schema__(
        cls, generic_type: Type[T], handler: GetCoreSchemaHandler
    ) -> core_schema.SerSchema | None:
        def serialize(association: RelationSet[T], serializer) -> Any:
            instance = association.__instance__
            fields_set = getattr(instance, "__pydantic_fields_set__", None)
            if fields_set is None or association.field_name not in fields_set:
                return serializer(
                    list(set.copy(association) | association.__payloads__)
                )
            with _AsAncestor(instance) as ancestors:
                return serializer(
                    [item for item in association.copy() if id(item) not in ancestors]
                )

        return core_schema.wrap_serializer_function_ser_schema(
            serialize,
            schema=core_schema.list_schema(handler.generate_schema(generic_type)),
            when_used="always",
        )

    def __init__(self, payloads: Iterable[T] | None = None):
        super().__init__()
        self.__instance__ = None
        self.__loaded__ = False
        self.__payloads__ = set(payloads) if payloads else set()

    @property
    def __provided__(self) -> Any | None:
        # The return type should be a duck typed set-like object provided by the current materia provider.
        # For example, with SQLAlchemyMateria and collection_class=set, it would be an InstrumentedSet.
        if not self.__instance_provider__:
            return None
        return getattr(self.__instance_provider__, self.used_name)

    @cached_property
    def __set_validator__(self) -> TypeAdapter[set[T]]:
        return get_cached_adapter(set[self.__args__[0]])

    @overload
    def bless(self, value: T) -> T: ...
    @overload
    def bless(self, value: Iterable[Any]) -> set[T]: ...
    def bless(self, value: Any | Iterable[Any]) -> T | set[T]:
        """Bless the value into the generic type."""
        target: type[T] = self.__args__[0]
        is_iterable = isinstance(value, Iterable) and not isinstance(
            value, get_origin(target) or target
        )

        if is_iterable:
            if all(isinstance(item, target) for item in value):
                return set(value)
            return self.__set_validator__.validate_python(value)
        if isinstance(value, target):
            return value
        return self.__validator__.validate_python(value)

    def prepare(self, instance: Transmuter, field_name: str):
        super().prepare(instance, field_name)
        if self.__payloads__:
            # manually enforce loading first to remove duplicates in payloads
            # objects already assigned to the relationship may be added to payloads during revalidation
            self._load()
            provided = self.__provided__
            for item in self.__payloads__:
                if item in self:
                    continue
                if provided is not None:
                    provided.add(item.__transmuter_provided__)
                super().add(item)
            self.__payloads__.clear()

    @staticmethod
    def ensure_loaded(
        func: Callable[Concatenate[RelationSet[T], P], R],
    ) -> Callable[Concatenate[RelationSet[T], P], R]:
        @wraps(func)
        def wrapper(self: RelationSet[T], *args: P.args, **kwargs: P.kwargs) -> R:
            self._load()
            return func(self, *args, **kwargs)

        return wrapper

    def _load(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # no backing provider (NoOpMateria / not-yet-persisted): nothing to load
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        active_materia.get().load_association(self)

        # A: No provided, None
        # B: provided value is empty
        if not self.__provided__:
            return self

        # Remove payloads that are already present in __provided__
        provided_set = set(self.__provided__)
        self.__payloads__ = {
            payload
            for payload in self.__payloads__
            if payload.__transmuter_provided__ not in provided_set
        }

        if len(self.__provided__) != super().__len__():
            # If the length of __provided__ is not equal to the length of self,
            # it means some items were not blessed into transmuter objects.
            super().clear()
            super().update(self.bless(self.__provided__))
        self.__loaded__ = True

        return self

    async def _aload(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # no backing provider: nothing to load
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        # A: No provided, None
        # B: provided value is empty
        if not (provided := await active_materia.get().aload_association(self)):
            return self

        # Remove payloads that are already present in provided
        provided_set = set(provided)
        self.__payloads__ = {
            payload
            for payload in self.__payloads__
            if payload.__transmuter_provided__ not in provided_set
        }

        if len(provided) != super().__len__():
            # If the length of __provided__ is not equal to the length of self,
            # it means some items were not blessed into transmuter objects.
            super().clear()
            super().update(self.bless(provided))
        self.__loaded__ = True

        return self

    def __await__(self):
        return self._aload().__await__()

    @ensure_loaded
    def __iter__(self):
        return super().__iter__()

    @ensure_loaded
    def __len__(self):
        return super().__len__()

    @ensure_loaded
    def __contains__(self, item: object) -> bool:
        return super().__contains__(item)

    @ensure_loaded
    def __bool__(self):
        return super().__len__() > 0

    def __repr__(self):
        args = getattr(self, "__args__", None)
        type_name = (
            getattr(args[0], "__name__", repr(args[0]))
            if args and len(args) > 0
            else "?"
        )
        return f"RelationSet[{type_name}], instance={id(self.__instance__)}, size={super().__len__()}"

    @ensure_loaded
    def __str__(self):
        return super().__str__()

    @ensure_loaded
    @Association.ensure_mutable
    def add(self, item: T) -> None:
        """Add an element. No effect if already present (identity-based)."""
        item = self.bless(item)
        if item in self:
            return
        provided = self.__provided__
        if provided is not None:
            provided.add(item.__transmuter_provided__)
        super().add(item)

    @ensure_loaded
    @Association.ensure_mutable
    def discard(self, item: T) -> None:
        """Remove an element if present."""
        if item not in self:
            return
        provided = self.__provided__
        if provided is not None:
            provided.discard(item.__transmuter_provided__)
        super().discard(item)

    @ensure_loaded
    @Association.ensure_mutable
    def remove(self, item: T) -> None:
        """Remove an element. Raises KeyError if not present."""
        provided = self.__provided__
        if provided is not None:
            provided.discard(item.__transmuter_provided__)
        super().remove(item)

    @ensure_loaded
    @Association.ensure_mutable
    def pop(self) -> T:
        """Remove and return an arbitrary element. Raises KeyError if empty."""
        item = super().pop()
        provided = self.__provided__
        if provided is not None:
            provided.discard(item.__transmuter_provided__)
        return item

    @ensure_loaded
    @Association.ensure_mutable
    def update(self, *others: Iterable[T]) -> None:
        """Add all elements from iterables."""
        for other in others:
            items = self.bless(other)
            for item in items:
                self.add(item)

    @ensure_loaded
    @Association.ensure_mutable
    def clear(self) -> None:
        """Remove all elements."""
        provided = self.__provided__
        if provided is not None:
            provided.clear()
        super().clear()

    @ensure_loaded
    @Association.ensure_mutable
    def intersection_update(self, *others: Iterable[T]) -> None:
        """Keep only elements found in all others."""
        keep = set.intersection(self, *others)
        removed = set.difference(self, keep)
        for item in removed:
            self.discard(item)

    @ensure_loaded
    @Association.ensure_mutable
    def difference_update(self, *others: Iterable[T]) -> None:
        """Remove all elements found in others."""
        to_remove = set.intersection(self, *others)
        for item in to_remove:
            self.discard(item)

    @ensure_loaded
    @Association.ensure_mutable
    def symmetric_difference_update(self, other: Iterable[T]) -> None:
        """Update to symmetric difference with other."""
        other_set = set(other)
        to_remove = set.intersection(self, other_set)
        to_add = other_set - set.copy(self)
        for item in to_remove:
            self.discard(item)
        for item in to_add:
            self.add(item)

    @ensure_loaded
    def copy(self) -> set[T]:
        return super().copy()

    @ensure_loaded
    def union(self, *others: Iterable[T]) -> set[T]:
        return super().union(*others)

    @ensure_loaded
    def intersection(self, *others: Iterable[T]) -> set[T]:
        return super().intersection(*others)

    @ensure_loaded
    def difference(self, *others: Iterable[T]) -> set[T]:
        return super().difference(*others)

    @ensure_loaded
    def symmetric_difference(self, other: Iterable[T]) -> set[T]:
        return super().symmetric_difference(other)

    @ensure_loaded
    def issubset(self, other: Iterable[T]) -> bool:
        return super().issubset(other)

    @ensure_loaded
    def issuperset(self, other: Iterable[T]) -> bool:
        return super().issuperset(other)

    @ensure_loaded
    def isdisjoint(self, other: Iterable[T]) -> bool:
        return super().isdisjoint(other)

    @ensure_loaded
    def __eq__(self, other: object) -> bool:
        if isinstance(other, RelationSet):
            return set.__eq__(self, other)
        if isinstance(other, (set, frozenset)):
            return set.__eq__(self, other)
        return False

    @ensure_loaded
    def __ne__(self, other: object) -> bool:
        if isinstance(other, RelationSet):
            return set.__ne__(self, other)
        if isinstance(other, (set, frozenset)):
            return set.__ne__(self, other)
        return True

    @ensure_loaded
    def __le__(self, other: set[T]) -> bool:
        return super().__le__(other)

    @ensure_loaded
    def __lt__(self, other: set[T]) -> bool:
        return super().__lt__(other)

    @ensure_loaded
    def __ge__(self, other: set[T]) -> bool:
        return super().__ge__(other)

    @ensure_loaded
    def __gt__(self, other: set[T]) -> bool:
        return super().__gt__(other)

    @ensure_loaded
    def __or__(self, other: set[T]) -> set[T]:
        return super().__or__(other)

    @ensure_loaded
    def __and__(self, other: set[T]) -> set[T]:
        return super().__and__(other)

    @ensure_loaded
    def __sub__(self, other: set[T]) -> set[T]:
        return super().__sub__(other)

    @ensure_loaded
    def __xor__(self, other: set[T]) -> set[T]:
        return super().__xor__(other)

    @ensure_loaded
    @Association.ensure_mutable
    def __ior__(self, other: Iterable[T]) -> Self:
        self.update(other)
        return self

    @ensure_loaded
    @Association.ensure_mutable
    def __iand__(self, other: Iterable[T]) -> Self:
        self.intersection_update(other)
        return self

    @ensure_loaded
    @Association.ensure_mutable
    def __isub__(self, other: Iterable[T]) -> Self:
        self.difference_update(other)
        return self

    @ensure_loaded
    @Association.ensure_mutable
    def __ixor__(self, other: Iterable[T]) -> Self:
        self.symmetric_difference_update(other)
        return self

bless

bless(value: T) -> T
bless(value: Iterable[Any]) -> set[T]
bless(value: Any | Iterable[Any]) -> T | set[T]

Bless the value into the generic type.

Source code in arcanus/association.py
def bless(self, value: Any | Iterable[Any]) -> T | set[T]:
    """Bless the value into the generic type."""
    target: type[T] = self.__args__[0]
    is_iterable = isinstance(value, Iterable) and not isinstance(
        value, get_origin(target) or target
    )

    if is_iterable:
        if all(isinstance(item, target) for item in value):
            return set(value)
        return self.__set_validator__.validate_python(value)
    if isinstance(value, target):
        return value
    return self.__validator__.validate_python(value)

add

add(item: T) -> None

Add an element. No effect if already present (identity-based).

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def add(self, item: T) -> None:
    """Add an element. No effect if already present (identity-based)."""
    item = self.bless(item)
    if item in self:
        return
    provided = self.__provided__
    if provided is not None:
        provided.add(item.__transmuter_provided__)
    super().add(item)

discard

discard(item: T) -> None

Remove an element if present.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def discard(self, item: T) -> None:
    """Remove an element if present."""
    if item not in self:
        return
    provided = self.__provided__
    if provided is not None:
        provided.discard(item.__transmuter_provided__)
    super().discard(item)

remove

remove(item: T) -> None

Remove an element. Raises KeyError if not present.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def remove(self, item: T) -> None:
    """Remove an element. Raises KeyError if not present."""
    provided = self.__provided__
    if provided is not None:
        provided.discard(item.__transmuter_provided__)
    super().remove(item)

pop

pop() -> T

Remove and return an arbitrary element. Raises KeyError if empty.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def pop(self) -> T:
    """Remove and return an arbitrary element. Raises KeyError if empty."""
    item = super().pop()
    provided = self.__provided__
    if provided is not None:
        provided.discard(item.__transmuter_provided__)
    return item

update

update(*others: Iterable[T]) -> None

Add all elements from iterables.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def update(self, *others: Iterable[T]) -> None:
    """Add all elements from iterables."""
    for other in others:
        items = self.bless(other)
        for item in items:
            self.add(item)

clear

clear() -> None

Remove all elements.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def clear(self) -> None:
    """Remove all elements."""
    provided = self.__provided__
    if provided is not None:
        provided.clear()
    super().clear()

intersection_update

intersection_update(*others: Iterable[T]) -> None

Keep only elements found in all others.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def intersection_update(self, *others: Iterable[T]) -> None:
    """Keep only elements found in all others."""
    keep = set.intersection(self, *others)
    removed = set.difference(self, keep)
    for item in removed:
        self.discard(item)

difference_update

difference_update(*others: Iterable[T]) -> None

Remove all elements found in others.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def difference_update(self, *others: Iterable[T]) -> None:
    """Remove all elements found in others."""
    to_remove = set.intersection(self, *others)
    for item in to_remove:
        self.discard(item)

symmetric_difference_update

symmetric_difference_update(other: Iterable[T]) -> None

Update to symmetric difference with other.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def symmetric_difference_update(self, other: Iterable[T]) -> None:
    """Update to symmetric difference with other."""
    other_set = set(other)
    to_remove = set.intersection(self, other_set)
    to_add = other_set - set.copy(self)
    for item in to_remove:
        self.discard(item)
    for item in to_add:
        self.add(item)

RelationMap

Bases: dict[K, T], Association[T]

Source code in arcanus/association.py
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
class RelationMap(dict[K, T], Association[T]):
    # new items are held in __payloads__, loaded items are kept in the dict itself
    # __args__[0] = key type (K), __args__[1] = value type (T)
    __payloads__: dict[K, T]

    @classmethod
    def __get_pydantic_generic_schema__(
        cls,
        key_type: Type[K],
        value_type: Type[T],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        return core_schema.dict_schema(
            keys_schema=handler.generate_schema(key_type),
            values_schema=handler.generate_schema(value_type),
        )

    @classmethod
    def __get_pydantic_serialize_schema__(
        cls,
        key_type: Type[K],
        value_type: Type[T],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.SerSchema | None:
        def serialize(association: RelationMap[K, T], serializer) -> Any:
            instance = association.__instance__
            fields_set = getattr(instance, "__pydantic_fields_set__", None)
            if fields_set is None or association.field_name not in fields_set:
                return serializer(dict.copy(association) | association.__payloads__)
            with _AsAncestor(instance) as ancestors:
                return serializer(
                    {
                        key: value
                        for key, value in association.copy().items()
                        if id(value) not in ancestors
                    }
                )

        return core_schema.wrap_serializer_function_ser_schema(
            serialize,
            schema=core_schema.dict_schema(
                keys_schema=handler.generate_schema(key_type),
                values_schema=handler.generate_schema(value_type),
            ),
            when_used="always",
        )

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source_type: Type[RelationMap[K, T]], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        args = get_args(source_type)

        if not args or len(args) < 2:
            raise TypeError(
                f"Two generic types (key, value) must be provided to {source_type}."
            )

        key_type = args[0]
        value_type = args[1]

        def validate(
            value: Any,
            handler: core_schema.ValidatorFunctionWrapHandler,
            info: core_schema.ValidationInfo,
        ) -> RelationMap[K, T]:
            if value is DefferedAssociation:
                instance = cls()
            elif type(value) is cls:
                instance = value
                instance.__payloads__ = handler(instance.__payloads__)
            else:
                instance = cls(handler(value))

            instance.__args__ = (key_type, value_type)
            instance.field_name = info.field_name  # pyright: ignore[reportAttributeAccessIssue]

            return instance

        return core_schema.with_default_schema(
            core_schema.with_info_wrap_validator_function(
                validate,
                cls.__get_pydantic_generic_schema__(key_type, value_type, handler),
            ),
            default_factory=cls,
            serialization=cls.__get_pydantic_serialize_schema__(
                key_type, value_type, handler
            ),
        )

    def __init__(self, payloads: Mapping[K, T] | None = None):
        super().__init__()
        self.__instance__ = None
        self.__loaded__ = False
        self.__payloads__ = dict(payloads) if payloads else {}

    @property
    def __provided__(self) -> dict | None:
        # The return type should be a duck typed dict-like object provided by the current materia provider.
        # For example, with SQLAlchemyMateria and collection_class=attribute_keyed_dict,
        # it would be a KeyFuncDict.
        if not self.__instance_provider__:
            return None
        return getattr(self.__instance_provider__, self.used_name)

    @cached_property
    def __validator__(self) -> TypeAdapter[T]:
        return get_cached_adapter(self.__args__[1])

    @cached_property
    def __dict_validator__(self) -> TypeAdapter[dict[K, T]]:
        return get_cached_adapter(dict[self.__args__[0], self.__args__[1]])

    @cached_property
    def __key_validator__(self) -> TypeAdapter[K]:
        return get_cached_adapter(self.__args__[0])

    def bless_key(self, key: Any) -> K:
        """Validate and coerce a key into the key type."""
        target = self.__args__[0]
        if isinstance(target, type) and isinstance(key, target):
            return key
        return self.__key_validator__.validate_python(key)

    def bless_value(self, value: Any) -> T:
        """Validate and coerce a single value into the value type."""
        target = self.__args__[1]
        if isinstance(value, target):
            return value
        return self.__validator__.validate_python(value)

    def bless(self, value: Mapping[K, Any]) -> dict[K, T]:
        """Validate and coerce an entire dict/mapping into dict[K, T]."""
        key_t, val_t = self.__args__[0], self.__args__[1]
        if isinstance(key_t, type) and all(
            isinstance(k, key_t) and isinstance(v, val_t) for k, v in value.items()
        ):
            return dict(value)
        return self.__dict_validator__.validate_python(value)

    def prepare(self, instance: Transmuter, field_name: str):
        if self.__instance__ is not None:
            return

        self.field_name = field_name
        self.field_info = type(instance).__pydantic_fields__[field_name]

        self.__instance__ = instance

        annotation = self.field_info.annotation
        if isinstance(annotation, ForwardRef):
            resolved_hints = get_type_hints(type(instance))
            actual_type = resolved_hints[field_name]
            args = get_args(actual_type)
        else:
            args = get_args(annotation)

        self.__args__ = (args[0], args[1])

        if self.__payloads__:
            # manually enforce loading first to remove duplicates in payloads
            # objects already assigned to the relationship may be added to payloads during revalidation
            self._load()
            provided = self.__provided__
            if provided is not None:
                provided.update(
                    {
                        key: value.__transmuter_provided__
                        for key, value in self.__payloads__.items()
                    }
                )
            super().update(self.__payloads__)
            self.__payloads__.clear()

    @staticmethod
    def ensure_loaded(
        func: Callable[Concatenate[RelationMap[K, T], P], R],
    ) -> Callable[Concatenate[RelationMap[K, T], P], R]:
        @wraps(func)
        def wrapper(self: RelationMap[K, T], *args: P.args, **kwargs: P.kwargs) -> R:
            self._load()
            return func(self, *args, **kwargs)

        return wrapper

    def _load(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # no backing provider (NoOpMateria / not-yet-persisted): nothing to load
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        active_materia.get().load_association(self)

        # A: No provided, None
        # B: provided value is empty, {}
        if not self.__provided__:
            return self

        # Remove payloads whose key is already in __provided__
        self.__payloads__ = {
            k: v for k, v in self.__payloads__.items() if k not in self.__provided__
        }

        if len(self.__provided__) != super().__len__():
            # If the length of __provided__ is not equal to the length of self,
            # it means some items were not blessed into transmuter objects.
            super().clear()
            super().update(self.bless(self.__provided__))
        self.__loaded__ = True

        return self

    async def _aload(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # no backing provider: nothing to load
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        # A: No provided, None
        # B: provided value is empty, {}
        if not (provided := await active_materia.get().aload_association(self)):
            return self

        # Remove payloads whose key is already in provided
        self.__payloads__ = {
            k: v for k, v in self.__payloads__.items() if k not in provided
        }

        if len(provided) != super().__len__():
            # If the length of __provided__ is not equal to the length of self,
            # it means some items were not blessed into transmuter objects.
            super().clear()
            super().update(self.bless(provided))
        self.__loaded__ = True

        return self

    def __await__(self):
        return self._aload().__await__()

    @ensure_loaded
    def __getitem__(self, key: K) -> T:
        key = self.bless_key(key)
        return super().__getitem__(key)

    @ensure_loaded
    def __iter__(self):
        return super().__iter__()

    @ensure_loaded
    def __len__(self):
        return super().__len__()

    @ensure_loaded
    def __contains__(self, key: object) -> bool:
        key = self.bless_key(key)
        return super().__contains__(key)

    @ensure_loaded
    def __bool__(self):
        return super().__len__() > 0

    @ensure_loaded
    @Association.ensure_mutable
    def __setitem__(self, key: K, value: T) -> None:
        key = self.bless_key(key)
        value = self.bless_value(value)
        provided = self.__provided__
        if provided is not None:
            provided[key] = value.__transmuter_provided__
        super().__setitem__(key, value)

    @ensure_loaded
    @Association.ensure_mutable
    def __delitem__(self, key: K) -> None:
        key = self.bless_key(key)
        provided = self.__provided__
        if provided is not None:
            del provided[key]
        super().__delitem__(key)

    def __repr__(self):
        args = getattr(self, "__args__", None)
        if args and len(args) >= 2:
            key_type = args[0]
            value_type = args[1]
            key_name = getattr(key_type, "__name__", repr(key_type))
            value_name = getattr(value_type, "__name__", repr(value_type))
        else:
            key_name = value_name = "?"
        return f"RelationMap[{key_name}, {value_name}], instance={id(self.__instance__)}, size={super().__len__()}"

    @ensure_loaded
    def __str__(self):
        return super().__str__()

    @ensure_loaded
    def __eq__(self, other: object) -> bool:
        if isinstance(other, dict):
            return dict.__eq__(self, other)
        return False

    @ensure_loaded
    def __ne__(self, other: object) -> bool:
        if isinstance(other, dict):
            return dict.__ne__(self, other)
        return True

    @ensure_loaded
    def __or__(self, other: Mapping[K, T]) -> dict[K, T]:
        return dict.__or__(self.copy(), dict(other))

    @ensure_loaded
    @Association.ensure_mutable
    def __ior__(self, other: Mapping[K, T]) -> Self:
        self.update(other)
        return self

    @ensure_loaded
    def __reversed__(self):
        return super().__reversed__()

    @ensure_loaded
    def get(self, key: K, default: T | None = None) -> T | None:
        return super().get(self.bless_key(key), default)

    @ensure_loaded
    def keys(self):
        return super().keys()

    @ensure_loaded
    def values(self):
        return super().values()

    @ensure_loaded
    def items(self):
        return super().items()

    @overload
    def pop(self, key: K) -> T: ...

    @overload
    def pop(self, key: K, default: T) -> T: ...

    @overload
    def pop(self, key: K, default: D) -> T | D: ...

    @ensure_loaded
    @Association.ensure_mutable
    def pop(self, key: K, *args: Any) -> Any:
        """Remove specified key and return the corresponding value."""
        key = self.bless_key(key)
        item = super().pop(key, *args)
        provided = self.__provided__
        if provided is not None and key in provided:
            del provided[key]
        return item

    @ensure_loaded
    @Association.ensure_mutable
    def popitem(self) -> tuple[K, T]:
        """Remove and return an arbitrary (key, value) pair. Raises KeyError if empty."""
        key, item = super().popitem()
        provided = self.__provided__
        if provided is not None:
            del provided[key]
        return key, item

    @overload
    def update(self, m: Mapping[K, T], /, **kwargs: T) -> None: ...
    @overload
    def update(self, m: Iterable[tuple[K, T]], /, **kwargs: T) -> None: ...
    @overload
    def update(self, **kwargs: T) -> None: ...

    @ensure_loaded
    @Association.ensure_mutable
    def update(
        self,
        *args: Mapping[K, T] | Iterable[tuple[K, T]],
        **kwargs: T,
    ) -> None:
        """Update the dict with key-value pairs."""
        merged = {}
        if args:
            if isinstance(args[0], Mapping):
                merged.update(args[0])
            else:
                merged.update(dict(*args))
        if kwargs:
            merged.update(kwargs)

        if not merged:
            return

        blessed = self.bless(merged)
        provided = self.__provided__
        if provided is not None:
            provided.update(
                {key: value.__transmuter_provided__ for key, value in blessed.items()}
            )
        super().update(blessed)

    @overload
    def setdefault(self, key: K) -> T | None: ...
    @overload
    def setdefault(self, key: K, default: T) -> T: ...

    @ensure_loaded
    @Association.ensure_mutable
    def setdefault(self, key: K, default: T | None = None) -> T | None:
        """If key is not in the dict, insert key with the default value."""
        key = self.bless_key(key)
        if key not in self:
            if default is not None:
                self[key] = default
        return super().get(key, default)

    @ensure_loaded
    @Association.ensure_mutable
    def clear(self) -> None:
        """Remove all items."""
        provided = self.__provided__
        if provided is not None:
            provided.clear()
        super().clear()

    @ensure_loaded
    def copy(self) -> dict[K, T]:
        return super().copy()

bless_key

bless_key(key: Any) -> K

Validate and coerce a key into the key type.

Source code in arcanus/association.py
def bless_key(self, key: Any) -> K:
    """Validate and coerce a key into the key type."""
    target = self.__args__[0]
    if isinstance(target, type) and isinstance(key, target):
        return key
    return self.__key_validator__.validate_python(key)

bless_value

bless_value(value: Any) -> T

Validate and coerce a single value into the value type.

Source code in arcanus/association.py
def bless_value(self, value: Any) -> T:
    """Validate and coerce a single value into the value type."""
    target = self.__args__[1]
    if isinstance(value, target):
        return value
    return self.__validator__.validate_python(value)

bless

bless(value: Mapping[K, Any]) -> dict[K, T]

Validate and coerce an entire dict/mapping into dict[K, T].

Source code in arcanus/association.py
def bless(self, value: Mapping[K, Any]) -> dict[K, T]:
    """Validate and coerce an entire dict/mapping into dict[K, T]."""
    key_t, val_t = self.__args__[0], self.__args__[1]
    if isinstance(key_t, type) and all(
        isinstance(k, key_t) and isinstance(v, val_t) for k, v in value.items()
    ):
        return dict(value)
    return self.__dict_validator__.validate_python(value)

pop

pop(key: K) -> T
pop(key: K, default: T) -> T
pop(key: K, default: D) -> T | D
pop(key: K, *args: Any) -> Any

Remove specified key and return the corresponding value.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def pop(self, key: K, *args: Any) -> Any:
    """Remove specified key and return the corresponding value."""
    key = self.bless_key(key)
    item = super().pop(key, *args)
    provided = self.__provided__
    if provided is not None and key in provided:
        del provided[key]
    return item

popitem

popitem() -> tuple[K, T]

Remove and return an arbitrary (key, value) pair. Raises KeyError if empty.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def popitem(self) -> tuple[K, T]:
    """Remove and return an arbitrary (key, value) pair. Raises KeyError if empty."""
    key, item = super().popitem()
    provided = self.__provided__
    if provided is not None:
        del provided[key]
    return key, item

update

update(m: Mapping[K, T], /, **kwargs: T) -> None
update(m: Iterable[tuple[K, T]], /, **kwargs: T) -> None
update(**kwargs: T) -> None
update(*args: Mapping[K, T] | Iterable[tuple[K, T]], **kwargs: T) -> None

Update the dict with key-value pairs.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def update(
    self,
    *args: Mapping[K, T] | Iterable[tuple[K, T]],
    **kwargs: T,
) -> None:
    """Update the dict with key-value pairs."""
    merged = {}
    if args:
        if isinstance(args[0], Mapping):
            merged.update(args[0])
        else:
            merged.update(dict(*args))
    if kwargs:
        merged.update(kwargs)

    if not merged:
        return

    blessed = self.bless(merged)
    provided = self.__provided__
    if provided is not None:
        provided.update(
            {key: value.__transmuter_provided__ for key, value in blessed.items()}
        )
    super().update(blessed)

setdefault

setdefault(key: K) -> T | None
setdefault(key: K, default: T) -> T
setdefault(key: K, default: T | None = None) -> T | None

If key is not in the dict, insert key with the default value.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def setdefault(self, key: K, default: T | None = None) -> T | None:
    """If key is not in the dict, insert key with the default value."""
    key = self.bless_key(key)
    if key not in self:
        if default is not None:
            self[key] = default
    return super().get(key, default)

clear

clear() -> None

Remove all items.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def clear(self) -> None:
    """Remove all items."""
    provided = self.__provided__
    if provided is not None:
        provided.clear()
    super().clear()

RelationGroupMap

Bases: dict[K, list[T]], Association[T]

A dict-based association that groups multiple values under each key.

Unlike :class:RelationMap which maps dict[K, T] (one value per key, silently dropping duplicates), this class stores dict[K, list[T]] so that multiple items sharing the same key coexist.

Backed by :class:~arcanus.materia.sqlalchemy.collections.KeyFuncListDict on the SQLAlchemy side (via attribute_keyed_list_dict).

Usage::

class Article(BaseTransmuter):
    generated_files: RelationGroupMap[str, File] = GroupedRelationship()
Source code in arcanus/association.py
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
class RelationGroupMap(dict[K, list[T]], Association[T]):
    """A dict-based association that groups multiple values under each key.

    Unlike :class:`RelationMap` which maps ``dict[K, T]`` (one value per key,
    silently dropping duplicates), this class stores ``dict[K, list[T]]`` so
    that multiple items sharing the same key coexist.

    Backed by :class:`~arcanus.materia.sqlalchemy.collections.KeyFuncListDict`
    on the SQLAlchemy side (via ``attribute_keyed_list_dict``).

    Usage::

        class Article(BaseTransmuter):
            generated_files: RelationGroupMap[str, File] = GroupedRelationship()
    """

    # new items are held in __payloads__, loaded items are kept in the dict itself
    # __args__[0] = key type (K), __args__[1] = value type (T)
    __payloads__: dict[K, list[T]]

    @classmethod
    def __get_pydantic_generic_schema__(
        cls,
        key_type: Type[K],
        value_type: Type[T],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        return core_schema.dict_schema(
            keys_schema=handler.generate_schema(key_type),
            values_schema=core_schema.list_schema(handler.generate_schema(value_type)),
        )

    @classmethod
    def __get_pydantic_serialize_schema__(
        cls,
        key_type: Type[K],
        value_type: Type[T],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.SerSchema | None:
        def serialize(association: RelationGroupMap[K, T], serializer) -> Any:
            instance = association.__instance__
            fields_set = getattr(instance, "__pydantic_fields_set__", None)
            if fields_set is None or association.field_name not in fields_set:
                return serializer(dict.copy(association) | association.__payloads__)
            with _AsAncestor(instance) as ancestors:
                return serializer(
                    {
                        key: [v for v in values if id(v) not in ancestors]
                        for key, values in association.copy().items()
                    }
                )

        return core_schema.wrap_serializer_function_ser_schema(
            serialize,
            schema=core_schema.dict_schema(
                keys_schema=handler.generate_schema(key_type),
                values_schema=core_schema.list_schema(
                    handler.generate_schema(value_type)
                ),
            ),
            when_used="always",
        )

    @classmethod
    def __get_pydantic_core_schema__(
        cls, source_type: Type[RelationGroupMap[K, T]], handler: GetCoreSchemaHandler
    ) -> core_schema.CoreSchema:
        args = get_args(source_type)

        if not args or len(args) < 2:
            raise TypeError(
                f"Two generic types (key, value) must be provided to {source_type}."
            )

        key_type = args[0]
        value_type = args[1]

        def validate(
            value: Any,
            handler: core_schema.ValidatorFunctionWrapHandler,
            info: core_schema.ValidationInfo,
        ) -> RelationGroupMap[K, T]:
            if value is DefferedAssociation:
                instance = cls()
            elif type(value) is cls:
                instance = value
                instance.__payloads__ = handler(instance.__payloads__)
            else:
                instance = cls(handler(value))

            instance.__args__ = (key_type, value_type)
            instance.field_name = info.field_name  # pyright: ignore[reportAttributeAccessIssue]

            return instance

        return core_schema.with_default_schema(
            core_schema.with_info_wrap_validator_function(
                validate,
                cls.__get_pydantic_generic_schema__(key_type, value_type, handler),
            ),
            default_factory=cls,
            serialization=cls.__get_pydantic_serialize_schema__(
                key_type, value_type, handler
            ),
        )

    def __init__(self, payloads: Mapping[K, list[T]] | None = None):
        super().__init__()
        self.__instance__ = None
        self.__loaded__ = False
        self.__backing_attr__ = None
        self.__payloads__: dict[K, list[T]] = (
            {k: list(v) for k, v in payloads.items()} if payloads else {}
        )

    # When the transmuter field maps to an association proxy (not the underlying
    # relationship directly), the materia can set this to the underlying
    # collection name so mutations go through the real collection class.
    __backing_attr__: str | None

    @property
    def __provided__(self) -> Any | None:
        # The return type should be a dict-of-lists object provided by the current materia provider.
        # For example, with SQLAlchemyMateria and collection_class=attribute_keyed_list_dict,
        # it would be a KeyFuncListDict.
        if not self.__instance_provider__:
            return None
        attr = self.__backing_attr__ or self.used_name
        return getattr(self.__instance_provider__, attr)

    @cached_property
    def __validator__(self) -> TypeAdapter[T]:
        return get_cached_adapter(self.__args__[1])

    @cached_property
    def __list_validator__(self) -> TypeAdapter[list[T]]:
        return get_cached_adapter(list[self.__args__[1]])

    @cached_property
    def __dict_validator__(self) -> TypeAdapter[dict[K, list[T]]]:
        return get_cached_adapter(dict[self.__args__[0], list[self.__args__[1]]])

    @cached_property
    def __key_validator__(self) -> TypeAdapter[K]:
        return get_cached_adapter(self.__args__[0])

    def bless_key(self, key: Any) -> K:
        """Validate and coerce a key into the key type."""
        target = self.__args__[0]
        if isinstance(target, type) and isinstance(key, target):
            return key
        return self.__key_validator__.validate_python(key)

    def bless_value(self, value: Any) -> T:
        """Validate and coerce a single value into the value type."""
        target = self.__args__[1]
        if isinstance(value, target):
            return value
        return self.__validator__.validate_python(value)

    def bless_values(self, values: Iterable[Any]) -> list[T]:
        """Validate and coerce a list of values into list[T]."""
        target = self.__args__[1]
        if all(isinstance(item, target) for item in values):
            return list(values)
        return self.__list_validator__.validate_python(values)

    def bless(self, value: Mapping[K, Any]) -> dict[K, list[T]]:
        """Validate and coerce an entire mapping into dict[K, list[T]]."""
        key_t, val_t = self.__args__[0], self.__args__[1]
        if (
            isinstance(key_t, type)
            and all(isinstance(k, key_t) for k in value)
            and all(isinstance(i, val_t) for lst in value.values() for i in lst)
        ):
            return {k: list(v) for k, v in value.items()}
        return self.__dict_validator__.validate_python(value)

    def prepare(self, instance: Transmuter, field_name: str):
        if self.__instance__ is not None:
            return

        self.field_name = field_name
        self.field_info = type(instance).__pydantic_fields__[field_name]

        self.__instance__ = instance

        annotation = self.field_info.annotation
        if isinstance(annotation, ForwardRef):
            resolved_hints = get_type_hints(type(instance))
            actual_type = resolved_hints[field_name]
            args = get_args(actual_type)
        else:
            args = get_args(annotation)

        self.__args__ = (args[0], args[1])

        if self.__payloads__:
            self._load()
            self._merge_payloads()
            self.__payloads__.clear()

    def _merge_payloads(self) -> None:
        """Merge __payloads__ into self (the loaded dict)."""
        for key, values in self.__payloads__.items():
            if key in self:
                existing = super().__getitem__(key)
                existing.extend(values)
            else:
                super().__setitem__(key, list(values))

    @staticmethod
    def ensure_loaded(
        func: Callable[Concatenate[RelationGroupMap[K, T], P], R],
    ) -> Callable[Concatenate[RelationGroupMap[K, T], P], R]:
        @wraps(func)
        def wrapper(
            self: RelationGroupMap[K, T], *args: P.args, **kwargs: P.kwargs
        ) -> R:
            self._load()
            return func(self, *args, **kwargs)

        return wrapper

    def _load(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # no backing provider (NoOpMateria / not-yet-persisted): nothing to load
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        provided = active_materia.get().load_association(self)

        # A: No provided, None
        # B: provided value is empty, {}
        if not provided:
            return self

        # Remove payloads whose key is already in provided
        self.__payloads__ = {
            k: v for k, v in self.__payloads__.items() if k not in provided
        }

        if len(provided) != super().__len__() or not super().__len__():
            # Bless: provided is a dict[K, list[ORM]] (e.g. KeyFuncListDict)
            super().clear()
            for key, orm_list in provided.items():
                super().__setitem__(key, self.bless_values(orm_list))
        self.__loaded__ = True

        return self

    async def _aload(self):
        # already loaded
        if self.__loaded__:
            return self

        # maybe during deepcopy from field default
        if not self.__instance__:
            return self

        # no backing provider: nothing to load
        if self.__instance_provider__ is None:
            self.__loaded__ = True
            return self

        # A: No provided, None
        # B: provided value is empty, {}
        if not (provided := await active_materia.get().aload_association(self)):
            return self

        # Remove payloads whose key is already in provided
        self.__payloads__ = {
            k: v for k, v in self.__payloads__.items() if k not in provided
        }

        if len(provided) != super().__len__() or not super().__len__():
            super().clear()
            for key, orm_list in provided.items():
                super().__setitem__(key, self.bless_values(orm_list))
        self.__loaded__ = True

        return self

    def __await__(self):
        return self._aload().__await__()

    @ensure_loaded
    def __getitem__(self, key: K) -> list[T]:
        key = self.bless_key(key)
        return super().__getitem__(key)

    @ensure_loaded
    def __iter__(self):
        return super().__iter__()

    @ensure_loaded
    def __len__(self):
        return super().__len__()

    @ensure_loaded
    def __contains__(self, key: object) -> bool:
        key = self.bless_key(key)
        return super().__contains__(key)

    @ensure_loaded
    def __bool__(self):
        return super().__len__() > 0

    @ensure_loaded
    @Association.ensure_mutable
    def __setitem__(self, key: K, value: list[T]) -> None:
        key = self.bless_key(key)
        value = self.bless_values(value)
        provided = self.__provided__
        if provided is not None:
            # Remove old items from provider, then add new ones
            if key in provided:
                old_items = list(dict.__getitem__(provided, key))
                for item in old_items:
                    provided.remove(item)
            for item in value:
                provided.set(item.__transmuter_provided__)
        super().__setitem__(key, value)

    @ensure_loaded
    @Association.ensure_mutable
    def __delitem__(self, key: K) -> None:
        key = self.bless_key(key)
        provided = self.__provided__
        if provided is not None and key in provided:
            old_items = list(dict.__getitem__(provided, key))
            for item in old_items:
                provided.remove(item)
        super().__delitem__(key)

    def __repr__(self):
        args = getattr(self, "__args__", None)
        if args and len(args) >= 2:
            key_type = args[0]
            value_type = args[1]
            key_name = getattr(key_type, "__name__", repr(key_type))
            value_name = getattr(value_type, "__name__", repr(value_type))
        else:
            key_name = value_name = "?"
        return f"RelationGroupMap[{key_name}, {value_name}], instance={id(self.__instance__)}, size={super().__len__()}"

    @ensure_loaded
    def __str__(self):
        return super().__str__()

    @ensure_loaded
    def __eq__(self, other: object) -> bool:
        if isinstance(other, dict):
            return dict.__eq__(self, other)
        return False

    @ensure_loaded
    def __ne__(self, other: object) -> bool:
        if isinstance(other, dict):
            return dict.__ne__(self, other)
        return True

    @ensure_loaded
    def __or__(self, other: Mapping[K, list[T]]) -> dict[K, list[T]]:
        return dict.__or__(self.copy(), dict(other))

    @ensure_loaded
    @Association.ensure_mutable
    def __ior__(self, other: Mapping[K, list[T]]) -> Self:
        self.update(other)
        return self

    @ensure_loaded
    def __reversed__(self):
        return super().__reversed__()

    @ensure_loaded
    def get(self, key: K, default: list[T] | None = None) -> list[T] | None:
        return super().get(self.bless_key(key), default)

    @ensure_loaded
    def keys(self):
        return super().keys()

    @ensure_loaded
    def values(self):
        return super().values()

    @ensure_loaded
    def items(self):
        return super().items()

    @overload
    def pop(self, key: K) -> list[T]: ...

    @overload
    def pop(self, key: K, default: list[T]) -> list[T]: ...

    @overload
    def pop(self, key: K, default: D) -> list[T] | D: ...

    @ensure_loaded
    @Association.ensure_mutable
    def pop(self, key: K, *args: Any) -> Any:
        """Remove specified key and return the corresponding list."""
        key = self.bless_key(key)
        item = super().pop(key, *args)
        provided = self.__provided__
        if provided is not None and key in provided:
            old_items = list(dict.__getitem__(provided, key))
            for old in old_items:
                provided.remove(old)
        return item

    @ensure_loaded
    @Association.ensure_mutable
    def popitem(self) -> tuple[K, list[T]]:
        """Remove and return an arbitrary (key, list) pair."""
        key, items = super().popitem()
        provided = self.__provided__
        if provided is not None and key in provided:
            old_items = list(dict.__getitem__(provided, key))
            for old in old_items:
                provided.remove(old)
        return key, items

    @overload
    def update(self, m: Mapping[K, list[T]], /, **kwargs: list[T]) -> None: ...
    @overload
    def update(self, m: Iterable[tuple[K, list[T]]], /, **kwargs: list[T]) -> None: ...
    @overload
    def update(self, **kwargs: list[T]) -> None: ...

    @ensure_loaded
    @Association.ensure_mutable
    def update(
        self,
        *args: Mapping[K, list[T]] | Iterable[tuple[K, list[T]]],
        **kwargs: list[T],
    ) -> None:
        """Update the dict with key-list pairs."""
        merged: dict[K, list[T]] = {}
        if args:
            if isinstance(args[0], Mapping):
                merged.update(args[0])
            else:
                merged.update(dict(*args))
        if kwargs:
            merged.update(kwargs)  # type: ignore[arg-type]

        if not merged:
            return

        blessed = self.bless(merged)
        provided = self.__provided__
        if provided is not None:
            for key, items in blessed.items():
                # Remove old items at this key from provider
                if key in provided:
                    old_items = list(dict.__getitem__(provided, key))
                    for old in old_items:
                        provided.remove(old)
                # Add new items
                for item in items:
                    provided.set(item.__transmuter_provided__)
        super().update(blessed)

    @overload
    def setdefault(self, key: K) -> list[T]: ...
    @overload
    def setdefault(self, key: K, default: list[T]) -> list[T]: ...

    @ensure_loaded
    @Association.ensure_mutable
    def setdefault(self, key: K, default: list[T] | None = None) -> list[T]:
        """If key is not in the dict, insert key with the default list."""
        key = self.bless_key(key)
        if key not in self:
            if default is not None:
                self[key] = default
            else:
                self[key] = []
        return super().__getitem__(key)

    @ensure_loaded
    @Association.ensure_mutable
    def clear(self) -> None:
        """Remove all items."""
        provided = self.__provided__
        if provided is not None:
            # Remove each item individually so SQLAlchemy fires proper remove events
            for key in list(dict.keys(provided)):
                items = list(dict.__getitem__(provided, key))
                for item in items:
                    provided.remove(item)
        super().clear()

    @ensure_loaded
    def copy(self) -> dict[K, list[T]]:
        return {k: list(v) for k, v in super().items()}

    # ── Convenience methods unique to grouped maps ──

    @ensure_loaded
    @Association.ensure_mutable
    def append(self, key: K, value: T) -> None:
        """Append a single item to the group at *key*, creating the group if needed."""
        key = self.bless_key(key)
        value = self.bless_value(value)
        if key not in self:
            super().__setitem__(key, [])
        super().__getitem__(key).append(value)
        provided = self.__provided__
        if provided is not None:
            provided.set(value.__transmuter_provided__)

    @ensure_loaded
    @Association.ensure_mutable
    def extend(self, key: K, values: Iterable[T]) -> None:
        """Append multiple items to the group at *key*."""
        key = self.bless_key(key)
        values = self.bless_values(values)
        if key not in self:
            super().__setitem__(key, [])
        super().__getitem__(key).extend(values)
        provided = self.__provided__
        if provided is not None:
            for item in values:
                provided.set(item.__transmuter_provided__)

    @ensure_loaded
    @Association.ensure_mutable
    def discard(self, key: K, value: T) -> None:
        """Remove a single item from the group at *key*.

        Removes the key entirely if its list becomes empty.
        """
        key = self.bless_key(key)
        lst = super().__getitem__(key)
        lst.remove(value)
        provided = self.__provided__
        if provided is not None:
            provided.remove(value.__transmuter_provided__)
        if not lst:
            super().__delitem__(key)

    @ensure_loaded
    def flatten(self) -> list[T]:
        """Return all values across all keys as a flat list."""
        result: list[T] = []
        for lst in super().values():
            result.extend(lst)
        return result

bless_key

bless_key(key: Any) -> K

Validate and coerce a key into the key type.

Source code in arcanus/association.py
def bless_key(self, key: Any) -> K:
    """Validate and coerce a key into the key type."""
    target = self.__args__[0]
    if isinstance(target, type) and isinstance(key, target):
        return key
    return self.__key_validator__.validate_python(key)

bless_value

bless_value(value: Any) -> T

Validate and coerce a single value into the value type.

Source code in arcanus/association.py
def bless_value(self, value: Any) -> T:
    """Validate and coerce a single value into the value type."""
    target = self.__args__[1]
    if isinstance(value, target):
        return value
    return self.__validator__.validate_python(value)

bless_values

bless_values(values: Iterable[Any]) -> list[T]

Validate and coerce a list of values into list[T].

Source code in arcanus/association.py
def bless_values(self, values: Iterable[Any]) -> list[T]:
    """Validate and coerce a list of values into list[T]."""
    target = self.__args__[1]
    if all(isinstance(item, target) for item in values):
        return list(values)
    return self.__list_validator__.validate_python(values)

bless

bless(value: Mapping[K, Any]) -> dict[K, list[T]]

Validate and coerce an entire mapping into dict[K, list[T]].

Source code in arcanus/association.py
def bless(self, value: Mapping[K, Any]) -> dict[K, list[T]]:
    """Validate and coerce an entire mapping into dict[K, list[T]]."""
    key_t, val_t = self.__args__[0], self.__args__[1]
    if (
        isinstance(key_t, type)
        and all(isinstance(k, key_t) for k in value)
        and all(isinstance(i, val_t) for lst in value.values() for i in lst)
    ):
        return {k: list(v) for k, v in value.items()}
    return self.__dict_validator__.validate_python(value)

pop

pop(key: K) -> list[T]
pop(key: K, default: list[T]) -> list[T]
pop(key: K, default: D) -> list[T] | D
pop(key: K, *args: Any) -> Any

Remove specified key and return the corresponding list.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def pop(self, key: K, *args: Any) -> Any:
    """Remove specified key and return the corresponding list."""
    key = self.bless_key(key)
    item = super().pop(key, *args)
    provided = self.__provided__
    if provided is not None and key in provided:
        old_items = list(dict.__getitem__(provided, key))
        for old in old_items:
            provided.remove(old)
    return item

popitem

popitem() -> tuple[K, list[T]]

Remove and return an arbitrary (key, list) pair.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def popitem(self) -> tuple[K, list[T]]:
    """Remove and return an arbitrary (key, list) pair."""
    key, items = super().popitem()
    provided = self.__provided__
    if provided is not None and key in provided:
        old_items = list(dict.__getitem__(provided, key))
        for old in old_items:
            provided.remove(old)
    return key, items

update

update(m: Mapping[K, list[T]], /, **kwargs: list[T]) -> None
update(m: Iterable[tuple[K, list[T]]], /, **kwargs: list[T]) -> None
update(**kwargs: list[T]) -> None
update(*args: Mapping[K, list[T]] | Iterable[tuple[K, list[T]]], **kwargs: list[T]) -> None

Update the dict with key-list pairs.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def update(
    self,
    *args: Mapping[K, list[T]] | Iterable[tuple[K, list[T]]],
    **kwargs: list[T],
) -> None:
    """Update the dict with key-list pairs."""
    merged: dict[K, list[T]] = {}
    if args:
        if isinstance(args[0], Mapping):
            merged.update(args[0])
        else:
            merged.update(dict(*args))
    if kwargs:
        merged.update(kwargs)  # type: ignore[arg-type]

    if not merged:
        return

    blessed = self.bless(merged)
    provided = self.__provided__
    if provided is not None:
        for key, items in blessed.items():
            # Remove old items at this key from provider
            if key in provided:
                old_items = list(dict.__getitem__(provided, key))
                for old in old_items:
                    provided.remove(old)
            # Add new items
            for item in items:
                provided.set(item.__transmuter_provided__)
    super().update(blessed)

setdefault

setdefault(key: K) -> list[T]
setdefault(key: K, default: list[T]) -> list[T]
setdefault(key: K, default: list[T] | None = None) -> list[T]

If key is not in the dict, insert key with the default list.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def setdefault(self, key: K, default: list[T] | None = None) -> list[T]:
    """If key is not in the dict, insert key with the default list."""
    key = self.bless_key(key)
    if key not in self:
        if default is not None:
            self[key] = default
        else:
            self[key] = []
    return super().__getitem__(key)

clear

clear() -> None

Remove all items.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def clear(self) -> None:
    """Remove all items."""
    provided = self.__provided__
    if provided is not None:
        # Remove each item individually so SQLAlchemy fires proper remove events
        for key in list(dict.keys(provided)):
            items = list(dict.__getitem__(provided, key))
            for item in items:
                provided.remove(item)
    super().clear()

append

append(key: K, value: T) -> None

Append a single item to the group at key, creating the group if needed.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def append(self, key: K, value: T) -> None:
    """Append a single item to the group at *key*, creating the group if needed."""
    key = self.bless_key(key)
    value = self.bless_value(value)
    if key not in self:
        super().__setitem__(key, [])
    super().__getitem__(key).append(value)
    provided = self.__provided__
    if provided is not None:
        provided.set(value.__transmuter_provided__)

extend

extend(key: K, values: Iterable[T]) -> None

Append multiple items to the group at key.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def extend(self, key: K, values: Iterable[T]) -> None:
    """Append multiple items to the group at *key*."""
    key = self.bless_key(key)
    values = self.bless_values(values)
    if key not in self:
        super().__setitem__(key, [])
    super().__getitem__(key).extend(values)
    provided = self.__provided__
    if provided is not None:
        for item in values:
            provided.set(item.__transmuter_provided__)

discard

discard(key: K, value: T) -> None

Remove a single item from the group at key.

Removes the key entirely if its list becomes empty.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def discard(self, key: K, value: T) -> None:
    """Remove a single item from the group at *key*.

    Removes the key entirely if its list becomes empty.
    """
    key = self.bless_key(key)
    lst = super().__getitem__(key)
    lst.remove(value)
    provided = self.__provided__
    if provided is not None:
        provided.remove(value.__transmuter_provided__)
    if not lst:
        super().__delitem__(key)

flatten

flatten() -> list[T]

Return all values across all keys as a flat list.

Source code in arcanus/association.py
@ensure_loaded
def flatten(self) -> list[T]:
    """Return all values across all keys as a flat list."""
    result: list[T] = []
    for lst in super().values():
        result.extend(lst)
    return result

TypedRelationMap

Bases: dict, Association[TD]

A dict-based association whose keys and per-key value types are defined by a TypedDict.

Unlike :class:RelationMap which maps homogeneous dict[K, T], this class accepts a single TypedDict generic argument so that each key can have its own Transmuter type. This is designed for polymorphic relationships where different keys correspond to different subclasses.

Usage::

class DocumentFiles(TypedDict):
    image: Image
    video: Video

class Document(BaseTransmuter):
    files: TypedRelationMap[DocumentFiles] = TypedRelationship()

All values in the TypedDict must be Transmuter subclasses.

Source code in arcanus/association.py
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
class TypedRelationMap(dict, Association[TD]):
    """A dict-based association whose keys and per-key value types are defined
    by a ``TypedDict``.

    Unlike :class:`RelationMap` which maps homogeneous ``dict[K, T]``, this
    class accepts a single ``TypedDict`` generic argument so that each key can
    have its own Transmuter type.  This is designed for polymorphic
    relationships where different keys correspond to different subclasses.

    Usage::

        class DocumentFiles(TypedDict):
            image: Image
            video: Video

        class Document(BaseTransmuter):
            files: TypedRelationMap[DocumentFiles] = TypedRelationship()

    All values in the TypedDict **must** be ``Transmuter`` subclasses.
    """

    # new items are held in __payloads__, loaded items are kept in the dict itself
    __payloads__: dict[str, Any]
    __typed_dict__: type  # the TypedDict class itself

    @classmethod
    def __get_pydantic_generic_schema__(
        cls,
        typed_dict_cls: type,
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        return handler.generate_schema(typed_dict_cls)

    @classmethod
    def __get_pydantic_serialize_schema__(
        cls,
        typed_dict_cls: type,
        handler: GetCoreSchemaHandler,
    ) -> core_schema.SerSchema | None:
        def serialize(association: TypedRelationMap, serializer) -> Any:
            instance = association.__instance__
            fields_set = getattr(instance, "__pydantic_fields_set__", None)
            if fields_set is None or association.field_name not in fields_set:
                return serializer(dict.copy(association) | association.__payloads__)
            with _AsAncestor(instance) as ancestors:
                return serializer(
                    {
                        key: value
                        for key, value in association.copy().items()
                        if id(value) not in ancestors
                    }
                )

        # Build a union schema from the TypedDict value types for serialization.
        # Using a plain dict schema avoids the TypedDict's totality constraint
        # so partial dicts (e.g. loaded from DB) serialize correctly.
        hints = get_type_hints(typed_dict_cls)
        value_types = list(dict.fromkeys(hints.values()))  # unique, order-preserved
        if len(value_types) == 1:
            values_schema = handler.generate_schema(value_types[0])
        else:
            values_schema = core_schema.union_schema(
                [handler.generate_schema(t) for t in value_types]
            )

        return core_schema.wrap_serializer_function_ser_schema(
            serialize,
            schema=core_schema.dict_schema(
                keys_schema=core_schema.str_schema(),
                values_schema=values_schema,
            ),
            when_used="always",
        )

    @classmethod
    def __get_pydantic_core_schema__(
        cls,
        source_type: Type[TypedRelationMap],
        handler: GetCoreSchemaHandler,
    ) -> core_schema.CoreSchema:
        args = get_args(source_type)

        if not args or len(args) != 1:
            raise TypeError(
                f"Exactly one TypedDict generic type must be provided to {source_type}."
            )

        typed_dict_cls = args[0]

        if not is_typeddict(typed_dict_cls):
            raise TypeError(
                f"The generic argument to TypedRelationMap must be a TypedDict, "
                f"got {typed_dict_cls!r}."
            )

        def validate(
            value: Any,
            handler: core_schema.ValidatorFunctionWrapHandler,
            info: core_schema.ValidationInfo,
        ) -> TypedRelationMap:
            if value is DefferedAssociation:
                instance = cls()
            elif type(value) is cls:
                instance = value
                instance.__payloads__ = handler(instance.__payloads__)
            else:
                instance = cls(handler(value))

            instance.__args__ = (typed_dict_cls,)
            instance.__typed_dict__ = typed_dict_cls
            instance.field_name = info.field_name  # pyright: ignore[reportAttributeAccessIssue]

            return instance

        return core_schema.with_default_schema(
            core_schema.with_info_wrap_validator_function(
                validate,
                cls.__get_pydantic_generic_schema__(typed_dict_cls, handler),
            ),
            default_factory=cls,
            serialization=cls.__get_pydantic_serialize_schema__(
                typed_dict_cls, handler
            ),
        )

    @cached_property
    def __typed_hints__(self) -> dict[str, type]:
        """Per-key type hints resolved from the TypedDict."""
        return get_type_hints(self.__typed_dict__)

    @cached_property
    def __validator__(self) -> TypeAdapter:
        """Whole-dict TypedDict validator."""
        return get_cached_adapter(self.__typed_dict__)

    def bless(self, value: Mapping[str, Any]) -> dict[str, Any]:
        """Validate and coerce an entire mapping against the TypedDict schema."""
        return self.__validator__.validate_python(value)

    def bless_value(self, key: str, value: Any) -> Any:
        """Validate a single value against the type declared for *key*."""
        expected_type = self.__typed_hints__.get(key)
        if expected_type is None:
            raise KeyError(
                f"Key {key!r} is not defined in {self.__typed_dict__.__name__}."
            )
        return get_cached_adapter(expected_type).validate_python(value)

    def __init__(self, payloads: Mapping[str, Any] | None = None):
        super().__init__()
        self.__instance__ = None
        self.__loaded__ = False
        self.__payloads__ = dict(payloads) if payloads else {}

    @property
    def __provided__(self) -> dict | None:
        if not self.__instance_provider__:
            return None
        return getattr(self.__instance_provider__, self.used_name)

    def prepare(self, instance: Transmuter, field_name: str):
        if self.__instance__ is not None:
            return

        self.field_name = field_name
        self.field_info = type(instance).__pydantic_fields__[field_name]

        self.__instance__ = instance

        annotation = self.field_info.annotation
        if isinstance(annotation, ForwardRef):
            resolved_hints = get_type_hints(type(instance))
            actual_type = resolved_hints[field_name]
            args = get_args(actual_type)
        else:
            args = get_args(annotation)

        self.__typed_dict__ = args[0]
        self.__args__ = (args[0],)

        if self.__payloads__:
            self._load()
            provided = self.__provided__
            if provided is not None:
                provided.update(
                    {
                        key: value.__transmuter_provided__
                        for key, value in self.__payloads__.items()
                    }
                )
            super().update(self.__payloads__)
            self.__payloads__.clear()

    @staticmethod
    def ensure_loaded(
        func: Callable[Concatenate[TypedRelationMap, P], R],
    ) -> Callable[Concatenate[TypedRelationMap, P], R]:
        @wraps(func)
        def wrapper(self: TypedRelationMap, *args: P.args, **kwargs: P.kwargs) -> R:
            self._load()
            return func(self, *args, **kwargs)

        return wrapper

    def _load(self):
        if not self.__instance__:
            return self

        if self.__loaded__:
            return self

        active_materia.get().load_association(self)

        if not self.__provided__:
            return self

        # Remove payloads whose key is already in __provided__
        self.__payloads__ = {
            k: v for k, v in self.__payloads__.items() if k not in self.__provided__
        }

        if len(self.__provided__) != super().__len__():
            super().clear()
            # Validate per-key: DB state may be partial (not all TypedDict keys present)
            super().update(
                {k: self.bless_value(k, v) for k, v in self.__provided__.items()}
            )
        self.__loaded__ = True

        return self

    async def _aload(self):
        if not self.__instance__:
            return self

        if self.__loaded__:
            return self

        if not (provided := await active_materia.get().aload_association(self)):
            return self

        self.__payloads__ = {
            k: v for k, v in self.__payloads__.items() if k not in provided
        }

        if len(provided) != super().__len__():
            super().clear()
            # Validate per-key: DB state may be partial (not all TypedDict keys present)
            super().update({k: self.bless_value(k, v) for k, v in provided.items()})
        self.__loaded__ = True

        return self

    def __await__(self):
        return self._aload().__await__()

    @ensure_loaded
    def __getitem__(self, key: str) -> Any:
        return super().__getitem__(key)

    @ensure_loaded
    def __iter__(self):
        return super().__iter__()

    @ensure_loaded
    def __len__(self):
        return super().__len__()

    @ensure_loaded
    def __contains__(self, key: object) -> bool:
        return super().__contains__(key)

    @ensure_loaded
    def __bool__(self):
        return super().__len__() > 0

    @ensure_loaded
    @Association.ensure_mutable
    def __setitem__(self, key: str, value: Any) -> None:
        value = self.bless_value(key, value)
        provided = self.__provided__
        if provided is not None:
            provided[key] = value.__transmuter_provided__
        super().__setitem__(key, value)

    @ensure_loaded
    @Association.ensure_mutable
    def __delitem__(self, key: str) -> None:
        provided = self.__provided__
        if provided is not None:
            del provided[key]
        super().__delitem__(key)

    def __repr__(self):
        typed_dict = getattr(self, "__typed_dict__", None)
        td_name = (
            getattr(typed_dict, "__name__", repr(typed_dict))
            if typed_dict is not None
            else "?"
        )
        return f"TypedRelationMap[{td_name}], instance={id(self.__instance__)}, size={super().__len__()}"

    @ensure_loaded
    def __str__(self):
        return dict.__repr__(self)

    @ensure_loaded
    def __eq__(self, other: object) -> bool:
        if isinstance(other, dict):
            return dict.__eq__(self, other)
        return False

    @ensure_loaded
    def __ne__(self, other: object) -> bool:
        if isinstance(other, dict):
            return dict.__ne__(self, other)
        return True

    @ensure_loaded
    def __or__(self, other: Mapping[str, Any]) -> dict[str, Any]:
        return dict.__or__(self.copy(), dict(other))

    @ensure_loaded
    @Association.ensure_mutable
    def __ior__(self, other: Mapping[str, Any]) -> Self:
        self.update(other)
        return self

    @ensure_loaded
    def __reversed__(self):
        return super().__reversed__()

    @ensure_loaded
    def get(self, key: str, default: Any = None) -> Any:
        return super().get(key, default)

    @ensure_loaded
    def keys(self):
        return super().keys()

    @ensure_loaded
    def values(self):
        return super().values()

    @ensure_loaded
    def items(self):
        return super().items()

    @ensure_loaded
    @Association.ensure_mutable
    def pop(self, key: str, *args: Any) -> Any:
        """Remove specified key and return the corresponding value."""
        item = super().pop(key, *args)
        provided = self.__provided__
        if provided is not None and key in provided:
            del provided[key]
        return item

    @ensure_loaded
    @Association.ensure_mutable
    def popitem(self) -> tuple[str, Any]:
        """Remove and return an arbitrary (key, value) pair."""
        key, item = super().popitem()
        provided = self.__provided__
        if provided is not None:
            del provided[key]
        return key, item

    @ensure_loaded
    @Association.ensure_mutable
    def update(
        self,
        *args: Mapping[str, Any] | Iterable[tuple[str, Any]],
        **kwargs: Any,
    ) -> None:
        """Update the dict with key-value pairs, validating per-key."""
        merged: dict[str, Any] = {}
        if args:
            if isinstance(args[0], Mapping):
                merged.update(args[0])
            else:
                merged.update(dict(*args))
        if kwargs:
            merged.update(kwargs)

        if not merged:
            return

        # Validate per-key to allow partial updates (not all TypedDict keys required)
        blessed: dict[str, Any] = {}
        for key, value in merged.items():
            blessed[key] = self.bless_value(key, value)
        provided = self.__provided__
        if provided is not None:
            provided.update(
                {key: value.__transmuter_provided__ for key, value in blessed.items()}
            )
        super().update(blessed)

    @ensure_loaded
    @Association.ensure_mutable
    def setdefault(self, key: str, default: Any = None) -> Any:
        """If key is not in the dict, insert key with the default value."""
        if key not in self:
            if default is not None:
                self[key] = default
        return super().get(key, default)

    @ensure_loaded
    @Association.ensure_mutable
    def clear(self) -> None:
        """Remove all items."""
        provided = self.__provided__
        if provided is not None:
            provided.clear()
        super().clear()

    @ensure_loaded
    def copy(self) -> dict[str, Any]:
        return super().copy()

bless

bless(value: Mapping[str, Any]) -> dict[str, Any]

Validate and coerce an entire mapping against the TypedDict schema.

Source code in arcanus/association.py
def bless(self, value: Mapping[str, Any]) -> dict[str, Any]:
    """Validate and coerce an entire mapping against the TypedDict schema."""
    return self.__validator__.validate_python(value)

bless_value

bless_value(key: str, value: Any) -> Any

Validate a single value against the type declared for key.

Source code in arcanus/association.py
def bless_value(self, key: str, value: Any) -> Any:
    """Validate a single value against the type declared for *key*."""
    expected_type = self.__typed_hints__.get(key)
    if expected_type is None:
        raise KeyError(
            f"Key {key!r} is not defined in {self.__typed_dict__.__name__}."
        )
    return get_cached_adapter(expected_type).validate_python(value)

pop

pop(key: str, *args: Any) -> Any

Remove specified key and return the corresponding value.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def pop(self, key: str, *args: Any) -> Any:
    """Remove specified key and return the corresponding value."""
    item = super().pop(key, *args)
    provided = self.__provided__
    if provided is not None and key in provided:
        del provided[key]
    return item

popitem

popitem() -> tuple[str, Any]

Remove and return an arbitrary (key, value) pair.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def popitem(self) -> tuple[str, Any]:
    """Remove and return an arbitrary (key, value) pair."""
    key, item = super().popitem()
    provided = self.__provided__
    if provided is not None:
        del provided[key]
    return key, item

update

update(*args: Mapping[str, Any] | Iterable[tuple[str, Any]], **kwargs: Any) -> None

Update the dict with key-value pairs, validating per-key.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def update(
    self,
    *args: Mapping[str, Any] | Iterable[tuple[str, Any]],
    **kwargs: Any,
) -> None:
    """Update the dict with key-value pairs, validating per-key."""
    merged: dict[str, Any] = {}
    if args:
        if isinstance(args[0], Mapping):
            merged.update(args[0])
        else:
            merged.update(dict(*args))
    if kwargs:
        merged.update(kwargs)

    if not merged:
        return

    # Validate per-key to allow partial updates (not all TypedDict keys required)
    blessed: dict[str, Any] = {}
    for key, value in merged.items():
        blessed[key] = self.bless_value(key, value)
    provided = self.__provided__
    if provided is not None:
        provided.update(
            {key: value.__transmuter_provided__ for key, value in blessed.items()}
        )
    super().update(blessed)

setdefault

setdefault(key: str, default: Any = None) -> Any

If key is not in the dict, insert key with the default value.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def setdefault(self, key: str, default: Any = None) -> Any:
    """If key is not in the dict, insert key with the default value."""
    if key not in self:
        if default is not None:
            self[key] = default
    return super().get(key, default)

clear

clear() -> None

Remove all items.

Source code in arcanus/association.py
@ensure_loaded
@Association.ensure_mutable
def clear(self) -> None:
    """Remove all items."""
    provided = self.__provided__
    if provided is not None:
        provided.clear()
    super().clear()

Relationships

Relationships(*, unique: Literal[True], frozen: bool = ..., **kwargs: Any) -> Any
Relationships(*, unique: Literal[False] = ..., frozen: bool = ..., **kwargs: Any) -> Any
Relationships(*, frozen: bool = ..., **kwargs: Any) -> Any
Relationships(*, unique: bool = False, frozen: bool = False, **kwargs: Any) -> Any

Create a relationship field for a collection of related transmuters.

Parameters:

Name Type Description Default
unique bool

If True, use a RelationSet (set semantics, no duplicates). If False (default), use a RelationCollection (list semantics).

False
frozen bool

If True, block mutation methods on the association contents.

False
**kwargs Any

Additional keyword arguments passed to pydantic's Field().

{}

Returns:

Type Description
Any

A pydantic Field configured with the appropriate default_factory.

Source code in arcanus/association.py
def Relationships(*, unique: bool = False, frozen: bool = False, **kwargs: Any) -> Any:
    """Create a relationship field for a collection of related transmuters.

    Args:
        unique: If True, use a RelationSet (set semantics, no duplicates).
                If False (default), use a RelationCollection (list semantics).
        frozen: If True, block mutation methods on the association contents.
        **kwargs: Additional keyword arguments passed to pydantic's Field().

    Returns:
        A pydantic Field configured with the appropriate default_factory.
    """
    factory = RelationSet if unique else RelationCollection
    return Field(default_factory=factory, frozen=frozen, **kwargs)