Skip to content

API Reference

Auto-generated from source docstrings via mkdocstrings.


GenericLinkedBaseModel

Base class for all linked data models. Provides JSON-LD serialization, type registry, and the to_jsonld() / to_json() methods.

Source code in src/oold/static.py
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
class GenericLinkedBaseModel:
    def _object_to_iri(self, d, exclude_none=False):
        for name in list(d.keys()):  # force copy of keys for inline-delete
            if name in self.__iris__:
                d[name] = self.__iris__[name]
            if exclude_none and d[name] is None:
                del d[name]
        return d

    @staticmethod
    def remove_none(d: dict) -> dict:
        """Remove None values from a dictionary recursively."""
        if isinstance(d, dict):
            return {k: GenericLinkedBaseModel.remove_none(v) for k, v in d.items() if v is not None}
        elif isinstance(d, list):
            return [GenericLinkedBaseModel.remove_none(i) for i in d]
        else:
            return d

    @classmethod
    def export_schema(
        cls,
        mode: SchemaExportMode | None = SchemaExportMode.FULL,
        cutoff_base_cls: BaseModel | BaseModel_v1 | tuple[BaseModel | BaseModel_v1] | None = None,
        partial_mode: PartialSchemaExportMode | None = PartialSchemaExportMode.BASE_CLASS_CUTOFF,
        serialize: Literal["json", "yaml"] | None = None,
    ) -> dict:
        """Export the schema of the model as a dictionary."""
        schema = export_schema(cls, mode, cutoff_base_cls, partial_mode)
        if serialize == "json":
            return json.dumps(schema, indent=2)
        elif serialize == "yaml":
            _ignore_aliases = yaml.Dumper.ignore_aliases
            yaml.Dumper.ignore_aliases = lambda *args: True
            yaml_doc = yaml.dump(schema, indent=2)
            yaml.Dumper.ignore_aliases = _ignore_aliases
            return yaml_doc
        return schema

    @classmethod
    @abstractmethod
    def from_jsonld(cls, jsonld: dict) -> "GenericLinkedBaseModel":
        """Constructs a model instance from a JSON-LD representation."""
        pass

    @abstractmethod
    def to_jsonld(self) -> dict:
        """Returns the JSON-LD representation of the model instance as a dictionary."""
        pass

    @classmethod
    @abstractmethod
    def from_json(cls, json_dict: dict) -> "GenericLinkedBaseModel":
        """Constructs a model instance from a JSON representation.
        Note: the given JSON must contain a field to identify the model class,
        default is 'type'."""
        pass

    @abstractmethod
    def to_json(self) -> dict:
        """Return the JSON representation of the object as a dictionary."""
        pass

    @abstractmethod
    def store_jsonld(self):
        """Store the model instance in a backend matching its IRI."""
        pass

    @classmethod
    @abstractmethod
    def get_cls_iri(cls) -> str | list[str] | None:
        """Get the IRI of the model itself.
        It will be used as key for a type registry and should be stored
        in the type field of the JSON(-LD) representation.
        May return both a expanded and a compacted IRI as list of strings."""
        pass

    @classmethod
    def get_type_field(cls) -> str:
        """Get the name of the field that stores the type information.
        It is expected to be aliased or mapped to '@type' in JSON-LD.
        Defaults to 'type'."""
        return "type"

export_schema(mode=SchemaExportMode.FULL, cutoff_base_cls=None, partial_mode=PartialSchemaExportMode.BASE_CLASS_CUTOFF, serialize=None) classmethod

Export the schema of the model as a dictionary.

Source code in src/oold/static.py
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
@classmethod
def export_schema(
    cls,
    mode: SchemaExportMode | None = SchemaExportMode.FULL,
    cutoff_base_cls: BaseModel | BaseModel_v1 | tuple[BaseModel | BaseModel_v1] | None = None,
    partial_mode: PartialSchemaExportMode | None = PartialSchemaExportMode.BASE_CLASS_CUTOFF,
    serialize: Literal["json", "yaml"] | None = None,
) -> dict:
    """Export the schema of the model as a dictionary."""
    schema = export_schema(cls, mode, cutoff_base_cls, partial_mode)
    if serialize == "json":
        return json.dumps(schema, indent=2)
    elif serialize == "yaml":
        _ignore_aliases = yaml.Dumper.ignore_aliases
        yaml.Dumper.ignore_aliases = lambda *args: True
        yaml_doc = yaml.dump(schema, indent=2)
        yaml.Dumper.ignore_aliases = _ignore_aliases
        return yaml_doc
    return schema

from_json(json_dict) abstractmethod classmethod

Constructs a model instance from a JSON representation. Note: the given JSON must contain a field to identify the model class, default is 'type'.

Source code in src/oold/static.py
227
228
229
230
231
232
233
@classmethod
@abstractmethod
def from_json(cls, json_dict: dict) -> "GenericLinkedBaseModel":
    """Constructs a model instance from a JSON representation.
    Note: the given JSON must contain a field to identify the model class,
    default is 'type'."""
    pass

from_jsonld(jsonld) abstractmethod classmethod

Constructs a model instance from a JSON-LD representation.

Source code in src/oold/static.py
216
217
218
219
220
@classmethod
@abstractmethod
def from_jsonld(cls, jsonld: dict) -> "GenericLinkedBaseModel":
    """Constructs a model instance from a JSON-LD representation."""
    pass

get_cls_iri() abstractmethod classmethod

Get the IRI of the model itself. It will be used as key for a type registry and should be stored in the type field of the JSON(-LD) representation. May return both a expanded and a compacted IRI as list of strings.

Source code in src/oold/static.py
245
246
247
248
249
250
251
252
@classmethod
@abstractmethod
def get_cls_iri(cls) -> str | list[str] | None:
    """Get the IRI of the model itself.
    It will be used as key for a type registry and should be stored
    in the type field of the JSON(-LD) representation.
    May return both a expanded and a compacted IRI as list of strings."""
    pass

get_type_field() classmethod

Get the name of the field that stores the type information. It is expected to be aliased or mapped to '@type' in JSON-LD. Defaults to 'type'.

Source code in src/oold/static.py
254
255
256
257
258
259
@classmethod
def get_type_field(cls) -> str:
    """Get the name of the field that stores the type information.
    It is expected to be aliased or mapped to '@type' in JSON-LD.
    Defaults to 'type'."""
    return "type"

remove_none(d) staticmethod

Remove None values from a dictionary recursively.

Source code in src/oold/static.py
186
187
188
189
190
191
192
193
194
@staticmethod
def remove_none(d: dict) -> dict:
    """Remove None values from a dictionary recursively."""
    if isinstance(d, dict):
        return {k: GenericLinkedBaseModel.remove_none(v) for k, v in d.items() if v is not None}
    elif isinstance(d, list):
        return [GenericLinkedBaseModel.remove_none(i) for i in d]
    else:
        return d

store_jsonld() abstractmethod

Store the model instance in a backend matching its IRI.

Source code in src/oold/static.py
240
241
242
243
@abstractmethod
def store_jsonld(self):
    """Store the model instance in a backend matching its IRI."""
    pass

to_json() abstractmethod

Return the JSON representation of the object as a dictionary.

Source code in src/oold/static.py
235
236
237
238
@abstractmethod
def to_json(self) -> dict:
    """Return the JSON representation of the object as a dictionary."""
    pass

to_jsonld() abstractmethod

Returns the JSON-LD representation of the model instance as a dictionary.

Source code in src/oold/static.py
222
223
224
225
@abstractmethod
def to_jsonld(self) -> dict:
    """Returns the JSON-LD representation of the model instance as a dictionary."""
    pass

LinkedBaseModel (v2)

Pydantic v2 implementation. Adds IRI-transparent field resolution, lazy loading, cast(), and the [] subscript operator.

Bases: BaseModel, GenericLinkedBaseModel

LinkedBaseModel for pydantic v2

