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 May 13, 2021
1 parent 8d592a2 commit db2ff5d
Show file tree
Hide file tree
Showing 3 changed files with 45 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
from urllib.parse import urlparse
Expand Down Expand Up @@ -990,7 +991,10 @@ def serialize(
stream = destination
serializer.serialize(stream, base=base, encoding=encoding, **args)
else:
location = destination
if isinstance(destination, pathlib.PurePath):
location = str(destination)
else:
location = 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 @@ -222,7 +222,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
39 changes: 39 additions & 0 deletions test/test_serialize.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
from unittest import TestCase
from rdflib import Graph, URIRef
from tempfile import NamedTemporaryFile, TemporaryDirectory
from pathlib import Path, PurePath


class TestSerialize(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)))

0 comments on commit db2ff5d

Please sign in to comment.