From ad0226dcf31e538d2f8c187ebf70079bda72c75a Mon Sep 17 00:00:00 2001 From: Charles Tapley Hoyt Date: Tue, 21 Jan 2025 19:38:13 +0100 Subject: [PATCH] Refactor common code for serializing references/literals --- src/pyobo/struct/reference.py | 19 ++++++++++--------- src/pyobo/struct/struct.py | 16 +++------------- 2 files changed, 13 insertions(+), 22 deletions(-) diff --git a/src/pyobo/struct/reference.py b/src/pyobo/struct/reference.py index c988a228..4451da5c 100644 --- a/src/pyobo/struct/reference.py +++ b/src/pyobo/struct/reference.py @@ -250,15 +250,7 @@ def multi_reference_escape( def comma_separate_references(elements: Iterable[Reference | OBOLiteral]) -> str: """Map a list to strings and make comma separated.""" - parts = [] - for element in elements: - match element: - case Reference(): - parts.append(get_preferred_curie(element)) - case OBOLiteral(value, _datatype, _language): - # TODO check datatype is URI - parts.append(value) - return ", ".join(parts) + return ", ".join(reference_or_literal_to_str(element) for element in elements) def _ground_relation(relation_str: str) -> Reference | None: @@ -343,3 +335,12 @@ def _reference_list_tag( ) -> Iterable[str]: for reference in references: yield f"{tag}: {reference_escape(reference, ontology_prefix=ontology_prefix, add_name_comment=True)}" + + +def reference_or_literal_to_str(x: Reference | OBOLiteral) -> str: + """Get a string from a reference or literal.""" + match x: + case Reference(): + return get_preferred_curie(x) + case OBOLiteral(value, _, _): + return value diff --git a/src/pyobo/struct/struct.py b/src/pyobo/struct/struct.py index 628369a0..7998b62e 100644 --- a/src/pyobo/struct/struct.py +++ b/src/pyobo/struct/struct.py @@ -36,6 +36,7 @@ default_reference, get_preferred_curie, reference_escape, + reference_or_literal_to_str, ) from .struct_utils import ( Annotation, @@ -341,14 +342,7 @@ def extend_parents(self, references: Collection[Reference]) -> None: def get_property_literals(self, prop: ReferenceHint) -> list[str]: """Get properties from the given key.""" - rv = [] - for t in self.properties.get(_ensure_ref(prop), []): - match t: - case Reference(): - rv.append(get_preferred_curie(t)) - case OBOLiteral(value, _datatype, _language): - rv.append(value) - return rv + return [reference_or_literal_to_str(t) for t in self.properties.get(_ensure_ref(prop), [])] def get_property(self, prop: ReferenceHint) -> str | None: """Get a single property of the given key.""" @@ -1548,11 +1542,7 @@ def iterate_filtered_properties( for t in term.get_property_annotations(): if t.predicate != prop: continue - match t.value: - case OBOLiteral(value, _datatype): - yield term, value - case Reference(): - yield term, get_preferred_curie(t.value) + yield term, reference_or_literal_to_str(t.value) def get_filtered_properties_df( self, prop: ReferenceHint, *, use_tqdm: bool = False