1
1
import inspect
2
2
from deprecation import deprecated
3
+ from typing import Dict , Any , Type
3
4
4
5
from gemd .entity .dict_serializable import DictSerializable
5
6
from gemd .entity .base_entity import BaseEntity
@@ -21,7 +22,7 @@ class GEMDJson(object):
21
22
22
23
def __init__ (self , scope : str = 'auto' ):
23
24
self ._scope = scope
24
- self ._clazz_index = DictSerializable . class_mapping
25
+ self ._clazz_index = dict ()
25
26
26
27
@property
27
28
def scope (self ) -> str :
@@ -74,8 +75,15 @@ def loads(self, json_str: str, **kwargs):
74
75
# Create an index to hold the objects by their uid reference
75
76
# so we can replace links with pointers
76
77
index = {}
78
+ clazz_index = DictSerializable .class_mapping
79
+ clazz_index .update (self ._clazz_index )
77
80
raw = json_builtin .loads (
78
- json_str , object_hook = lambda x : self ._load_and_index (x , index , True ), ** kwargs )
81
+ json_str ,
82
+ object_hook = lambda x : self ._load_and_index (x ,
83
+ index ,
84
+ clazz_index = clazz_index ,
85
+ substitute = True ),
86
+ ** kwargs )
79
87
# the return value is in the 2nd position.
80
88
return raw ["object" ]
81
89
@@ -196,8 +204,12 @@ def raw_loads(self, json_str, **kwargs):
196
204
# Create an index to hold the objects by their uid reference
197
205
# so we can replace links with pointers
198
206
index = {}
207
+ clazz_index = DictSerializable .class_mapping
208
+ clazz_index .update (self ._clazz_index )
199
209
return json_builtin .loads (
200
- json_str , object_hook = lambda x : self ._load_and_index (x , index ), ** kwargs )
210
+ json_str ,
211
+ object_hook = lambda x : self ._load_and_index (x , index , clazz_index = clazz_index ),
212
+ ** kwargs )
201
213
202
214
@deprecated (deprecated_in = "1.13.0" , removed_in = "2.0.0" ,
203
215
details = "Classes are now automatically registered when extending BaseEntity" )
@@ -229,7 +241,12 @@ def register_classes(self, classes):
229
241
230
242
self ._clazz_index .update (classes )
231
243
232
- def _load_and_index (self , d , object_index , substitute = False ):
244
+ @staticmethod
245
+ def _load_and_index (
246
+ d : Dict [str , Any ],
247
+ object_index : Dict [str , DictSerializable ],
248
+ clazz_index : Dict [str , Type ],
249
+ substitute : bool = False ) -> DictSerializable :
233
250
"""
234
251
Load the class based on the type string and index it, if a BaseEntity.
235
252
@@ -254,10 +271,10 @@ def _load_and_index(self, d, object_index, substitute=False):
254
271
return d
255
272
typ = d .pop ("type" )
256
273
257
- if typ not in self . _clazz_index :
274
+ if typ not in clazz_index :
258
275
raise TypeError ("Unexpected base object type: {}" .format (typ ))
259
276
260
- clz = self . _clazz_index [typ ]
277
+ clz = clazz_index [typ ]
261
278
obj = clz .from_dict (d )
262
279
263
280
if isinstance (obj , BaseEntity ): # Add it to the object index
0 commit comments