From db2ff5d09366f1c846b210a279022bc4d19b83a4 Mon Sep 17 00:00:00 2001 From: Iwan Aucamp Date: Thu, 13 May 2021 21:44:11 +0200 Subject: [PATCH] Add pathlib.PurePath support for Graph.{serialize,parse} Graph.parse did already support pathlib.Path but there is no good reason to not support PurePath AFAICT. --- rdflib/graph.py | 6 +++++- rdflib/parser.py | 2 +- test/test_serialize.py | 39 +++++++++++++++++++++++++++++++++++++++ 3 files changed, 45 insertions(+), 2 deletions(-) create mode 100644 test/test_serialize.py diff --git a/rdflib/graph.py b/rdflib/graph.py index c541f1d5b9..0a5812b9c3 100644 --- a/rdflib/graph.py +++ b/rdflib/graph.py @@ -19,6 +19,7 @@ import os import shutil import tempfile +import pathlib from io import BytesIO from urllib.parse import urlparse @@ -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( diff --git a/rdflib/parser.py b/rdflib/parser.py index a6f155a62a..8153e55183 100644 --- a/rdflib/parser.py +++ b/rdflib/parser.py @@ -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 diff --git a/test/test_serialize.py b/test/test_serialize.py new file mode 100644 index 0000000000..37305c8ae6 --- /dev/null +++ b/test/test_serialize.py @@ -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)))