Source code in src/oold/model/__init__.py
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
class LinkedBaseModel(BaseModel, GenericLinkedBaseModel, metaclass=LinkedBaseModelMetaClass):
    """LinkedBaseModel for pydantic v2"""

    __iris__: dict[str, str | list[str]] | None = {}

    @classmethod
    def get_cls_iri(cls) -> str | list[str] | None:
        """Return the unique IRI of the class.
        Overwrite this method in the subclass."""
        schema = {}
        # pydantic v2
        if hasattr(cls, "model_config") and "json_schema_extra" in cls.model_config:
            schema = cls.model_config["json_schema_extra"]

        cls_iri = []
        # schema annotation - should be expanded IRI
        if "$id" in schema:
            cls_iri.append(schema["$id"])
        elif "iri" in schema:
            cls_iri.append(schema["iri"])
        # default value of type field - may be compacted IRI
        type_field_name = cls.get_type_field()
        # pydantic v2
        type_field = cls.model_fields.get(type_field_name, None)
        if type_field is not None and type_field.default not in cls_iri:
            cls_iri.append(type_field.default)

        if len(cls_iri) == 0:
            return None
        elif len(cls_iri) == 1:
            return cls_iri[0]
        else:
            return cls_iri

    def get_iri(self) -> str:
        """Return the unique IRI of the object.
        Overwrite this method in the subclass."""
        return self.id

    @classmethod
    def model_validate(
        cls,
        obj: Any,
        *,
        strict: bool | None = None,
        from_attributes: bool | None = None,
        context: Any | None = None,
    ) -> Self:
        """Validate a pydantic model instance.

        Args:
            obj: The object to validate.
            strict: Whether to enforce types strictly.
            from_attributes: Whether to extract data from object attributes.
            context: Additional context to pass to the validator.

        Raises:
            ValidationError: If the object could not be validated.

        Returns:
            The validated model instance.
        """
        if isinstance(obj, str):
            return cls._resolve([obj])[obj]
        if isinstance(obj, list):
            node_dict = cls._resolve(obj)
            node_list = []
            for iri in obj:
                node = node_dict[iri]
                if node:
                    node_list.append(node)
            return node_list
        elif isinstance(obj, dict):
            super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context)

    def __init__(self, *a, **kw):
        # Accept a model instance as first positional arg:
        # TargetModel(source_model, extra_field=value)
        if a and isinstance(a[0], BaseModel):
            source = a[0]
            result = source.cast(type(self), **kw)
            kw = result._raw_dict()
            kw["__iris__"] = getattr(result, "__iris__", {})
            a = ()

        if "__iris__" not in kw:
            kw["__iris__"] = {}

        for name in list(kw):  # force copy of keys for inline-delete
            if name == "__iris__":
                continue
            if name not in self.model_fields:
                continue
            # rewrite <attr> to <attr>_iri
            # pprint(self.__fields__)
            extra = None
            # pydantic v1
            # if name in self.__fields__:
            #     if hasattr(self.__fields__[name].default, "json_schema_extra"):
            #         extra = self.__fields__[name].default.json_schema_extra
            #     elif hasattr(self.__fields__[name].field_info, "extra"):
            #         extra = self.__fields__[name].field_info.extra
            # pydantic v2
            extra = self.model_fields[name].json_schema_extra

            if extra and "range" in extra:
                arg_is_list = isinstance(kw[name], list)

                # annotation_is_list = False
                # args = self.model_fields[name].annotation.__args__
                # if hasattr(args[0], "_name"):
                #    is_list = args[0]._name == "List"
                if arg_is_list:
                    kw["__iris__"][name] = []
                    for e in kw[name][:]:  # interate over copy of list
                        if isinstance(e, BaseModel):  # contructed with object ref
                            kw["__iris__"][name].append(e.get_iri())
                        elif isinstance(e, str):  # constructed from json
                            kw["__iris__"][name].append(e)
                            kw[name].remove(e)  # remove to construct valid instance
                    if len(kw[name]) == 0:
                        # pydantic v1
                        # kw[name] = None # else pydantic v1 will set a FieldInfo object
                        # pydantic v2
                        kw[name] = None  # else default value may be set
                else:
                    if isinstance(kw[name], BaseModel):  # contructed with object ref
                        # print(kw[name].id)
                        kw["__iris__"][name] = kw[name].get_iri()
                    elif isinstance(kw[name], str):  # constructed from json
                        kw["__iris__"][name] = kw[name]
                        # pydantic v1
                        # kw[name] = None # else pydantic v1 will set a FieldInfo object
                        # pydantic v2
                        kw[name] = None  # else default value may be set

        BaseModel.__init__(self, *a, **kw)
        # handle default values
        for name in list(self.__dict__.keys()):
            if self.__dict__[name] is None:
                continue
            extra = None
            # pydantic v1
            # if name in self.__fields__:
            #     if hasattr(self.__fields__[name].default, "json_schema_extra"):
            #         extra = self.__fields__[name].default.json_schema_extra
            #     elif hasattr(self.__fields__[name].field_info, "extra"):
            #         extra = self.__fields__[name].field_info.extra
            # pydantic v2
            extra = self.model_fields[name].json_schema_extra

            if extra and "range" in extra:
                arg_is_list = isinstance(self.__dict__, list)

                if arg_is_list:
                    kw["__iris__"][name] = []
                    for e in self.__dict__[name]:
                        if isinstance(e, BaseModel):  # contructed with object ref
                            kw["__iris__"][name].append(e.get_iri())
                else:
                    if isinstance(self.__dict__[name], BaseModel):  # contructed with object ref
                        kw["__iris__"][name] = self.__dict__[name].get_iri()

        self.__iris__ = kw["__iris__"]

        # iterate over all fields
        # if x-oold-required-iri occurs in extra and the field is not set in __iri__
        # throw an error
        for name in self.model_fields:
            extra = None
            # pydantic v1
            # if name in self.__fields__:
            #     if hasattr(self.__fields__[name].default, "json_schema_extra"):
            #         extra = self.__fields__[name].default.json_schema_extra
            #     elif hasattr(self.__fields__[name].field_info, "extra"):
            #         extra = self.__fields__[name].field_info.extra
            # pydantic v2
            extra = self.model_fields[name].json_schema_extra

            if extra and "x-oold-required-iri" in extra and name not in self.__iris__:
                raise ValueError(f"{name} is required but not set")

    def _handle_value(self, name, value):
        extra = None
        # pydantic v1
        # if name in self.__fields__:
        #     if hasattr(self.__fields__[name].default, "json_schema_extra"):
        #         extra = self.__fields__[name].default.json_schema_extra
        #     elif hasattr(self.__fields__[name].field_info, "extra"):
        #         extra = self.__fields__[name].field_info.extra
        # pydantic v2
        extra = self.model_fields[name].json_schema_extra

        if extra and "range" in extra:
            arg_is_list = isinstance(value, list)

            if arg_is_list:
                self.__iris__[name] = []
                for e in value[:]:  # interate over copy of list
                    if isinstance(e, BaseModel):  # contructed with object ref
                        self.__iris__[name].append(e.get_iri())
                    elif isinstance(e, str):  # constructed from json
                        self.__iris__[name].append(e)
                        value.remove(e)  # remove to construct valid instance
                if len(value) == 0:
                    # pydantic v1
                    value = None  # else pydantic v1 will set a FieldInfo object
                    # pydantic v2
                    # del kw[name]
            else:
                if isinstance(value, BaseModel):  # contructed with object ref
                    # print(value.id)
                    self.__iris__[name] = value.get_iri()
                elif isinstance(value, str):  # constructed from json
                    self.__iris__[name] = value
                    # pydantic v1
                    value = None  # else pydantic v1 will set a FieldInfo object
                    # pydantic v2
                    # del kw[name]
                elif value is None:
                    del self.__iris__[name]
        return value

    def __setattr__(self, name, value, internal=False):
        # print("__setattr__", name, value)
        # Only apply range handling for declared model fields
        if not internal and name in self.model_fields:
            value = self._handle_value(name, value)

        return super().__setattr__(name, value)

    def __getattribute__(self, name):
        # print("__getattribute__ ", name)
        # async? https://stackoverflow.com/questions/33128325/
        # how-to-set-class-attribute-with-await-in-init

        if name in ["__dict__", "__pydantic_private__", "__iris__"]:
            return BaseModel.__getattribute__(self, name)  # prevent loop

        if name == "model_fields":
            return type(self).model_fields

        else:
            if (
                hasattr(self, "__iris__")
                and name in self.__iris__
                and len(self.__iris__[name]) > 0
                and (
                    self.__dict__[name] is None
                    or (isinstance(self.__dict__[name], list) and len(self.__dict__[name]) == 0)
                )
            ):
                iris = self.__iris__[name]
                is_list = isinstance(iris, list)
                if not is_list:
                    iris = [iris]

                node_dict = self._resolve(iris)
                if is_list:
                    node_list = []
                    for iri in iris:
                        node = node_dict[iri]
                        node_list.append(node)
                    self.__setattr__(name, node_list, True)
                else:
                    node = node_dict[iris[0]]
                    if node:
                        self.__setattr__(name, node, True)

        result = BaseModel.__getattribute__(self, name)
        if isinstance(result, list) and name in self.__iris__:
            result = LinkedBaseModelList[type(self)](result, _synced_iri_list=self.__iris__[name])
        return result

    def _raw_dict(self):
        """Serialize to dict without _object_to_iri at any level.

        Used by cast() to preserve inline objects through reconstruction.
        IRI-only fields (value=None, IRI in __iris__) are included as
        IRI strings. Inline objects are recursively serialized as dicts.
        """
        d = {}
        fields = self.model_fields if hasattr(self, "model_fields") else getattr(self, "__fields__", {})
        for name in fields:
            val = self.__dict__.get(name)
            if val is None:
                iri = self.__iris__.get(name) if hasattr(self, "__iris__") else None
                d[name] = iri if iri else None
            elif isinstance(val, list):
                items = []
                for item in val:
                    if hasattr(item, "_raw_dict"):
                        items.append(item._raw_dict())
                    elif hasattr(item, "model_dump"):
                        items.append(item.model_dump())
                    elif hasattr(item, "dict"):
                        items.append(item.dict())
                    else:
                        items.append(item)
                d[name] = items
            elif hasattr(val, "_raw_dict"):
                d[name] = val._raw_dict()
            elif hasattr(val, "model_dump"):
                d[name] = val.model_dump()
            elif hasattr(val, "dict"):
                d[name] = val.dict()
            else:
                d[name] = val
        return d

    def model_dump(self, **kwargs):  # extent BaseClass export function
        # print("dict")
        remove_none = kwargs.get("exclude_none", False)
        kwargs["exclude_none"] = False
        d = super().model_dump(**kwargs)
        # pprint(d)
        self._object_to_iri(d)
        self._recursive_object_to_iri(d, self)
        if remove_none:
            d = self.remove_none(d)
        # pprint(d)
        return d

    @staticmethod
    @staticmethod
    def _recursive_object_to_iri(d: dict, model_obj):
        """Recursively apply __iris__ replacement for nested model objects."""
        fields = model_obj.model_fields if hasattr(model_obj, "model_fields") else getattr(model_obj, "__fields__", {})
        for name, value in list(d.items()):
            if name not in fields:
                continue
            model_value = model_obj.__dict__.get(name)
            if isinstance(value, list) and isinstance(model_value, list):
                for item, model_item in zip(value, model_value, strict=False):
                    if isinstance(item, dict) and hasattr(model_item, "__iris__"):
                        model_item._object_to_iri(item)
                        LinkedBaseModel._recursive_object_to_iri(item, model_item)
            elif isinstance(value, dict) and hasattr(model_value, "__iris__"):
                model_value._object_to_iri(value)
                LinkedBaseModel._recursive_object_to_iri(value, model_value)

    def get_iri_ref(self, field_name: str):
        """Return the stored IRI reference string(s) for a field without
        triggering resolution.

        Parameters
        ----------
        field_name
            The name of the field to retrieve the IRI reference for.

        Returns
        -------
            A string IRI, a list of string IRIs, or ``None`` if no IRI is
            stored for the given field.
        """
        iris = self.__iris__.get(field_name)
        if iris is None:
            return None
        if isinstance(iris, list):
            return iris if iris else None
        return iris

    def get_raw(self, field_name: str):
        """Return the raw value of a field without triggering IRI resolution.

        Unlike normal attribute access which may trigger network calls to
        resolve IRI references, this returns the Python object as stored
        internally (``None`` for unresolved IRIs, the model instance if
        already resolved, or a plain value for non-IRI fields).

        Parameters
        ----------
        field_name
            The name of the field to retrieve.

        Returns
        -------
            The raw field value, or ``None`` if the field is unresolved or
            does not exist.
        """
        return self.__dict__.get(field_name)

    @staticmethod
    def _resolve(iris):
        resolver = get_resolver(GetResolverParam(iri=iris[0])).resolver
        node_dict = resolver.resolve(ResolveParam(iris=iris, model_cls=LinkedBaseModel)).nodes
        return node_dict

    def _store(self):
        backend = get_backend(GetBackendParam(iri=self.get_iri())).backend
        backend.store(StoreParam(nodes={self.get_iri(): self}))

    def store_jsonld(self):
        """Store the model instance in a backend matching its IRI."""
        self._store()

    @classmethod
    def _oold_query(cls, query: str | list[str] | Query | Condition) -> "LinkedBaseModelList[Self]":
        # get all resolvers
        # ToDo: filter resolvers that support this class
        resolvers: list[Resolver] = interface._resolvers.values()
        node_list = []
        for r in resolvers:
            try:
                if isinstance(query, (str, list)):
                    _node_list = r.resolve(
                        ResolveParam(
                            iris=[query] if isinstance(query, str) else query,
                            model_cls=cls,
                        )
                    ).nodes.values()
                else:
                    _node_list = r.query(QueryParam(query=query, model_cls=cls)).nodes.values()
                node_list.extend(_node_list)
            except NotImplementedError:
                # resolver does not support query
                continue

        if isinstance(query, str):
            return node_list[0] if len(node_list) > 0 else None
        else:
            return LinkedBaseModelList[Self](node_list, _synced_iri_list=None) if len(node_list) > 0 else None

    @overload
    @classmethod
    def oold_query(cls, item: str) -> Self: ...

    @overload
    @classmethod
    def oold_query(cls, item: list[str]) -> "LinkedBaseModelList[Self]": ...

    # note: (Entity.name == "test") is interpreted as bool
    @overload
    @classmethod
    def oold_query(cls, item: Query | Condition | bool) -> Optional["LinkedBaseModelList[Self]"]: ...

    @classmethod
    def oold_query(
        cls, item: str | list[str] | Query | bool
    ) -> Union[Self, "LinkedBaseModelList[Self]", Optional["LinkedBaseModelList[Self]"]]:
        """Allow access to the class by its IRI."""
        return cls._oold_query(item)
        # if isinstance(item, Query):
        #     # resolve all instances of this class
        #     #print(f"Select all {cls.__name__} that match {index}")
        #     #return cls._oold_query(item)
        #     return cls(id="ex:test", name="test")
        # else:
        #     result = cls._resolve(item if isinstance(item, list) else [item])
        #     return (
        #         result[item] if isinstance(item, str)
        #         else LinkedBaseModelList[Self](
        #             [result[i] for i in item]
        #         )
        #     )

    # pydantic v2
    def model_dump_json(
        self,
        *,
        indent: int | None = None,
        include: pydantic.main.IncEx | None = None,
        exclude: pydantic.main.IncEx | None = None,
        context: Any | None = None,
        by_alias: bool = False,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        round_trip: bool = False,
        warnings: bool | Literal["none", "warn", "error"] = True,
        serialize_as_any: bool = False,
        **dumps_kwargs: Any,
    ) -> str:
        """Usage docs:
        https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump_json

        Generates a JSON representation of the model using Pydantic's `to_json` method.

        Args:
            indent: Indentation to use in the JSON output.
                If None is passed, the output will be compact.
            include: Field(s) to include in the JSON output.
            exclude: Field(s) to exclude from the JSON output.
            context: Additional context to pass to the serializer.
            by_alias: Whether to serialize using field aliases.
            exclude_unset: Whether to exclude fields that have not been explicitly set.
            exclude_defaults: Whether to exclude fields that are set to
                their default value.
            exclude_none: Whether to exclude fields that have a value of `None`.
            round_trip: If True, dumped values should be valid as input
                for non-idempotent types such as Json[T].
            warnings: How to handle serialization errors. False/"none" ignores them,
                True/"warn" logs errors, "error" raises a
                [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
            serialize_as_any: Whether to serialize fields with duck-typing serialization
                behavior.

        Returns:
            A JSON string representation of the model.
        """
        d = json.loads(
            BaseModel.model_dump_json(
                self,
                indent=indent,
                include=include,
                exclude=exclude,
                context=context,
                by_alias=by_alias,
                exclude_unset=exclude_unset,
                exclude_defaults=exclude_defaults,
                exclude_none=False,  # handle None values separately
                round_trip=round_trip,
                warnings=warnings,
                serialize_as_any=serialize_as_any,
            )
        )  # ToDo directly use dict?
        # this may replace some None values with IRIs in case they were never resolved
        # thats why we handle exclude_none there
        self._object_to_iri(d)
        self._recursive_object_to_iri(d, self)
        if exclude_none:
            d = self.remove_none(d)
        return json.dumps(d, **dumps_kwargs)

    def cast(
        self,
        cls,
        none_to_default=False,
        remove_extra=False,
        silent=True,
        **kwargs,
    ):
        """Cast this instance to a different model class.

        Parameters
        ----------
        cls
            Target class to cast to.
        none_to_default
            If True, attributes that are None or empty lists are
            removed so the target class uses its defaults.
        remove_extra
            If True, drop fields not defined on the target class.
        silent
            If True, suppress warnings about dropped fields.
        kwargs
            Additional fields to set on the new instance.
        """
        # Use _raw_dict to preserve inline objects at all depths.
        raw = self._raw_dict()
        data = {**raw, **kwargs}
        none_args = []
        if none_to_default:
            reduced = {}
            for k, v in data.items():
                if v is None or (isinstance(v, list) and (len(v) == 0 or all(item is None for item in v))):
                    none_args.append(k)
                else:
                    reduced[k] = v
            data = reduced
        extra_args = []
        if remove_extra:
            target_fields = set()
            if hasattr(cls, "model_fields"):
                target_fields = set(cls.model_fields.keys())
            elif hasattr(cls, "__fields__"):
                target_fields = set(cls.__fields__.keys())
            if target_fields:
                extra_args = [k for k in data if k not in target_fields]
                for k in extra_args:
                    del data[k]
        if not silent:
            if none_to_default and none_args:
                _logger.warning("Removed None/empty attributes: %s", none_args)
            if remove_extra and extra_args:
                _logger.warning("Removed extra attributes: %s", extra_args)
        if "type" in data:
            del data["type"]
        # Carry over __iris__ (range field references)
        if hasattr(self, "__iris__"):
            iris = dict(self.__iris__)
            if "__iris__" in data:
                iris.update(data["__iris__"])
            data["__iris__"] = iris
        return cls(**data)

    def cast_none_to_default(self, cls, **kwargs):
        """Cast to target class, dropping None/empty list attributes."""
        return self.cast(cls, none_to_default=True, **kwargs)

    def to_jsonld(self) -> dict:
        """Return the RDF representation of the object as JSON-LD."""
        return export_jsonld(self, BaseModel)

    @classmethod
    def from_jsonld(cls, jsonld: dict) -> "LinkedBaseModel":
        """Constructs a model instance from a JSON-LD representation."""
        return import_jsonld(BaseModel, LinkedBaseModel, cls, jsonld, _types)

    def to_json(self, exclude_defaults: bool = False) -> dict:
        """Return the JSON representation of the object.

        Parameters
        ----------
        exclude_defaults
            If True, fields with default values are excluded from the
            output. Useful for compact storage where defaults can be
            re-populated on deserialization via from_json().
        """
        result = json.loads(
            self.model_dump_json(
                exclude_none=True,
                exclude_defaults=exclude_defaults,
            )
        )
        # Re-inject IRI-only fields from __iris__ that were excluded
        # because their model value is None (the IRI lives in __iris__)
        if hasattr(self, "__iris__"):
            for field_name, iri in self.__iris__.items():
                if iri is None:
                    continue
                existing = result.get(field_name)
                if existing is None or existing == [] or existing == {}:
                    result[field_name] = iri
        return result

    @classmethod
    def from_json(cls, data: dict) -> "LinkedBaseModel":
        """Constructs a model instance from a JSON representation."""
        return import_json(BaseModel, LinkedBaseModel, cls, data, _types)

