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:
ABCSerializer for PROV documents.
- deserialize_options: ClassVar[frozenset[str]] = frozenset({})¶
Keyword arguments
deserialize()accepts beyondstream;prov.read()forwards only these.
- serialize_options: ClassVar[frozenset[str]] = frozenset({})¶
Keyword arguments
serialize()accepts beyondstreamthat the command line may name with-w.
- document = None¶
PROV document to serialise.
- abstractmethod serialize(stream: IOBase, **args: Any) None[source]¶
Serialize
self.documentand 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
streamand build a newProvDocumentfrom 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.
jsonandprovnhave no optional dependencies and are always registered.rdf(needsrdflib) andxml(needslxml) are registered only if their extra is installed, so thatimport provand JSON/PROV-N work in a minimal install; requesting an unavailable format then raises an informativeDoNotExist(seeget()) rather than a bareModuleNotFoundError.get()andprov.read()call it on first use. The registry order isjson, rdf, provn, xml, jsonld, andprov.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
Serializersubclass 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
ProvDocumentfrom a file, path, or string.A
str/bytessource naming an existing file is read from that file; any otherstr/bytesis parsed as raw document content.If
formatis 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, andProvFormatNotDetectedsays when one is its__cause__; passformatexplicitly 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 anerrorfilter 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; passformatexplicitly 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"). IfNone, every registered format is tried in turn.**kwargs – Passed to the deserializer, for example
profilefor PROV-N orrdf_formatfor PROV-O. Each serializer declares the options it accepts (deserialize_options); withformatgiven, an undeclared option raisesTypeError. With auto-detection, every candidate receives only the options it declares, so an undeclared option has no effect, and an unsupportedprofileends inProvFormatNotDetectedfor PROV-N content and has no effect on content in another format.
- Returns:
The deserialized
ProvDocument.- Raises:
TypeError – If
formatis given and names an option the corresponding deserializer does not declare. The message names the format and the options it accepts.ValueError – If
formatis"provn"andprofileis not"strict","default"or"lenient".ProvFormatNotDetected – If
formatisNoneand no registered serializer produced a non-empty document fromsource. It is also aTypeError; seeProvFormatNotDetectedfor 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:
ErrorA 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,TypeErrorprov.read()could not detect the format of its source.Also a
TypeError, soexcept TypeErroraroundprov.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 worddocumentnames PROV-N. When that reader rejected the source with its ownProvSerializationError, 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 theValueErrorfor an unsupportedprofile, or when a non-seekable stream cannot be read again. Passformattoprov.read()to get a reader’s error on its own.
- class prov.serializers.DoNotExist[source]¶
Bases:
ErrorException for the case a serializer is not available.
- class prov.serializers.provn.ProvNSyntaxError(message: str, line: int, column: int)[source]¶
Bases:
ProvSerializationError,ProvExceptionA 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.