serializer.py 1.9 KB

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