cast(cls, none_to_default=False, remove_extra=False, silent=True, **kwargs)

Cast this instance to a different model class.

Parameters:

Name Type Description Default
cls

Target class to cast to.

required
none_to_default

If True, attributes that are None or empty lists are removed so the target class uses its defaults.

False
remove_extra

If True, drop fields not defined on the target class.

False
silent

If True, suppress warnings about dropped fields.

True
kwargs

Additional fields to set on the new instance.

{}
Source code in src/oold/model/__init__.py
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
def cast(
    self,
    cls,
    none_to_default=False,
    remove_extra=False,
    silent=True,
    **kwargs,
):
    """Cast this instance to a different model class.

    Parameters
    ----------
    cls
        Target class to cast to.
    none_to_default
        If True, attributes that are None or empty lists are
        removed so the target class uses its defaults.
    remove_extra
        If True, drop fields not defined on the target class.
    silent
        If True, suppress warnings about dropped fields.
    kwargs
        Additional fields to set on the new instance.
    """
    # Use _raw_dict to preserve inline objects at all depths.
    raw = self._raw_dict()
    data = {**raw, **kwargs}
    none_args = []
    if none_to_default:
        reduced = {}
        for k, v in data.items():
            if v is None or (isinstance(v, list) and (len(v) == 0 or all(item is None for item in v))):
                none_args.append(k)
            else:
                reduced[k] = v
        data = reduced
    extra_args = []
    if remove_extra:
        target_fields = set()
        if hasattr(cls, "model_fields"):
            target_fields = set(cls.model_fields.keys())
        elif hasattr(cls, "__fields__"):
            target_fields = set(cls.__fields__.keys())
        if target_fields:
            extra_args = [k for k in data if k not in target_fields]
            for k in extra_args:
                del data[k]
    if not silent:
        if none_to_default and none_args:
            _logger.warning("Removed None/empty attributes: %s", none_args)
        if remove_extra and extra_args:
            _logger.warning("Removed extra attributes: %s", extra_args)
    if "type" in data:
        del data["type"]
    # Carry over __iris__ (range field references)
    if hasattr(self, "__iris__"):
        iris = dict(self.__iris__)
        if "__iris__" in data:
            iris.update(data["__iris__"])
        data["__iris__"] = iris
    return cls(**data)

cast_none_to_default(cls, **kwargs)

Cast to target class, dropping None/empty list attributes.

Source code in src/oold/model/__init__.py
939
940
941
def cast_none_to_default(self, cls, **kwargs):
    """Cast to target class, dropping None/empty list attributes."""
    return self.cast(cls, none_to_default=True, **kwargs)

from_json(data) classmethod

Constructs a model instance from a JSON representation.

Source code in src/oold/model/__init__.py
979
980
981
982
@classmethod
def from_json(cls, data: dict) -> "LinkedBaseModel":
    """Constructs a model instance from a JSON representation."""
    return import_json(BaseModel, LinkedBaseModel, cls, data, _types)

from_jsonld(jsonld) classmethod

Constructs a model instance from a JSON-LD representation.

Source code in src/oold/model/__init__.py
947
948
949
950
@classmethod
def from_jsonld(cls, jsonld: dict) -> "LinkedBaseModel":
    """Constructs a model instance from a JSON-LD representation."""
    return import_jsonld(BaseModel, LinkedBaseModel, cls, jsonld, _types)

get_cls_iri() classmethod

Return the unique IRI of the class. Overwrite this method in the subclass.

Source code in src/oold/model/__init__.py
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
@classmethod
def get_cls_iri(cls) -> str | list[str] | None:
    """Return the unique IRI of the class.
    Overwrite this method in the subclass."""
    schema = {}
    # pydantic v2
    if hasattr(cls, "model_config") and "json_schema_extra" in cls.model_config:
        schema = cls.model_config["json_schema_extra"]

    cls_iri = []
    # schema annotation - should be expanded IRI
    if "$id" in schema:
        cls_iri.append(schema["$id"])
    elif "iri" in schema:
        cls_iri.append(schema["iri"])
    # default value of type field - may be compacted IRI
    type_field_name = cls.get_type_field()
    # pydantic v2
    type_field = cls.model_fields.get(type_field_name, None)
    if type_field is not None and type_field.default not in cls_iri:
        cls_iri.append(type_field.default)

    if len(cls_iri) == 0:
        return None
    elif len(cls_iri) == 1:
        return cls_iri[0]
    else:
        return cls_iri

get_iri()

Return the unique IRI of the object. Overwrite this method in the subclass.

Source code in src/oold/model/__init__.py
387
388
389
390
def get_iri(self) -> str:
    """Return the unique IRI of the object.
    Overwrite this method in the subclass."""
    return self.id

get_iri_ref(field_name)

Return the stored IRI reference string(s) for a field without triggering resolution.

Parameters:

