Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

FIX: Make namespace.to_dict() recurse fully #1790

Merged
merged 3 commits into from
Apr 17, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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