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

Add pathlib.PurePath support for Graph.serialize and Graph.parse #1309

Merged
merged 1 commit into from
Jun 29, 2021
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
6 changes: 5 additions & 1 deletion rdflib/graph.py
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
import os
import shutil
import tempfile
import pathlib

from io import BytesIO, BufferedIOBase
from urllib.parse import urlparse
Expand Down Expand Up @@ -1065,7 +1066,10 @@ def serialize(
stream = cast(BufferedIOBase, destination)
serializer.serialize(stream, base=base, encoding=encoding, **args)
else:
location = cast(str, destination)
if isinstance(destination, pathlib.PurePath):
location = str(destination)
else:
location = cast(str, destination)
scheme, netloc, path, params, _query, fragment = urlparse(location)
if netloc != "":
print(
Expand Down
2 changes: 1 addition & 1 deletion rdflib/parser.py
Original file line number Diff line number Diff line change
Expand Up @@ -238,7 +238,7 @@ def create_input_source(
else:
if isinstance(source, str):
location = source
elif isinstance(source, pathlib.Path):
elif isinstance(source, pathlib.PurePath):
location = str(source)
elif isinstance(source, bytes):
data = source
Expand Down
43 changes: 43 additions & 0 deletions test/test_serialize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,43 @@
import unittest
from rdflib import Graph, URIRef
from tempfile import NamedTemporaryFile, TemporaryDirectory
from pathlib import Path, PurePath


class TestSerialize(unittest.TestCase):
def setUp(self) -> None:

graph = Graph()
subject = URIRef("example:subject")
predicate = URIRef("example:predicate")
object = URIRef("example:object")
self.triple = (
subject,
predicate,
object,
)
graph.add(self.triple)
self.graph = graph
return super().setUp()

def test_serialize_to_purepath(self):
with TemporaryDirectory() as td:
tfpath = PurePath(td) / "out.nt"
self.graph.serialize(destination=tfpath, format="nt")
graph_check = Graph()
graph_check.parse(source=tfpath, format="nt")

self.assertEqual(self.triple, next(iter(graph_check)))

def test_serialize_to_path(self):
with NamedTemporaryFile() as tf:
tfpath = Path(tf.name)
self.graph.serialize(destination=tfpath, format="nt")
graph_check = Graph()
graph_check.parse(source=tfpath, format="nt")

self.assertEqual(self.triple, next(iter(graph_check)))


if __name__ == "__main__":
unittest.main()