Name Type Description Default
field_name str

The name of the field to retrieve the IRI reference for.

required

Returns:

Type Description
A string IRI, a list of string IRIs, or ``None`` if no IRI is

stored for the given field.

Source code in src/oold/model/__init__.py
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
def get_iri_ref(self, field_name: str):
    """Return the stored IRI reference string(s) for a field without
    triggering resolution.

    Parameters
    ----------
    field_name
        The name of the field to retrieve the IRI reference for.

    Returns
    -------
        A string IRI, a list of string IRIs, or ``None`` if no IRI is
        stored for the given field.
    """
    iris = self.__iris__.get(field_name)
    if iris is None:
        return None
    if isinstance(iris, list):
        return iris if iris else None
    return iris

get_raw(field_name)

Return the raw value of a field without triggering IRI resolution.

Unlike normal attribute access which may trigger network calls to resolve IRI references, this returns the Python object as stored internally (None for unresolved IRIs, the model instance if already resolved, or a plain value for non-IRI fields).

Parameters:

Name Type Description Default
field_name str

The name of the field to retrieve.

required

Returns:

Type Description
The raw field value, or ``None`` if the field is unresolved or

does not exist.

Source code in src/oold/model/__init__.py
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
def get_raw(self, field_name: str):
    """Return the raw value of a field without triggering IRI resolution.

    Unlike normal attribute access which may trigger network calls to
    resolve IRI references, this returns the Python object as stored
    internally (``None`` for unresolved IRIs, the model instance if
    already resolved, or a plain value for non-IRI fields).

    Parameters
    ----------
    field_name
        The name of the field to retrieve.

    Returns
    -------
        The raw field value, or ``None`` if the field is unresolved or
        does not exist.
    """
    return self.__dict__.get(field_name)

model_dump_json(*, indent=None, include=None, exclude=None, context=None, by_alias=False, exclude_unset=False, exclude_defaults=False, exclude_none=False, round_trip=False, warnings=True, serialize_as_any=False, **dumps_kwargs)

Usage docs: https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump_json

Generates a JSON representation of the model using Pydantic's to_json method.

Args: indent: Indentation to use in the JSON output. If None is passed, the output will be compact. include: Field(s) to include in the JSON output. exclude: Field(s) to exclude from the JSON output. context: Additional context to pass to the serializer. by_alias: Whether to serialize using field aliases. exclude_unset: Whether to exclude fields that have not been explicitly set. exclude_defaults: Whether to exclude fields that are set to their default value. exclude_none: Whether to exclude fields that have a value of None. round_trip: If True, dumped values should be valid as input for non-idempotent types such as Json[T]. warnings: How to handle serialization errors. False/"none" ignores them, True/"warn" logs errors, "error" raises a [PydanticSerializationError][pydantic_core.PydanticSerializationError]. serialize_as_any: Whether to serialize fields with duck-typing serialization behavior.

Returns: A JSON string representation of the model.

Source code in src/oold/model/__init__.py
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
def model_dump_json(
    self,
    *,
    indent: int | None = None,
    include: pydantic.main.IncEx | None = None,
    exclude: pydantic.main.IncEx | None = None,
    context: Any | None = None,
    by_alias: bool = False,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    round_trip: bool = False,
    warnings: bool | Literal["none", "warn", "error"] = True,
    serialize_as_any: bool = False,
    **dumps_kwargs: Any,
) -> str:
    """Usage docs:
    https://docs.pydantic.dev/2.10/concepts/serialization/#modelmodel_dump_json

    Generates a JSON representation of the model using Pydantic's `to_json` method.

    Args:
        indent: Indentation to use in the JSON output.
            If None is passed, the output will be compact.
        include: Field(s) to include in the JSON output.
        exclude: Field(s) to exclude from the JSON output.
        context: Additional context to pass to the serializer.
        by_alias: Whether to serialize using field aliases.
        exclude_unset: Whether to exclude fields that have not been explicitly set.
        exclude_defaults: Whether to exclude fields that are set to
            their default value.
        exclude_none: Whether to exclude fields that have a value of `None`.
        round_trip: If True, dumped values should be valid as input
            for non-idempotent types such as Json[T].
        warnings: How to handle serialization errors. False/"none" ignores them,
            True/"warn" logs errors, "error" raises a
            [`PydanticSerializationError`][pydantic_core.PydanticSerializationError].
        serialize_as_any: Whether to serialize fields with duck-typing serialization
            behavior.

    Returns:
        A JSON string representation of the model.
    """
    d = json.loads(
        BaseModel.model_dump_json(
            self,
            indent=indent,
            include=include,
            exclude=exclude,
            context=context,
            by_alias=by_alias,
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            exclude_none=False,  # handle None values separately
            round_trip=round_trip,
            warnings=warnings,
            serialize_as_any=serialize_as_any,
        )
    )  # ToDo directly use dict?
    # this may replace some None values with IRIs in case they were never resolved
    # thats why we handle exclude_none there
    self._object_to_iri(d)
    self._recursive_object_to_iri(d, self)
    if exclude_none:
        d = self.remove_none(d)
    return json.dumps(d, **dumps_kwargs)

model_validate(obj, *, strict=None, from_attributes=None, context=None) classmethod

Validate a pydantic model instance.

Args: obj: The object to validate. strict: Whether to enforce types strictly. from_attributes: Whether to extract data from object attributes. context: Additional context to pass to the validator.

Raises: ValidationError: If the object could not be validated.

Returns: The validated model instance.

Source code in src/oold/model/__init__.py
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
@classmethod
def model_validate(
    cls,
    obj: Any,
    *,
    strict: bool | None = None,
    from_attributes: bool | None = None,
    context: Any | None = None,
) -> Self:
    """Validate a pydantic model instance.

    Args:
        obj: The object to validate.
        strict: Whether to enforce types strictly.
        from_attributes: Whether to extract data from object attributes.
        context: Additional context to pass to the validator.

    Raises:
        ValidationError: If the object could not be validated.

    Returns:
        The validated model instance.
    """
    if isinstance(obj, str):
        return cls._resolve([obj])[obj]
    if isinstance(obj, list):
        node_dict = cls._resolve(obj)
        node_list = []
        for iri in obj:
            node = node_dict[iri]
            if node:
                node_list.append(node)
        return node_list
    elif isinstance(obj, dict):
        super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context)

oold_query(item) classmethod

oold_query(item: str) -> Self
oold_query(item: list[str]) -> LinkedBaseModelList[Self]
oold_query(
    item: Query | Condition | bool,
) -> Optional[LinkedBaseModelList[Self]]

Allow access to the class by its IRI.

Source code in src/oold/model/__init__.py
789
790
791
792
793
794
@classmethod
def oold_query(
    cls, item: str | list[str] | Query | bool
) -> Union[Self, "LinkedBaseModelList[Self]", Optional["LinkedBaseModelList[Self]"]]:
    """Allow access to the class by its IRI."""
    return cls._oold_query(item)

store_jsonld()

Store the model instance in a backend matching its IRI.

Source code in src/oold/model/__init__.py
745
746
747
def store_jsonld(self):
    """Store the model instance in a backend matching its IRI."""
    self._store()

to_json(exclude_defaults=False)

Return the JSON representation of the object.

Parameters:

Name Type Description Default
exclude_defaults bool

If True, fields with default values are excluded from the output. Useful for compact storage where defaults can be re-populated on deserialization via from_json().

False
Source code in src/oold/model/__init__.py
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
def to_json(self, exclude_defaults: bool = False) -> dict:
    """Return the JSON representation of the object.

    Parameters
    ----------
    exclude_defaults
        If True, fields with default values are excluded from the
        output. Useful for compact storage where defaults can be
        re-populated on deserialization via from_json().
    """
    result = json.loads(
        self.model_dump_json(
            exclude_none=True,
            exclude_defaults=exclude_defaults,
        )
    )
    # Re-inject IRI-only fields from __iris__ that were excluded
    # because their model value is None (the IRI lives in __iris__)
    if hasattr(self, "__iris__"):
        for field_name, iri in self.__iris__.items():
            if iri is None:
                continue
            existing = result.get(field_name)
            if existing is None or existing == [] or existing == {}:
                result[field_name] = iri
    return result

to_jsonld()

Return the RDF representation of the object as JSON-LD.

Source code in src/oold/model/__init__.py
943
944
945
def to_jsonld(self) -> dict:
    """Return the RDF representation of the object as JSON-LD."""
    return export_jsonld(self, BaseModel)

BaseController

Mixin for adding runtime behavior to a LinkedBaseModel subclass without polluting the data model or the type registry.

Base mixin for controllers that extend LinkedBaseModel data classes.

Overrides to_json() and to_jsonld() to serialize only the pure data model fields, stripping controller-only fields (e.g. archive_database, auto_archive, connection state).

The data model class is auto-detected from the MRO: the first LinkedBaseModel subclass that is not also a BaseController subclass.

Controllers are excluded from oold's type IRI registry (_types) so they don't replace their pure data model counterparts during backend resolution.

Source code in src/oold/model/__init__.py
 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
