11import json
22from abc import abstractmethod
3- from typing import TYPE_CHECKING , Any , Dict , List , Literal , Optional , Union
3+ from typing import TYPE_CHECKING , Any , Dict , List , Literal , Optional , Union , overload
44
55import pydantic
66from pydantic import BaseModel
7- from typing_extensions import Self # to support python < 3.11
7+ from typing_extensions import Self
88
99from oold .model .static import GenericLinkedBaseModel , export_jsonld , import_jsonld
1010
@@ -60,18 +60,30 @@ def get_resolver(param: GetResolverParam) -> GetResolverResult:
6060class LinkedBaseModelMetaClass (pydantic .main ._model_construction .ModelMetaclass ):
6161 def __new__ (mcs , name , bases , namespace ):
6262 cls = super ().__new__ (mcs , name , bases , namespace )
63- schema = {}
64-
65- # pydantic v2
66- if "model_config" in namespace :
67- if "json_schema_extra" in namespace ["model_config" ]:
68- schema = namespace ["model_config" ]["json_schema_extra" ]
6963
70- if "iri" in schema :
71- iri = schema ["iri" ]
72- _types [iri ] = cls
64+ if hasattr (cls , "get_cls_iri" ):
65+ iri = cls .get_cls_iri ()
66+ if iri is not None :
67+ _types [iri ] = cls
7368 return cls
7469
70+ # override operators, see https://docs.python.org/3/library/operator.html
71+
72+ @overload
73+ def __getitem__ (cls : "LinkedBaseModel" , item : str ) -> Self :
74+ ...
75+
76+ @overload
77+ def __getitem__ (cls : "LinkedBaseModel" , item : List [str ]) -> List [Self ]:
78+ ...
79+
80+ def __getitem__ (
81+ cls : "LinkedBaseModel" , item : Union [str , List [str ]]
82+ ) -> Union [Self , List [Self ]]:
83+ """Allow access to the class by its IRI."""
84+ result = cls ._resolve (item if isinstance (item , list ) else [item ])
85+ return result [item ] if isinstance (item , str ) else [result [i ] for i in item ]
86+
7587
7688# the following switch ensures that autocomplete works in IDEs like VSCode
7789if TYPE_CHECKING :
@@ -92,6 +104,20 @@ class LinkedBaseModel(_LinkedBaseModel):
92104
93105 __iris__ : Optional [Dict [str , Union [str , List [str ]]]] = {}
94106
107+ @classmethod
108+ def get_cls_iri (cls ) -> str :
109+ """Return the unique IRI of the class.
110+ Overwrite this method in the subclass."""
111+ schema = {}
112+ if hasattr (cls , "__config__" ):
113+ if hasattr (cls .__config__ , "schema_extra" ):
114+ schema = cls .__config__ .schema_extra
115+
116+ if "iri" in schema :
117+ return schema ["iri" ]
118+ else :
119+ return None
120+
95121 def get_iri (self ) -> str :
96122 """Return the unique IRI of the object.
97123 Overwrite this method in the subclass."""
0 commit comments