Skip to content

Commit

Permalink
Add pathlib.PurePath support for Graph.{serialize,parse}
Browse files Browse the repository at this point in the history
Graph.parse did already support pathlib.Path but there is no good
reason to not support PurePath AFAICT.
  • Loading branch information
aucampia committed Jun 29, 2021
1 parent 5d77b14 commit db9ebf4
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 2 deletions.
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()

0 comments on commit db9ebf4

Please sign in to comment.