Skip to content

Commit de8f371

Browse files
benjefferymergify-bot
authored andcommitted
Add schema.asdict
1 parent 1e8efa1 commit de8f371

File tree

2 files changed

+14
-2
lines changed

2 files changed

+14
-2
lines changed

python/tests/test_metadata.py

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -347,11 +347,15 @@ def test_parse(self):
347347
ms = metadata.parse_metadata_schema("")
348348
assert isinstance(ms, metadata.MetadataSchema)
349349
assert ms.schema is None
350+
assert ms.asdict() is None
350351

351352
# json gives MetaDataSchema with json codec
352353
ms = metadata.parse_metadata_schema(json.dumps({"codec": "json"}))
353354
assert isinstance(ms, metadata.MetadataSchema)
354355
assert ms.schema == {"codec": "json"}
356+
assert ms.asdict() == {"codec": "json"}
357+
# check we get a copy
358+
assert ms.asdict() is not ms._schema
355359

356360
# Bad JSON gives error
357361
with pytest.raises(ValueError):

python/tskit/metadata.py

Lines changed: 10 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -548,8 +548,16 @@ def __eq__(self, other) -> bool:
548548

549549
@property
550550
def schema(self) -> Optional[Mapping[str, Any]]:
551-
# Make schema read-only
552-
return self._schema
551+
# Return a copy to avoid unintentional mutation
552+
return copy.deepcopy(self._schema)
553+
554+
def asdict(self) -> Optional[Mapping[str, Any]]:
555+
"""
556+
Returns a dict representation of this schema. One possible use of this is to
557+
modify this dict and then pass it to the ``MetadataSchema`` constructor to create
558+
a similar schema.
559+
"""
560+
return self.schema
553561

554562
def validate_and_encode_row(self, row: Any) -> bytes:
555563
"""

0 commit comments

Comments
 (0)