class BaseController:
    """Base mixin for controllers that extend LinkedBaseModel data classes.

    Overrides to_json() and to_jsonld() to serialize only the pure data
    model fields, stripping controller-only fields (e.g. archive_database,
    auto_archive, connection state).

    The data model class is auto-detected from the MRO: the first
    LinkedBaseModel subclass that is not also a BaseController subclass.

    Controllers are excluded from oold's type IRI registry (_types) so
    they don't replace their pure data model counterparts during
    backend resolution.
    """

    def __setattr__(self, name, value, internal=False):
        """Route private attrs through object.__setattr__ to bypass
        Pydantic's field validation for controller state fields."""
        if name.startswith("_"):
            object.__setattr__(self, name, value)
        else:
            try:
                super().__setattr__(name, value, internal=internal)
            except (ValueError, AttributeError):
                _logger.warning(
                    "Setting '%s' on %s bypassed Pydantic. Declare it as a Pydantic field or use a _private name.",
                    name,
                    type(self).__name__,
                )
                object.__setattr__(self, name, value)

    def _get_data_model_cls(self):
        """Auto-detect the pure data model class from the MRO.

        Finds all direct LinkedBaseModel bases that are not controllers.
        If there are multiple, creates a dynamic union class combining
        them (e.g. Controller(ModelA, ModelB) -> _ModelA_ModelB).
        """

        def _is_data_model(cls):
            return (
                cls is not type(self)
                and cls.__name__
                not in (
                    "LinkedBaseModel",
                    "_LinkedBaseModel",
                    "BaseController",
                    "GenericLinkedBaseModel",
                    "BaseModel",
                    "Representation",
                )
                and hasattr(cls, "to_json")
                and hasattr(cls, "from_json")
                and not issubclass(cls, BaseController)
            )

        model_bases = []
        for cls in type(self).__mro__:
            if _is_data_model(cls) and not any(issubclass(m, cls) for m in model_bases):
                model_bases.append(cls)
        if len(model_bases) == 0:
            return None
        if len(model_bases) == 1:
            return model_bases[0]
        name = "_".join(b.__name__ for b in model_bases)
        union_cls = type(name, tuple(model_bases), {})
        union_cls._union_bases = model_bases
        return union_cls

    def _get_model_bases(self):
        """Return the list of pure data model base classes."""
        model_cls = self._get_data_model_cls()
        if model_cls is None:
            return []
        if hasattr(model_cls, "_union_bases"):
            return model_cls._union_bases
        return [model_cls]

    def _collect_type_array(self):
        """Collect merged type array from all pure data model bases."""
        bases = self._get_model_bases()
        if len(bases) <= 1:
            return None
        merged = []
        for base in bases:
            field = None
            if hasattr(base, "model_fields"):
                field = base.model_fields.get("type")
            elif hasattr(base, "__fields__"):
                field = base.__fields__.get("type")
            default = getattr(field, "default", None) if field else None
            if isinstance(default, list):
                for t in default:
                    if t not in merged:
                        merged.append(t)
            elif isinstance(default, str) and default not in merged:
                merged.append(default)
        return merged if merged else None

    def to_json(self, **kwargs):
        # Serialize with LinkedBaseModel.to_json (includes __iris__),
        # then strip controller-only fields
        model_cls = self._get_data_model_cls()
        if model_cls is not None:
            # Use _raw_dict to avoid serialization errors from
            # non-serializable controller fields (e.g. _driver).
            # This bypasses BaseModel.json() which would fail on
            # controller-added fields before we can strip them.
            data = self._raw_dict()
            model_fields = set(
                model_cls.model_fields.keys()
                if hasattr(model_cls, "model_fields")
                else getattr(model_cls, "__fields__", {}).keys()
            )
            for key in list(data.keys()):
                if key not in model_fields and key not in ("type", "@context"):
                    del data[key]
            merged_types = self._collect_type_array()
            if merged_types:
                data["type"] = merged_types
            # Remove None values (match exclude_none behavior)
            data = {k: v for k, v in data.items() if v is not None}
            return data
        return super().to_json(**kwargs)

    def to_jsonld(self):
        data = super().to_jsonld()
        model_cls = self._get_data_model_cls()
        if model_cls is not None:
            merged_types = self._collect_type_array()
            if merged_types:
                data["type"] = merged_types
            model_fields = set(
                model_cls.model_fields.keys()
                if hasattr(model_cls, "model_fields")
                else getattr(model_cls, "__fields__", {}).keys()
            )
            for key in list(data.keys()):
                if key not in model_fields and key not in (
                    "type",
                    "@type",
                    "@context",
                    "@id",
                    "id",
                ):
                    del data[key]
        return data

__setattr__(name, value, internal=False)

Route private attrs through object.setattr to bypass Pydantic's field validation for controller state fields.

Source code in src/oold/model/__init__.py
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
def __setattr__(self, name, value, internal=False):
    """Route private attrs through object.__setattr__ to bypass
    Pydantic's field validation for controller state fields."""
    if name.startswith("_"):
        object.__setattr__(self, name, value)
    else:
        try:
            super().__setattr__(name, value, internal=internal)
        except (ValueError, AttributeError):
            _logger.warning(
                "Setting '%s' on %s bypassed Pydantic. Declare it as a Pydantic field or use a _private name.",
                name,
                type(self).__name__,
            )
            object.__setattr__(self, name, value)

LinkedBaseModel (v1 - legacy)

Pydantic v1 implementation. Use oold.model.LinkedBaseModel for new projects.

Bases: _LinkedBaseModel

LinkedBaseModel for pydantic v1

