Skip to content

Commit

Permalink
FIX: Make namespace.to_dict() recurse fully (#1790)
Browse files Browse the repository at this point in the history
* fix namespace.to_dict

* add test searching for namespaces

* [pre-commit.ci] auto fixes from pre-commit.com hooks

for more information, see https://pre-commit.ci

---------

Co-authored-by: pre-commit-ci[bot] <66853113+pre-commit-ci[bot]@users.noreply.github.com>
  • Loading branch information
bendichter and pre-commit-ci[bot] authored Apr 17, 2024
1 parent 37b11ec commit bff4f0c
Show file tree
Hide file tree
Showing 2 changed files with 24 additions and 6 deletions.
13 changes: 13 additions & 0 deletions tools/schemacode/bidsschematools/tests/test_schema.py
Original file line number Diff line number Diff line change
Expand Up @@ -343,3 +343,16 @@ def test_dereferencing():
},
},
}


def test_namespace_to_dict():

def check_for_namespaces(obj):
if isinstance(obj, dict):
[check_for_namespaces(val) for val in obj.values()]
elif isinstance(obj, list):
[check_for_namespaces(val) for val in obj]
elif isinstance(obj, types.Namespace):
raise ValueError("Namespace object found in dict")

check_for_namespaces(schema.load_schema().to_dict())
17 changes: 11 additions & 6 deletions tools/schemacode/bidsschematools/types/namespace.py
Original file line number Diff line number Diff line change
Expand Up @@ -168,12 +168,17 @@ def __init__(self, *args, **kwargs):
self._properties = dict(*args, **kwargs)

def to_dict(self) -> dict:
ret = {}
for key, val in self._properties.items():
if isinstance(val, Namespace):
val = val.to_dict()
ret[key] = val
return ret

def _to_dict(obj):
if isinstance(obj, Namespace):
return {k: _to_dict(v) for k, v in obj._properties.items()}
if isinstance(obj, list):
return [_to_dict(v) for v in obj]
if isinstance(obj, dict):
return {k: _to_dict(v) for k, v in obj.items()}
return obj

return _to_dict(self)

def __deepcopy__(self, memo):
return self.build(self.to_dict())
Expand Down

0 comments on commit bff4f0c

Please sign in to comment.