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

Retain datatype when listing literals from rdflib #163

Merged
merged 3 commits into from
Jan 11, 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
27 changes: 27 additions & 0 deletions tests/backends/test_rdflib.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,27 @@
"""Test rdflib backend.

Most of the rdflib backend is already tested in tests/test_triplestore.py.
"""
import pytest

from tripper import Literal, Triplestore

rdflib = pytest.importorskip("rdflib")


# Test for issue #162: Literals are lost when listing triples with rdflib
ts = Triplestore("rdflib")
ts.parse(
format="turtle",
data=(
"<http://ex#s> <http://ex#p> "
'"abc"^^<http://www.w3.org/2001/XMLSchema#string> .'
),
)
assert list(ts.triples()) == [
(
"http://ex#s",
"http://ex#p",
Literal("abc", datatype="http://www.w3.org/2001/XMLSchema#string"),
)
]
2 changes: 1 addition & 1 deletion tripper/mappings/mappings.py
Original file line number Diff line number Diff line change
Expand Up @@ -122,7 +122,7 @@ def __repr__(self):
args.append(f", property_iri={self.property_iri}")
if self.cost:
args.append(f", cost={self.cost}")
return f"Value({self._value}{''.join(args)})"
return f"Value({self._value!r}{''.join(args)})"
ajeklund marked this conversation as resolved.
Show resolved Hide resolved

def get_value(self, unit=None, magnitude=False, quantity=None) -> "Any":
"""Returns the evaluated value of given input route number.
Expand Down
10 changes: 9 additions & 1 deletion tripper/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -128,10 +128,18 @@ def parse_literal(literal: "Any") -> "Literal":
if isinstance(literal, Literal):
return literal

if hasattr(literal, "lang"):
lang = literal.lang
elif hasattr(literal, "language"):
lang = literal.language

if not lang and hasattr(literal, "datatype"):
datatype = str(literal.datatype)

# This will handle rdflib literals correctly and probably most other
# literal representations as well.
if hasattr(literal, "value"):
return Literal(literal.value)
return Literal(literal.value, lang=lang, datatype=datatype)
ajeklund marked this conversation as resolved.
Show resolved Hide resolved

if not isinstance(literal, str):
if isinstance(literal, tuple(Literal.datatypes)):
Expand Down