Source code in src/oold/model/v1/__init__.py
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
class LinkedBaseModel(_LinkedBaseModel):
    """LinkedBaseModel for pydantic v1"""

    __iris__: dict[str, str | list[str]] | None = PrivateAttr()

    @classmethod
    def get_cls_iri(cls) -> str | list[str] | None:
        """Return the unique IRI of the class.
        Overwrite this method in the subclass."""
        schema = {}
        # pydantic v1
        if hasattr(cls, "__config__") and hasattr(cls.__config__, "schema_extra"):
            schema = cls.__config__.schema_extra

        cls_iri = []
        # schema annotation - should be expanded IRI
        if "$id" in schema:
            cls_iri.append(schema["$id"])
        elif "iri" in schema:
            cls_iri.append(schema["iri"])
        # default value of type field - may be compacted IRI
        type_field_name = cls.get_type_field()
        # pydantic v2
        type_field = cls.__fields__.get(type_field_name, None)
        if type_field is not None:
            cls_iri.append(type_field.default)
        if len(cls_iri) == 0:
            return None
        elif len(cls_iri) == 1:
            return cls_iri[0]
        else:
            return cls_iri

    def get_iri(self) -> str:
        """Return the unique IRI of the object.
        Overwrite this method in the subclass."""
        return self.id

    @classmethod
    def parse_obj(cls, obj: Any) -> "LinkedBaseModel":
        """Parse the object and return a LinkedBaseModel instance.
        This method is called by pydantic when creating
        a new (default) instance of the model."""
        if isinstance(obj, str):
            # pydantic v1
            return cls._resolve([obj])[obj]
        if isinstance(obj, list):
            # pydantic v1
            # return cls._resolve(obj).nodes[obj[0]]
            node_dict = cls._resolve(obj)
            node_list = []
            for iri in obj:
                node = node_dict[iri]
                if node:
                    node_list.append(node)
            return node_list
        elif isinstance(obj, dict):
            return super().parse_obj(obj)

    def __init__(self, *a, **kw):
        # Accept a model instance as first positional arg:
        # TargetModel(source_model, extra_field=value)
        if a and isinstance(a[0], BaseModel):
            source = a[0]
            result = source.cast(type(self), **kw)
            kw = result._raw_dict()
            kw["__iris__"] = getattr(result, "__iris__", {})
            a = ()

        if "__iris__" not in kw:
            kw["__iris__"] = {}

        for name in list(kw):  # force copy of keys for inline-delete
            # print(name)
            if name == "__iris__":
                continue
            # rewrite <attr> to <attr>_iri
            # pprint(self.__fields__)
            extra = None
            # pydantic v1
            if name in self.__fields__:
                if hasattr(self.__fields__[name].default, "json_schema_extra"):
                    extra = self.__fields__[name].default.json_schema_extra
                elif hasattr(self.__fields__[name].field_info, "extra"):
                    extra = self.__fields__[name].field_info.extra
            # pydantic v2
            # extra = self.model_fields[name].json_schema_extra

            if extra and "range" in extra:
                arg_is_list = isinstance(kw[name], list)

                # annotation_is_list = False
                # args = self.model_fields[name].annotation.__args__
                # if hasattr(args[0], "_name"):
                #    is_list = args[0]._name == "List"
                if arg_is_list:
                    kw["__iris__"][name] = []
                    for e in kw[name][:]:  # interate over copy of list
                        if isinstance(e, BaseModel):  # contructed with object ref
                            kw["__iris__"][name].append(e.get_iri())
                        elif isinstance(e, str):  # constructed from json
                            kw["__iris__"][name].append(e)
                            kw[name].remove(e)  # remove to construct valid instance
                    if len(kw[name]) == 0:
                        # pydantic v1
                        kw[name] = None  # else pydantic v1 will set a FieldInfo object
                        # pydantic v2
                        # del kw[name]
                else:
                    if isinstance(kw[name], BaseModel):  # contructed with object ref
                        # print(kw[name].id)
                        kw["__iris__"][name] = kw[name].get_iri()
                    elif isinstance(kw[name], str):  # constructed from json
                        kw["__iris__"][name] = kw[name]
                        # pydantic v1
                        kw[name] = None  # else pydantic v1 will set a FieldInfo object
                        # pydantic v2
                        # del kw[name]

        BaseModel.__init__(self, *a, **kw)
        # handle default values
        for name in list(self.__dict__.keys()):
            if self.__dict__[name] is None:
                continue
            extra = None
            # pydantic v1
            if name in self.__fields__:
                if hasattr(self.__fields__[name].default, "json_schema_extra"):
                    extra = self.__fields__[name].default.json_schema_extra
                elif hasattr(self.__fields__[name].field_info, "extra"):
                    extra = self.__fields__[name].field_info.extra
            if extra and "range" in extra and name not in kw["__iris__"]:
                arg_is_list = isinstance(self.__dict__[name], list)

                if arg_is_list:
                    kw["__iris__"][name] = []
                    for e in self.__dict__[name]:
                        if isinstance(e, BaseModel):  # contructed with object ref
                            kw["__iris__"][name].append(e.get_iri())
                else:
                    # contructed with object ref
                    if isinstance(self.__dict__[name], BaseModel):
                        kw["__iris__"][name] = self.__dict__[name].get_iri()

        self.__iris__ = kw["__iris__"]

        # iterate over all fields
        # if x-oold-required-iri occurs in extra and the field is not set in __iri__
        # throw an error
        for name in self.__fields__:
            extra = None
            # pydantic v1
            if name in self.__fields__:
                if hasattr(self.__fields__[name].default, "json_schema_extra"):
                    extra = self.__fields__[name].default.json_schema_extra
                elif hasattr(self.__fields__[name].field_info, "extra"):
                    extra = self.__fields__[name].field_info.extra
            # pydantic v2
            # extra = self.model_fields[name].json_schema_extra

            if extra and "x_oold_required_iri" in extra and name not in self.__iris__:
                raise ValueError(f"{name} is required but not set")

    def _handle_value(self, name, value):
        extra = None
        # pydantic v1
        if name in self.__fields__:
            if hasattr(self.__fields__[name].default, "json_schema_extra"):
                extra = self.__fields__[name].default.json_schema_extra
            elif hasattr(self.__fields__[name].field_info, "extra"):
                extra = self.__fields__[name].field_info.extra
        # pydantic v2
        # extra = self.model_fields[name].json_schema_extra

        if extra and "range" in extra:
            arg_is_list = isinstance(value, list)

            if arg_is_list:
                self.__iris__[name] = []
                for e in value[:]:  # interate over copy of list
                    if isinstance(e, BaseModel):  # contructed with object ref
                        self.__iris__[name].append(e.get_iri())
                    elif isinstance(e, str):  # constructed from json
                        self.__iris__[name].append(e)
                        value.remove(e)  # remove to construct valid instance
                if len(value) == 0:
                    # pydantic v1
                    value = None  # else pydantic v1 will set a FieldInfo object
                    # pydantic v2
                    # del kw[name]
            else:
                if isinstance(value, BaseModel):  # contructed with object ref
                    # print(value.id)
                    self.__iris__[name] = value.get_iri()
                elif isinstance(value, str):  # constructed from json
                    self.__iris__[name] = value
                    # pydantic v1
                    value = None  # else pydantic v1 will set a FieldInfo object
                    # pydantic v2
                    # del kw[name]
                elif value is None:
                    del self.__iris__[name]
        return value

    def __setattr__(self, name, value, internal=False):
        # print("__setattr__", name, value)
        # Only apply range handling for declared model fields
        if not internal and name in self.__fields__:
            value = self._handle_value(name, value)

        return super().__setattr__(name, value)

    def __getattribute__(self, name):
        # print("__getattribute__ ", name)
        # async? https://stackoverflow.com/questions/33128325/
        # how-to-set-class-attribute-with-await-in-init

        if name in ["__dict__", "__pydantic_private__", "__iris__"]:
            return BaseModel.__getattribute__(self, name)  # prevent loop

        else:
            if (
                hasattr(self, "__iris__")
                and name in self.__iris__
                and len(self.__iris__[name]) > 0
                and (
                    self.__dict__[name] is None
                    or (isinstance(self.__dict__[name], list) and len(self.__dict__[name]) == 0)
                )
            ):
                iris = self.__iris__[name]
                is_list = isinstance(iris, list)
                if not is_list:
                    iris = [iris]

                node_dict = self._resolve(iris)
                if is_list:
                    node_list = []
                    for iri in iris:
                        node = node_dict[iri]
                        node_list.append(node)
                    self.__setattr__(name, node_list, True)
                else:
                    node = node_dict[iris[0]]
                    if node:
                        self.__setattr__(name, node, True)

        result = BaseModel.__getattribute__(self, name)
        if isinstance(result, list) and name in self.__iris__:
            result = LinkedBaseModelList[type(self)](result, _synced_iri_list=self.__iris__[name])
        return result

    def get_iri_ref(self, field_name: str):
        """Return the stored IRI reference string(s) for a field without
        triggering resolution.

        Parameters
        ----------
        field_name
            The name of the field to retrieve the IRI reference for.

        Returns
        -------
            A string IRI, a list of string IRIs, or ``None`` if no IRI is
            stored for the given field.
        """
        iris = self.__iris__.get(field_name)
        if iris is None:
            return None
        if isinstance(iris, list):
            return iris if iris else None
        return iris

    def get_raw(self, field_name: str):
        """Return the raw value of a field without triggering IRI resolution.

        Unlike normal attribute access which may trigger network calls to
        resolve IRI references, this returns the Python object as stored
        internally (``None`` for unresolved IRIs, the model instance if
        already resolved, or a plain value for non-IRI fields).

        Parameters
        ----------
        field_name
            The name of the field to retrieve.

        Returns
        -------
            The raw field value, or ``None`` if the field is unresolved or
            does not exist.
        """
        return self.__dict__.get(field_name)

    @staticmethod
    def _resolve(iris):
        resolver = get_resolver(GetResolverParam(iri=iris[0])).resolver
        node_dict = resolver.resolve(ResolveParam(iris=iris, model_cls=LinkedBaseModel)).nodes
        return node_dict

    def _store(self):
        backend = get_backend(GetBackendParam(iri=self.get_iri())).backend
        backend.store(StoreParam(nodes={self.get_iri(): self}))

    def store_jsonld(self):
        """Store the model instance in a backend matching its IRI."""
        self._store()

    @classmethod
    def _oold_query(cls, query: str | list[str] | Query | Condition) -> "LinkedBaseModelList[Self]":
        # get all resolvers
        resolvers: list[Resolver] = interface._resolvers.values()
        node_list = []
        for r in resolvers:
            try:
                if isinstance(query, (str, list)):
                    _node_list = r.resolve(
                        ResolveParam(
                            iris=[query] if isinstance(query, str) else query,
                            model_cls=cls,
                        )
                    ).nodes.values()
                else:
                    _node_list = r.query(QueryParam(query=query, model_cls=cls)).nodes.values()
                node_list.extend(_node_list)
            except NotImplementedError:
                continue

        if isinstance(query, str):
            return node_list[0] if len(node_list) > 0 else None
        else:
            return LinkedBaseModelList[Self](node_list, _synced_iri_list=None) if len(node_list) > 0 else None

    @overload
    @classmethod
    def oold_query(cls, item: str) -> Self: ...

    @overload
    @classmethod
    def oold_query(cls, item: list[str]) -> "LinkedBaseModelList[Self]": ...

    @overload
    @classmethod
    def oold_query(cls, item: Query | Condition | bool) -> Optional["LinkedBaseModelList[Self]"]: ...

    @classmethod
    def oold_query(
        cls, item: str | list[str] | Query | bool
    ) -> Union[Self, "LinkedBaseModelList[Self]", Optional["LinkedBaseModelList[Self]"]]:
        """Allow access to the class by its IRI."""
        return cls._oold_query(item)

    @staticmethod
    @staticmethod
    def _recursive_object_to_iri(d: dict, model_obj):
        """Recursively apply __iris__ replacement for nested model objects."""
        for name, value in list(d.items()):
            if name not in model_obj.__fields__:
                continue
            model_value = model_obj.__dict__.get(name)
            if isinstance(value, list) and isinstance(model_value, list):
                for item, model_item in zip(value, model_value, strict=False):
                    if isinstance(item, dict) and hasattr(model_item, "__iris__"):
                        model_item._object_to_iri(item)
                        LinkedBaseModel._recursive_object_to_iri(item, model_item)
            elif isinstance(value, dict) and hasattr(model_value, "__iris__"):
                model_value._object_to_iri(value)
                LinkedBaseModel._recursive_object_to_iri(value, model_value)

    def _raw_dict(self):
        """Serialize to dict without _object_to_iri at any level.

        Used by cast() to preserve inline objects through reconstruction.
        IRI-only fields (value=None, IRI in __iris__) are included as
        IRI strings. Inline objects are recursively serialized as dicts.
        """
        d = {}
        fields = getattr(self, "__fields__", {})
        for name in fields:
            val = self.__dict__.get(name)
            if val is None:
                iri = self.__iris__.get(name) if hasattr(self, "__iris__") else None
                d[name] = iri if iri else None
            elif isinstance(val, list):
                items = []
                for item in val:
                    if hasattr(item, "_raw_dict"):
                        items.append(item._raw_dict())
                    elif hasattr(item, "dict"):
                        items.append(item.dict())
                    else:
                        items.append(item)
                d[name] = items
            elif hasattr(val, "_raw_dict"):
                d[name] = val._raw_dict()
            elif hasattr(val, "dict"):
                d[name] = val.dict()
            else:
                d[name] = val
        return d

    def dict(self, **kwargs):
        """Override Pydantic v1 dict() to include __iris__ values.

        Ensures IRI-only fields (value=None, IRI in __iris__) are included
        in the output, including for nested model objects.
        """
        exclude_none = kwargs.pop("exclude_none", False)
        kwargs["exclude_none"] = False
        d = super().dict(**kwargs)
        self._object_to_iri(d)
        self._recursive_object_to_iri(d, self)
        if exclude_none:
            d = self.remove_none(d)
        return d

    # pydantic v1
    def json(
        self,
        *,
        include: Union["AbstractSetIntStr", "MappingIntStrAny"] | None = None,
        exclude: Union["AbstractSetIntStr", "MappingIntStrAny"] | None = None,
        by_alias: bool = False,
        skip_defaults: bool | None = None,
        exclude_unset: bool = False,
        exclude_defaults: bool = False,
        exclude_none: bool = False,
        encoder: Callable[[Any], Any] | None = None,
        models_as_dict: bool = True,
        **dumps_kwargs: Any,
    ) -> str:
        """
        Generate a JSON representation of the model,
        `include` and `exclude` arguments as per `dict()`.

        `encoder` is an optional function to supply as `default` to json.dumps(),
        other arguments as per `json.dumps()`.
        """
        d = json.loads(
            BaseModel.json(
                self,
                include=include,
                exclude=exclude,
                by_alias=by_alias,
                skip_defaults=skip_defaults,
                exclude_unset=exclude_unset,
                exclude_defaults=exclude_defaults,
                exclude_none=False,  # handle None values separately
                encoder=encoder,
                models_as_dict=models_as_dict,
                **dumps_kwargs,
            )
        )  # ToDo directly use dict?
        # this may replace some None values with IRIs in case they were never resolved
        # thats why we handle exclude_none there
        self._object_to_iri(d)
        # Recursively apply _object_to_iri for nested models
        self._recursive_object_to_iri(d, self)
        if exclude_none:
            d = self.remove_none(d)
        return json.dumps(d, **dumps_kwargs)

    def cast(
        self,
        cls,
        none_to_default=False,
        remove_extra=False,
        silent=True,
        **kwargs,
    ):
        """Cast this instance to a different model class.

        Parameters
        ----------
        cls
            Target class to cast to.
        none_to_default
            If True, attributes that are None or empty lists are
            removed so the target class uses its defaults.
        remove_extra
            If True, drop fields not defined on the target class.
        silent
            If True, suppress warnings about dropped fields.
        kwargs
            Additional fields to set on the new instance.
        """
        # Use _raw_dict to preserve inline objects at all depths.
        # Unlike dict()/_object_to_iri, this keeps nested models as
        # dicts instead of replacing them with IRIs.
        raw = self._raw_dict()
        data = {**raw, **kwargs}
        none_args = []
        if none_to_default:
            reduced = {}
            for k, v in data.items():
                if v is None or (isinstance(v, list) and (len(v) == 0 or all(item is None for item in v))):
                    none_args.append(k)
                else:
                    reduced[k] = v
            data = reduced
        extra_args = []
        if remove_extra:
            target_fields = set()
            if hasattr(cls, "__fields__"):
                target_fields = set(cls.__fields__.keys())
            if target_fields:
                extra_args = [k for k in data if k not in target_fields]
                for k in extra_args:
                    del data[k]
        if not silent:
            if none_to_default and none_args:
                _logger.warning("Removed None/empty attributes: %s", none_args)
            if remove_extra and extra_args:
                _logger.warning("Removed extra attributes: %s", extra_args)
        if "type" in data:
            del data["type"]
        if hasattr(self, "__iris__"):
            iris = dict(self.__iris__)
            if "__iris__" in data:
                iris.update(data["__iris__"])
            data["__iris__"] = iris
        return cls(**data)

    def cast_none_to_default(self, cls, **kwargs):
        """Cast to target class, dropping None/empty list attributes."""
        return self.cast(cls, none_to_default=True, **kwargs)

    def to_jsonld(self) -> builtins.dict:
        """Return the RDF representation of the object as JSON-LD."""
        return export_jsonld(self, BaseModel)

    @classmethod
    def from_jsonld(cls, jsonld: builtins.dict) -> "LinkedBaseModel":
        """Constructs a model instance from a JSON-LD representation."""
        return import_jsonld(BaseModel, LinkedBaseModel, cls, jsonld, _types)

    def to_json(self, exclude_defaults: bool = False) -> builtins.dict:
        """Return the JSON representation of the object as dict.

        Parameters
        ----------
        exclude_defaults
            If True, fields with default values are excluded from the
            output. Useful for compact storage where defaults can be
            re-populated on deserialization via from_json().
        """
        result = json.loads(
            self.json(
                exclude_none=True,
                exclude_defaults=exclude_defaults,
            )
        )
        # Re-inject IRI-only fields from __iris__ that were excluded
        # because their model value is None (the IRI lives in __iris__)
        if hasattr(self, "__iris__"):
            for field_name, iri in self.__iris__.items():
                if iri is None:
                    continue
                existing = result.get(field_name)
                if existing is None or existing == [] or existing == {}:
                    result[field_name] = iri
        return result

    @classmethod
    def from_json(cls, json_dict: builtins.dict) -> "LinkedBaseModel":
        """Constructs a model instance from a JSON representation."""
        return import_json(BaseModel, LinkedBaseModel, cls, json_dict, _types)

