prov.serializers

prov.serializers defines the serializer interface behind ProvDocument.serialize() and ProvDocument.deserialize(), and the registry that maps a format name ("json", "rdf", "provn", "xml", "jsonld") to its serializer class. Read and write documents shows how to read and write in any format, and the format guides (Work with PROV-JSON, Work with PROV-XML, Work with PROV-O (RDF), Work with PROV-N, Work with PROV-JSONLD) show how to use each format. This page documents the interface, the registry and the exception classes for reading and writing.

class prov.serializers.Serializer(document: ProvDocument | None = None)[source]

Bases: ABC

Serializer for PROV documents.

deserialize_options: ClassVar[frozenset[str]] = frozenset({})

Keyword arguments deserialize() accepts beyond stream; prov.read() forwards only these.

serialize_options: ClassVar[frozenset[str]] = frozenset({})

Keyword arguments serialize() accepts beyond stream that the command line may name with -w.

document = None

PROV document to serialise.

abstractmethod serialize(stream: IOBase, **args: Any) → None[source]

Serialize self.document and write it to a stream.

Subclasses implement this to encode the bound document and write the result to stream.

Parameters:
  • stream – Stream to write the serialized document into.

  • **args – Format-specific serialization options, passed through by subclasses.

abstractmethod deserialize(stream: io.IOBase, **args: Any) → ProvDocument[source]

Read and parse a document from a stream.

Subclasses implement this to parse stream and build a new ProvDocument from it.

Parameters:
  • stream – Stream to deserialize the document from.

  • **args – Format-specific deserialization options, passed through by subclasses.

Returns:

The deserialized ProvDocument.

class prov.serializers.Registry[source]

Registry of serializers.

serializers: ClassVar[dict[str, type[Serializer]] | None] = None

Property caching all available serializers in a dict.

static load_serializers() → None[source]

Load all serializers whose optional dependencies are installed.

json and provn have no optional dependencies and are always registered. rdf (needs rdflib) and xml (needs lxml) are registered only if their extra is installed, so that import prov and JSON/PROV-N work in a minimal install; requesting an unavailable format then raises an informative DoNotExist (see get()) rather than a bare ModuleNotFoundError.

get() and prov.read() call it on first use. The registry order is json, rdf, provn, xml, jsonld, and prov.read() tries the formats in that order when it detects one, as Detect the format with prov.read() describes for streams.

prov.serializers.get(format_name: str) → type[Serializer][source]

Return the serializer class registered for a format.

Parameters:

format_name – Registry key, e.g. "json", "xml", "rdf", "provn", "jsonld".

Returns:

The Serializer subclass for the format.

Raises:

DoNotExist – If no serializer is registered under format_name.

Reading documents

Detect the format with prov.read() shows how to read a document whose format is not known.

prov.read(source: StreamOrPath, format: str | None = None, **kwargs: Any) → ProvDocument[source]

Read a ProvDocument from a file, path, or string.

A str/bytes source naming an existing file is read from that file; any other str/bytes is parsed as raw document content.

If format is not given, the format is detected by trying each registered deserializer in turn and returning the first that both succeeds and produces a non-empty document. A source that parses to no records and no bundles is not that format. Auto-detection swallows each candidate’s error, and ProvFormatNotDetected says when one is its __cause__; pass format explicitly to get a reader’s error on its own.

prov’s own warnings from a candidate that fails or produces an empty document are dropped. Those of the chosen candidate are emitted at the caller’s line, so an error filter raises them from here. Warnings from other libraries are emitted where they occur.

A seekable stream source (e.g. an open file object, io.StringIO, io.BytesIO) is rewound to its starting position before each auto-detection attempt, so every candidate format sees the full content. A non-seekable stream is consumed by the first candidate; pass format explicitly for those.

Parameters:
  • source – File-like stream, path to an existing file, or raw content.

  • format – Serialization format to use (e.g. "json", "xml", "rdf", "provn"). If None, every registered format is tried in turn.

  • **kwargs – Passed to the deserializer, for example profile for PROV-N or rdf_format for PROV-O. Each serializer declares the options it accepts (deserialize_options); with format given, an undeclared option raises TypeError. With auto-detection, every candidate receives only the options it declares, so an undeclared option has no effect, and an unsupported profile ends in ProvFormatNotDetected for PROV-N content and has no effect on content in another format.

Returns:

The deserialized ProvDocument.

Raises:
  • TypeError – If format is given and names an option the corresponding deserializer does not declare. The message names the format and the options it accepts.

  • ValueError – If format is "provn" and profile is not "strict", "default" or "lenient".

  • ProvFormatNotDetected – If format is None and no registered serializer produced a non-empty document from source. It is also a TypeError; see ProvFormatNotDetected for its __cause__.

Exceptions

The exceptions below derive from prov.Error. The model’s refusals derive from ProvException, and a failure to read or write a document derives from ProvSerializationError.

prov.Error
|-- ProvException                        (prov.model)
|   |-- ProvValueError                   also a ValueError
|   |-- ProvExceptionInvalidQualifiedName
|   |-- ProvElementIdentifierRequired
|   |-- ProvMissingFormalAttribute
|   `-- ProvUnificationError
|-- ProvSerializationError               (prov.serializers)
|   |-- ProvJSONException
|   |-- ProvJSONLDException
|   |-- ProvNSyntaxError                 also a ProvException
|   |-- ProvXMLException
|   |-- ProvRDFException
|   `-- ProvFormatNotDetected            also a TypeError
`-- DoNotExist                           (prov.serializers)

ProvSerializationError says what a reader’s error carries, and code that builds the record gets the model’s exception itself. ProvFormatNotDetected says when its __cause__ is a reader’s error.

With an explicit format, input that is not well-formed in the underlying syntax raises the parsing library’s own error, outside the tree: json.JSONDecodeError for the two JSON formats, lxml’s XMLSyntaxError, and rdflib’s parser error for the chosen rdf_format, such as BadSyntax for TriG and Turtle.

class prov.serializers.ProvSerializationError[source]

Bases: Error

A document cannot be read from or written to a format.

Each format’s error derives from it. A reader raises its own subclass for input it cannot decode. When the model refuses a record or a namespace that the reader builds, the reader’s error locates the record or the declaration, carries the model’s sentence and sets the model’s exception as __cause__. A fault that the reader finds itself has no cause.

class prov.serializers.ProvFormatNotDetected[source]

Bases: ProvSerializationError, TypeError

prov.read() could not detect the format of its source.

Also a TypeError, so except TypeError around prov.read() keeps working.

The start of the source, after any whitespace, can name one reader. A { names PROV-JSONLD when the first 4096 characters hold "@context" or "@graph", and PROV-JSON otherwise. The word document names PROV-N. When that reader rejected the source with its own ProvSerializationError, that error is the __cause__, so the traceback shows the reader’s message and position. Any other start, such as < or @prefix, names no reader, and the exception has no cause. Neither has one when the named reader raised another error, such as the parsing library’s error for malformed JSON or the ValueError for an unsupported profile, or when a non-seekable stream cannot be read again. Pass format to prov.read() to get a reader’s error on its own.

class prov.serializers.DoNotExist[source]

Bases: Error

Exception for the case a serializer is not available.

class prov.serializers.provn.ProvNSyntaxError(message: str, line: int, column: int)[source]

Bases: ProvSerializationError, ProvException

A PROV-N document could not be tokenised or parsed.

message

What was expected and what was found.

line

1-based line of the offending token.

column

1-based column of the offending token.