From 414b060f5549582f910c5335ba5019015149a252 Mon Sep 17 00:00:00 2001 From: WhiteGobo Date: Fri, 28 Apr 2023 17:48:09 +0200 Subject: [PATCH] fix: supercharged ConjunctiveGraph.serialize to format as TriG by default (#1674) Created method ConjunctiveGraph.serialize(..., format='trig', ...). Because of typing problems I replaced some annotations in the overloaded methods of rdflib.Graph.serialize, so that in subclasses serialize knows, that it returns type(self) and not Graph. Because Graph.serialize annotations are still incompatible with ConjunctiveGraph.serialize added type: ignore [overriden] to let mypy skip that method. --- rdflib/graph.py | 24 +++++++++++++++++------- 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/rdflib/graph.py b/rdflib/graph.py index 6e2e50aff..f053ea43c 100644 --- a/rdflib/graph.py +++ b/rdflib/graph.py @@ -1225,7 +1225,7 @@ def absolutize(self, uri: str, defrag: int = 1) -> URIRef: # no destination and non-None positional encoding @overload def serialize( - self, + self: _GraphT, destination: None, format: str, base: Optional[str], @@ -1237,7 +1237,7 @@ def serialize( # no destination and non-None keyword encoding @overload def serialize( - self, + self: _GraphT, destination: None = ..., format: str = ..., base: Optional[str] = ..., @@ -1250,7 +1250,7 @@ def serialize( # no destination and None encoding @overload def serialize( - self, + self: _GraphT, destination: None = ..., format: str = ..., base: Optional[str] = ..., @@ -1262,25 +1262,25 @@ def serialize( # non-None destination @overload def serialize( - self, + self: _GraphT, destination: Union[str, pathlib.PurePath, IO[bytes]], format: str = ..., base: Optional[str] = ..., encoding: Optional[str] = ..., **args: Any, - ) -> "Graph": + ) -> _GraphT: ... # fallback @overload def serialize( - self, + self: _GraphT, destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = ..., format: str = ..., base: Optional[str] = ..., encoding: Optional[str] = ..., **args: Any, - ) -> Union[bytes, str, "Graph"]: + ) -> Union[bytes, str, _GraphT]: ... def serialize( @@ -2193,6 +2193,16 @@ def context_id(self, uri: str, context_id: Optional[str] = None) -> URIRef: context_id = "#context" return URIRef(context_id, base=uri) + def serialize( # type: ignore [override] + self: _ConjunctiveGraphT, + destination: Optional[Union[str, pathlib.PurePath, IO[bytes]]] = None, + format: str = "trig", + base: Optional[str] = None, + encoding: Optional[str] = None, + **args: Any, + ) -> Union[bytes, str, _ConjunctiveGraphT]: + return super().serialize(destination, format, base, encoding, **args) + def parse( self, source: Optional[