cast(cls, none_to_default=False, remove_extra=False, silent=True, **kwargs)

Cast this instance to a different model class.

Parameters:

Name Type Description Default
cls

Target class to cast to.

required
none_to_default

If True, attributes that are None or empty lists are removed so the target class uses its defaults.

False
remove_extra

If True, drop fields not defined on the target class.

False
silent

If True, suppress warnings about dropped fields.

True
kwargs

Additional fields to set on the new instance.

{}
Source code in src/oold/model/v1/__init__.py
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
def cast(
    self,
    cls,
    none_to_default=False,
    remove_extra=False,
    silent=True,
    **kwargs,
):
    """Cast this instance to a different model class.

    Parameters
    ----------
    cls
        Target class to cast to.
    none_to_default
        If True, attributes that are None or empty lists are
        removed so the target class uses its defaults.
    remove_extra
        If True, drop fields not defined on the target class.
    silent
        If True, suppress warnings about dropped fields.
    kwargs
        Additional fields to set on the new instance.
    """
    # Use _raw_dict to preserve inline objects at all depths.
    # Unlike dict()/_object_to_iri, this keeps nested models as
    # dicts instead of replacing them with IRIs.
    raw = self._raw_dict()
    data = {**raw, **kwargs}
    none_args = []
    if none_to_default:
        reduced = {}
        for k, v in data.items():
            if v is None or (isinstance(v, list) and (len(v) == 0 or all(item is None for item in v))):
                none_args.append(k)
            else:
                reduced[k] = v
        data = reduced
    extra_args = []
    if remove_extra:
        target_fields = set()
        if hasattr(cls, "__fields__"):
            target_fields = set(cls.__fields__.keys())
        if target_fields:
            extra_args = [k for k in data if k not in target_fields]
            for k in extra_args:
                del data[k]
    if not silent:
        if none_to_default and none_args:
            _logger.warning("Removed None/empty attributes: %s", none_args)
        if remove_extra and extra_args:
            _logger.warning("Removed extra attributes: %s", extra_args)
    if "type" in data:
        del data["type"]
    if hasattr(self, "__iris__"):
        iris = dict(self.__iris__)
        if "__iris__" in data:
            iris.update(data["__iris__"])
        data["__iris__"] = iris
    return cls(**data)

cast_none_to_default(cls, **kwargs)

Cast to target class, dropping None/empty list attributes.

Source code in src/oold/model/v1/__init__.py
822
823
824
def cast_none_to_default(self, cls, **kwargs):
    """Cast to target class, dropping None/empty list attributes."""
    return self.cast(cls, none_to_default=True, **kwargs)

dict(**kwargs)

Override Pydantic v1 dict() to include iris values.

Ensures IRI-only fields (value=None, IRI in iris) are included in the output, including for nested model objects.

Source code in src/oold/model/v1/__init__.py
700
701
702
703
704
705
706
707
708
709
710
711
712
713
def dict(self, **kwargs):
    """Override Pydantic v1 dict() to include __iris__ values.

    Ensures IRI-only fields (value=None, IRI in __iris__) are included
    in the output, including for nested model objects.
    """
    exclude_none = kwargs.pop("exclude_none", False)
    kwargs["exclude_none"] = False
    d = super().dict(**kwargs)
    self._object_to_iri(d)
    self._recursive_object_to_iri(d, self)
    if exclude_none:
        d = self.remove_none(d)
    return d

from_json(json_dict) classmethod

Constructs a model instance from a JSON representation.

Source code in src/oold/model/v1/__init__.py
862
863
864
865
@classmethod
def from_json(cls, json_dict: builtins.dict) -> "LinkedBaseModel":
    """Constructs a model instance from a JSON representation."""
    return import_json(BaseModel, LinkedBaseModel, cls, json_dict, _types)

from_jsonld(jsonld) classmethod

Constructs a model instance from a JSON-LD representation.

Source code in src/oold/model/v1/__init__.py
830
831
832
833
@classmethod
def from_jsonld(cls, jsonld: builtins.dict) -> "LinkedBaseModel":
    """Constructs a model instance from a JSON-LD representation."""
    return import_jsonld(BaseModel, LinkedBaseModel, cls, jsonld, _types)

get_cls_iri() classmethod

Return the unique IRI of the class. Overwrite this method in the subclass.

Source code in src/oold/model/v1/__init__.py
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
@classmethod
def get_cls_iri(cls) -> str | list[str] | None:
    """Return the unique IRI of the class.
    Overwrite this method in the subclass."""
    schema = {}
    # pydantic v1
    if hasattr(cls, "__config__") and hasattr(cls.__config__, "schema_extra"):
        schema = cls.__config__.schema_extra

    cls_iri = []
    # schema annotation - should be expanded IRI
    if "$id" in schema:
        cls_iri.append(schema["$id"])
    elif "iri" in schema:
        cls_iri.append(schema["iri"])
    # default value of type field - may be compacted IRI
    type_field_name = cls.get_type_field()
    # pydantic v2
    type_field = cls.__fields__.get(type_field_name, None)
    if type_field is not None:
        cls_iri.append(type_field.default)
    if len(cls_iri) == 0:
        return None
    elif len(cls_iri) == 1:
        return cls_iri[0]
    else:
        return cls_iri

get_iri()

Return the unique IRI of the object. Overwrite this method in the subclass.

Source code in src/oold/model/v1/__init__.py
333
334
335
336
def get_iri(self) -> str:
    """Return the unique IRI of the object.
    Overwrite this method in the subclass."""
    return self.id

get_iri_ref(field_name)

Return the stored IRI reference string(s) for a field without triggering resolution.

Parameters:

Name Type Description Default
field_name str

The name of the field to retrieve the IRI reference for.

required

Returns:

Type Description
A string IRI, a list of string IRIs, or ``None`` if no IRI is

stored for the given field.

Source code in src/oold/model/v1/__init__.py
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
def get_iri_ref(self, field_name: str):
    """Return the stored IRI reference string(s) for a field without
    triggering resolution.

    Parameters
    ----------
    field_name
        The name of the field to retrieve the IRI reference for.

    Returns
    -------
        A string IRI, a list of string IRIs, or ``None`` if no IRI is
        stored for the given field.
    """
    iris = self.__iris__.get(field_name)
    if iris is None:
        return None
    if isinstance(iris, list):
        return iris if iris else None
    return iris

get_raw(field_name)

Return the raw value of a field without triggering IRI resolution.

Unlike normal attribute access which may trigger network calls to resolve IRI references, this returns the Python object as stored internally (None for unresolved IRIs, the model instance if already resolved, or a plain value for non-IRI fields).

Parameters:

Name Type Description Default
field_name str

The name of the field to retrieve.

required

Returns:

Type Description
The raw field value, or ``None`` if the field is unresolved or

does not exist.

Source code in src/oold/model/v1/__init__.py
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
def get_raw(self, field_name: str):
    """Return the raw value of a field without triggering IRI resolution.

    Unlike normal attribute access which may trigger network calls to
    resolve IRI references, this returns the Python object as stored
    internally (``None`` for unresolved IRIs, the model instance if
    already resolved, or a plain value for non-IRI fields).

    Parameters
    ----------
    field_name
        The name of the field to retrieve.

    Returns
    -------
        The raw field value, or ``None`` if the field is unresolved or
        does not exist.
    """
    return self.__dict__.get(field_name)

json(*, include=None, exclude=None, by_alias=False, skip_defaults=None, exclude_unset=False, exclude_defaults=False, exclude_none=False, encoder=None, models_as_dict=True, **dumps_kwargs)

Generate a JSON representation of the model, include and exclude arguments as per dict().

encoder is an optional function to supply as default to json.dumps(), other arguments as per json.dumps().

Source code in src/oold/model/v1/__init__.py
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
def json(
    self,
    *,
    include: Union["AbstractSetIntStr", "MappingIntStrAny"] | None = None,
    exclude: Union["AbstractSetIntStr", "MappingIntStrAny"] | None = None,
    by_alias: bool = False,
    skip_defaults: bool | None = None,
    exclude_unset: bool = False,
    exclude_defaults: bool = False,
    exclude_none: bool = False,
    encoder: Callable[[Any], Any] | None = None,
    models_as_dict: bool = True,
    **dumps_kwargs: Any,
) -> str:
    """
    Generate a JSON representation of the model,
    `include` and `exclude` arguments as per `dict()`.

    `encoder` is an optional function to supply as `default` to json.dumps(),
    other arguments as per `json.dumps()`.
    """
    d = json.loads(
        BaseModel.json(
            self,
            include=include,
            exclude=exclude,
            by_alias=by_alias,
            skip_defaults=skip_defaults,
            exclude_unset=exclude_unset,
            exclude_defaults=exclude_defaults,
            exclude_none=False,  # handle None values separately
            encoder=encoder,
            models_as_dict=models_as_dict,
            **dumps_kwargs,
        )
    )  # ToDo directly use dict?
    # this may replace some None values with IRIs in case they were never resolved
    # thats why we handle exclude_none there
    self._object_to_iri(d)
    # Recursively apply _object_to_iri for nested models
    self._recursive_object_to_iri(d, self)
    if exclude_none:
        d = self.remove_none(d)
    return json.dumps(d, **dumps_kwargs)

oold_query(item) classmethod

oold_query(item: str) -> Self
oold_query(item: list[str]) -> LinkedBaseModelList[Self]
oold_query(
    item: Query | Condition | bool,
) -> Optional[LinkedBaseModelList[Self]]

Allow access to the class by its IRI.

Source code in src/oold/model/v1/__init__.py
644
645
646
647
648
649
@classmethod
def oold_query(
    cls, item: str | list[str] | Query | bool
) -> Union[Self, "LinkedBaseModelList[Self]", Optional["LinkedBaseModelList[Self]"]]:
    """Allow access to the class by its IRI."""
    return cls._oold_query(item)

parse_obj(obj) classmethod

Parse the object and return a LinkedBaseModel instance. This method is called by pydantic when creating a new (default) instance of the model.

Source code in src/oold/model/v1/__init__.py
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
@classmethod
def parse_obj(cls, obj: Any) -> "LinkedBaseModel":
    """Parse the object and return a LinkedBaseModel instance.
    This method is called by pydantic when creating
    a new (default) instance of the model."""
    if isinstance(obj, str):
        # pydantic v1
        return cls._resolve([obj])[obj]
    if isinstance(obj, list):
        # pydantic v1
        # return cls._resolve(obj).nodes[obj[0]]
        node_dict = cls._resolve(obj)
        node_list = []
        for iri in obj:
            node = node_dict[iri]
            if node:
                node_list.append(node)
        return node_list
    elif isinstance(obj, dict):
        return super().parse_obj(obj)

store_jsonld()

Store the model instance in a backend matching its IRI.

Source code in src/oold/model/v1/__init__.py
603
604
605
def store_jsonld(self):
    """Store the model instance in a backend matching its IRI."""
    self._store()

to_json(exclude_defaults=False)

Return the JSON representation of the object as dict.

Parameters:

Name Type Description Default
exclude_defaults bool

