Skip to content

Commit a09d3be

Browse files
committed
optimize the common definitions deepcopy
filter by args first! adding comments
1 parent f9727e3 commit a09d3be

1 file changed

Lines changed: 13 additions & 4 deletions

File tree

schema/common.py

Lines changed: 13 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -230,6 +230,7 @@ def load_definitions(*args, allow_null=False):
230230
231231
If allow_null is True, override definition types to allow null.
232232
"""
233+
# store the definitions once globally after reading from the source file
233234
global COMMON_DEFINITIONS
234235

235236
if COMMON_DEFINITIONS == {}:
@@ -246,23 +247,30 @@ def load_definitions(*args, allow_null=False):
246247

247248
COMMON_DEFINITIONS = common_definitions
248249

249-
definitions = copy.deepcopy(COMMON_DEFINITIONS)
250-
250+
# filter all definitions to those requested as args
251251
if args and len(args) > 0:
252-
definitions = { typekey: definitions.get(typekey) for typekey in args }
252+
_d = { key: COMMON_DEFINITIONS.get(key) for key in args }
253+
else:
254+
_d = COMMON_DEFINITIONS
255+
256+
# create a deepcopy for possible modifications
257+
definitions = copy.deepcopy(_d)
253258

254259
# modify definitions to allow null
255260
if allow_null:
261+
# get all definitions with a type property
256262
typekey = "type"
257263
typedefs = { k: v for k, v in definitions.items() if typekey in v }
258264
for key, defn in typedefs.items():
259265
nullkey = f"null_{key}"
260266

267+
# for reference definitions, override the reference to the null version
261268
if "$ref" in defn:
262269
refid = defn["$ref"].split("/")
263270
refid[-1] = f"null_{refid[-1]}"
264271

265272
defn["$ref"] = "/".join(refid)
273+
# for type definitions, create a new definition allowing null
266274
else:
267275
defnid = defn["$id"].split("/")
268276
defnid[-1] = f"null_{defnid[-1]}"
@@ -274,9 +282,10 @@ def load_definitions(*args, allow_null=False):
274282
nulldefn[typekey] = [nulldefn[typekey]]
275283
if "null" not in nulldefn[typekey]:
276284
nulldefn[typekey].append("null")
277-
285+
# add the null definition to the definitions dict
278286
definitions[nullkey] = nulldefn
279287

288+
# if there was only one arg, return the definition directly
280289
return definitions.get(args[0]) if len(args) == 1 else definitions
281290

282291

0 commit comments

Comments
 (0)