Source code

Download source archive ↓

src/rdflib/serializer.py

1"""Serializer plugin interface.
2
3The RDF serialization plugins used during
4[RDFlib's common serialization of a graph][rdflib.graph.Graph.serialize]
5is described in this module.
6
7TODO: info for how to write a serializer that can plugin to rdflib.
8See also [`rdflib.plugin`][rdflib.plugin]
9
10All builtin RDF Serializer are listed
11under [`rdflib.plugins.serializers`][rdflib.plugins.serializers].
12"""
13
14from __future__ import annotations
15
16from typing import IO, TYPE_CHECKING, Any, Optional, TypeVar, Union
17
18from rdflib.term import URIRef
19
20if TYPE_CHECKING:
21    from rdflib.graph import Graph
22
23
24__all__ = ["Serializer"]
25
26_StrT = TypeVar("_StrT", bound=str)
27
28
29class Serializer:
30    """Base class for RDF Serializer.
31
32    New Serializer can be registered as plugin as described
33    in [`rdflib.plugin`][rdflib.plugin].
34    """
35
36    def __init__(self, store: Graph):
37        self.store: Graph = store
38        self.encoding: str = "utf-8"
39        self.base: Optional[str] = None
40
41    def serialize(
42        self,
43        stream: IO[bytes],
44        base: Optional[str] = None,
45        encoding: Optional[str] = None,
46        **args: Any,
47    ) -> None:
48        """Abstract method. Print [Graph][rdflib.graph.Graph].
49        Used in [Graph.serialize][rdflib.graph.Graph.serialize]
50
51        Serialize Graph
52
53        Args:
54            stream: The destination to serialize the graph to.
55            base: The base IRI for formats that support it.
56            encoding: Encoding of output.
57            args: Additional arguments to pass to the Serializer that will be used.
58        """
59
60    def relativize(self, uri: _StrT) -> Union[_StrT, URIRef]:
61        base = self.base
62        if base is not None and uri.startswith(base):
63            # type error: Incompatible types in assignment (expression has type "str", variable has type "Node")
64            uri = URIRef(uri.replace(base, "", 1))  # type: ignore[assignment]
65        return uri