Skip to content

Commit 9b5e050

Browse files
committed
add strict arg to Component.to_dict
1 parent 09a254a commit 9b5e050

File tree

2 files changed

+37
-12
lines changed

2 files changed

+37
-12
lines changed

flopy4/mf6/component.py

Lines changed: 35 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -202,18 +202,45 @@ def write(self, format: str = MF6) -> None:
202202
for child in self.children.values(): # type: ignore
203203
child.write(format=format)
204204

205-
def to_dict(self, blocks: bool = False) -> dict[str, Any]:
206-
"""Convert the component to a dictionary representation."""
205+
def to_dict(self, blocks: bool = False, strict: bool = False) -> dict[str, Any]:
206+
"""
207+
Convert the component to a dictionary representation.
208+
209+
Parameters
210+
----------
211+
blocks : bool, optional
212+
If True, return a nested dict keyed by block name
213+
with values as dicts of fields. Default is False.
214+
strict : bool, optional
215+
If True, include only fields in the DFN specification.
216+
217+
Returns
218+
-------
219+
dict[str, Any]
220+
Dictionary containing component data, either
221+
in terms of fields (flat) or blocks (nested).
222+
"""
207223
data = xattree_asdict(self)
208-
data.pop("filename")
209-
data.pop("workspace", None) # might be a Context
210-
data.pop("nodes", None) # TODO: find a better way to omit
224+
spec = self.dfn.fields
225+
226+
if strict:
227+
data.pop("filename")
228+
data.pop("workspace", None) # might be a Context
229+
211230
if blocks:
212231
blocks_ = {} # type: ignore
213-
for field_name, field_value in data.items():
214-
block_name = self.dfn.fields[field_name].block
232+
for field_name in spec.keys():
233+
field_value = data[field_name]
234+
block_name = spec[field_name].block
235+
if strict and block_name is None:
236+
continue
215237
if block_name not in blocks_:
216238
blocks_[block_name] = {}
217239
blocks_[block_name][field_name] = field_value
218240
return blocks_
219-
return data
241+
else:
242+
return {
243+
field_name: data[field_name]
244+
for field_name in spec.keys()
245+
if spec[field_name].block or not strict
246+
}

test/test_component.py

Lines changed: 2 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -526,9 +526,7 @@ def test_to_dict_on_context():
526526
assert "tdis" in result
527527

528528

529-
def test_to_dict_excludes_derived_dims():
530-
# TODO eventually revise to test exclusion of all derived dimensions,
531-
# once we have a mechanism to mark them as such
529+
def test_to_dict_with_strict_excludes_fields_without_block_metadata():
532530
dims = {
533531
"nper": 1,
534532
"nlay": 1,
@@ -537,7 +535,7 @@ def test_to_dict_excludes_derived_dims():
537535
"nodes": 4,
538536
}
539537
dis = Dis(dims=dims)
540-
result = dis.to_dict()
538+
result = dis.to_dict(strict=True)
541539

542540
assert "nlay" in result
543541
assert "nrow" in result

0 commit comments

Comments
 (0)