If True, fields with default values are excluded from the output. Useful for compact storage where defaults can be re-populated on deserialization via from_json().

False
Source code in src/oold/model/v1/__init__.py
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
def to_json(self, exclude_defaults: bool = False) -> builtins.dict:
    """Return the JSON representation of the object as dict.

    Parameters
    ----------
    exclude_defaults
        If True, fields with default values are excluded from the
        output. Useful for compact storage where defaults can be
        re-populated on deserialization via from_json().
    """
    result = json.loads(
        self.json(
            exclude_none=True,
            exclude_defaults=exclude_defaults,
        )
    )
    # Re-inject IRI-only fields from __iris__ that were excluded
    # because their model value is None (the IRI lives in __iris__)
    if hasattr(self, "__iris__"):
        for field_name, iri in self.__iris__.items():
            if iri is None:
                continue
            existing = result.get(field_name)
            if existing is None or existing == [] or existing == {}:
                result[field_name] = iri
    return result

to_jsonld()

Return the RDF representation of the object as JSON-LD.

Source code in src/oold/model/v1/__init__.py
826
827
828
def to_jsonld(self) -> builtins.dict:
    """Return the RDF representation of the object as JSON-LD."""
    return export_jsonld(self, BaseModel)

Backend interface

Abstract interface implemented by all backends.

Bases: Resolver

Source code in src/oold/backend/interface.py
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
class Backend(Resolver):
    def store(self, param: StoreParam) -> StoreResult:
        jsonld_dicts = {}
        for iri, node in param.nodes.items():
            if node is None:
                jsonld_dicts[iri] = None
            else:
                if self.format == LinkedDataFormat.JSON_LD:
                    jsonld_dicts[iri] = node.to_jsonld()
                elif self.format == LinkedDataFormat.JSON:
                    jsonld_dicts[iri] = node.to_json()
                else:
                    raise ValueError(f"Unsupported format {self.format}")
        if self.format == LinkedDataFormat.JSON:
            return self.store_json_dicts(jsonld_dicts)
        else:
            return self.store_jsonld_dicts(jsonld_dicts)

    def store_jsonld_dicts(self, jsonld_dicts: dict[str, dict]) -> StoreResult:
        raise NotImplementedError("store_jsonld_dicts method not implemented in Backend subclass")

    def store_json_dicts(self, json_dicts: dict[str, dict]) -> StoreResult:
        raise NotImplementedError("store_json_dicts method not implemented in Backend subclass")

Generator

Code generation from OO-LD / JSON Schema definitions.

Source code in src/oold/generator.py
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
class Generator:
    class GenerateParams(BaseModel):
        json_schemas: list[dict]
        """JSON SCHEMA source(s)"""
        preprocess: bool = True
        """Preprocess the JSON schemas before generating the models"""
        main_schema: str | None = None
        """File name of the main schema"""
        output_model_type: DataModelType | None = (DataModelType.PydanticV2BaseModel,)
        """Output model type, e.g. PydanticV2BaseModel or PydanticBaseModel"""
        output_model_path: Path | None = Path(__file__).parent / "model" / "example.py"
        """Output model path, if not set the model will be generated
        in the current directory"""
        working_dir_path: Path | None = None
        """Working directory to store intermedia files
        and the generated partial models"""
        generate_init_py_files: bool = True
        """Generate __init__.py files along the output_model_path"""

    def generate(
        self,
        params: GenerateParams,
    ):
        if params.preprocess:
            self.preprocess(Generator.PreprocessParams(json_schemas=params.json_schemas))

        # monkey patch class
        datamodel_code_generator.parser.jsonschema.JsonSchemaParser = OOLDJsonSchemaParser

        with TemporaryDirectory() as temporary_directory_name:
            temporary_directory = Path(temporary_directory_name)
            if params.working_dir_path is not None:
                temporary_directory = params.working_dir_path

            input = Path(temporary_directory)
            if params.main_schema is not None:
                input = Path(temporary_directory / Path(params.main_schema))

            output = params.output_model_path
            if params.generate_init_py_files:
                # generate __init__.py files in every subdirectory
                # of the output model path that does not exist yet
                # output may be a file or a directory

                # check if output is a file or a directory
                target_dir = output
                if params.main_schema is not None:
                    target_dir = output.parent

                # interate over the target_dir path, starting at the top level dir
                # e.g. 'C:' or '/var'
                for segment in target_dir.parts:
                    # create the segment path
                    segment_path = Path(*target_dir.parts[: target_dir.parts.index(segment) + 1])
                    # check if the segment path exists
                    if not segment_path.exists():
                        # create the __init__.py file
                        os.makedirs(segment_path, exist_ok=False)
                        init_file = segment_path / "__init__.py"
                        with open(init_file, "w", encoding="utf-8") as f:
                            f.write("# Generated by oold.generator\n")

            for schema in params.json_schemas:
                name = schema["id"]
                os.makedirs(
                    os.path.dirname(Path(temporary_directory / (name + ".json"))),
                    exist_ok=True,
                )
                with open(Path(temporary_directory / (name + ".json")), "w", encoding="utf-8") as f:
                    schema_str = json.dumps(schema, ensure_ascii=False, indent=2).replace("dollarref", "$ref")
                    # print(schema_str)
                    f.write(schema_str + "\n")

            if params.output_model_type == DataModelType.PydanticV2BaseModel:
                base_class = "oold.model.LinkedBaseModel"
            else:
                base_class = "oold.model.v1.LinkedBaseModel"
            generate(
                input_=input,
                # json_schema,
                input_file_type=InputFileType.JsonSchema,
                # input_filename="Foo.json",
                output=output,
                # set up the output model types
                output_model_type=params.output_model_type,
                # custom_template_dir=Path(model_dir_path),
                field_include_all_keys=True,
                base_class=base_class,
                # use_default = True,
                allof_class_hierarchy=(datamodel_code_generator.AllOfClassHierarchy.Always),
                enum_field_as_literal=datamodel_code_generator.LiteralType.Off,
                use_title_as_name=True,
                use_schema_description=True,
                use_field_description=True,
                encoding="utf-8",
                use_double_quotes=True,
                disable_timestamp=True,
                collapse_root_models=True,
                reuse_model=True,
                # create MyEnum(str, Enum) instead of MyEnum(Enum)
                use_subclass_enum=True,
                additional_imports=["pydantic.ConfigDict"]
                if params.output_model_type == DataModelType.PydanticV2BaseModel
                else [],
                apply_default_values_for_required_fields=True,
            )

            if params.main_schema is not None:
                content = ""
                with open(output, encoding="utf-8") as f:
                    content = f.read()
                os.remove(output)

                content = re.sub(
                    r"(UUID = Field\(...)",
                    r"UUID = Field(default_factory=uuid4",
                    content,
                )  # enable default value for uuid

                if params.output_model_type == DataModelType.PydanticBaseModel:
                    # we are now using pydantic.v1
                    # pydantic imports lead to uninitialized fields
                    # (FieldInfo still present)
                    content = re.sub(r"(from pydantic import)", "from pydantic.v1 import", content)

                # fix unserializable defaults from datamodel-code-generator
                # when allOf merges a property override (e.g. hidden:true) with
                # a parent field typed as a complex model, the default becomes
                # an unserializable sentinel: lambda :Foo.parse_obj(<object ...>)
                content = re.sub(
                    r"default_factory=lambda\s*:.*<object object at 0x[0-9a-fA-F]+>\)",
                    "default=None)",
                    content,
                )
                # fix lambda formatting (space before colon breaks black)
                content = content.replace("lambda :", "lambda:")

                # write the content to the file
                with open(output, "w", encoding="utf-8") as f:
                    f.write(content)

    class PreprocessParams(BaseModel):
        json_schemas: list[dict]
        """JSON SCHEMA source(s)"""

    def preprocess(self, params: PreprocessParams):
        for schema in params.json_schemas:
            # schema = self.merge_property_schemas(schema)
            for property_key in schema.get("properties", {}):
                property = schema["properties"][property_key]
                if "range" in property:
                    if "type" in property:
                        del property["type"]
                    # if range is a string we create a allOf with a ref to the range
                    if isinstance(property["range"], str):
                        property["allOf"] = [{"$ref": property["range"]}]
                    else:
                        property["$ref"] = property["range"]
                    if "required" in schema and property_key in schema["required"]:
                        # if no default value is set, remove the property from required
                        if "default" not in property:
                            schema["required"].remove(property_key)
                        if "x-oold-required-iri" not in property:
                            property["x-oold-required-iri"] = True
                if "items" in property:
                    if "range" in property["items"]:
                        if "type" in property["items"]:
                            del property["items"]["type"]
                        if isinstance(property["items"]["range"], str):
                            property["items"]["allOf"] = [{"$ref": property["items"]["range"]}]
                        else:
                            property["items"]["$ref"] = property["items"]["range"]
                        property["range"] = property["items"]["range"]
                        if "required" in schema and property_key in schema["required"]:
                            # if no default value is set,
                            # remove the property from required
                            if "default" not in property["items"]:
                                schema["required"].remove(property_key)
                            if "x-oold-required-iri" not in property:
                                property["x-oold-required-iri"] = True

                    if "properties" in property["items"]:
                        self.preprocess(Generator.PreprocessParams(json_schemas=[property["items"]]))

                if "properties" in property:
                    self.preprocess(Generator.PreprocessParams(json_schemas=[property]))

GenerateParams

Bases: BaseModel

Source code in src/oold/generator.py
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class GenerateParams(BaseModel):
    json_schemas: list[dict]
    """JSON SCHEMA source(s)"""
    preprocess: bool = True
    """Preprocess the JSON schemas before generating the models"""
    main_schema: str | None = None
    """File name of the main schema"""
    output_model_type: DataModelType | None = (DataModelType.PydanticV2BaseModel,)
    """Output model type, e.g. PydanticV2BaseModel or PydanticBaseModel"""
    output_model_path: Path | None = Path(__file__).parent / "model" / "example.py"
    """Output model path, if not set the model will be generated
    in the current directory"""
    working_dir_path: Path | None = None
    """Working directory to store intermedia files
    and the generated partial models"""
    generate_init_py_files: bool = True
    """Generate __init__.py files along the output_model_path"""

generate_init_py_files = True class-attribute instance-attribute

Generate init.py files along the output_model_path

json_schemas instance-attribute

JSON SCHEMA source(s)

main_schema = None class-attribute instance-attribute

File name of the main schema

output_model_path = Path(__file__).parent / 'model' / 'example.py' class-attribute instance-attribute

Output model path, if not set the model will be generated in the current directory

output_model_type = (DataModelType.PydanticV2BaseModel,) class-attribute instance-attribute

Output model type, e.g. PydanticV2BaseModel or PydanticBaseModel

preprocess = True class-attribute instance-attribute

Preprocess the JSON schemas before generating the models

working_dir_path = None class-attribute instance-attribute

Working directory to store intermedia files and the generated partial models

PreprocessParams

Bases: BaseModel

Source code in src/oold/generator.py
156
157
158
class PreprocessParams(BaseModel):
    json_schemas: list[dict]
    """JSON SCHEMA source(s)"""

json_schemas instance-attribute

JSON SCHEMA source(s)