Debian Codegraph @

docs/howto/provo-rdf.md

raw
1 # Work with PROV-O (RDF)
2
3 [PROV-O](https://www.w3.org/TR/prov-o/) support needs the optional `rdflib` dependency:
4
5 ```bash
6 python -m pip install "prov[rdf]"
7 ```
8
9 The serialization format is selected with `format="rdf"`. A second, RDF-specific keyword,
10 `rdf_format`, chooses the concrete RDF syntax (`"trig"` by default) — do not confuse the
11 two.
12
13 ## Serialize to a file
14
15 ```python
16 import prov.model as pm
17
18 document = pm.ProvDocument()
19 document.set_default_namespace("http://example.org/")
20 e = document.entity("e1")
21 a = document.activity("a1")
22 document.wasGeneratedBy(e, a)
23
24 document.serialize("document.trig", format="rdf") # rdf_format="trig" is the default
25 ```
26
27 ## Choose a different RDF syntax
28
29 `rdf_format` accepts anything `rdflib` can serialize to, e.g. `"turtle"`, `"xml"`
30 (RDF/XML), `"nt"`, `"nquads"`:
31
32 ```python
33 turtle_str = document.serialize(format="rdf", rdf_format="turtle")
34 print(turtle_str)
35 ```
36
37 ```{important}
38 Only quad-based syntaxes (`"trig"` — the default — and `"nquads"`) preserve **bundles** as
39 separate named graphs. Triple-based syntaxes such as `"turtle"` or `"xml"` flatten every
40 bundle's statements into a single graph, discarding which bundle each statement came from.
41 Stick with the default TriG if your document has bundles.
42 ```
43
44 ## Serialize to a string
45
46 ```python
47 trig_str = document.serialize(format="rdf")
48 ```
49
50 ## Deserialize from a file or stream
51
52 ```python
53 loaded = pm.ProvDocument.deserialize("document.trig", format="rdf")
54 assert loaded == document
55 ```
56
57 Pass the matching `rdf_format` if the input is not TriG:
58
59 ```python
60 loaded = pm.ProvDocument.deserialize(content=turtle_str, format="rdf", rdf_format="turtle")
61 ```
62
63 ## Deserialize from a string
64
65 ```python
66 loaded = pm.ProvDocument.deserialize(content=trig_str, format="rdf")
67 ```
68
69 ## Auto-detect the format with `prov.read()`
70
71 PROV-O/RDF is the second format `prov.read()` tries (after PROV-JSON), so genuine RDF
72 content auto-detects reliably:
73
74 ```python
75 import prov
76
77 loaded = prov.read("document.trig")
78 assert loaded == document
79 ```
80
81 ## Common errors
82
83 Malformed RDF raises `rdflib`'s own parser error:
84
85 ```python
86 try:
87 pm.ProvDocument.deserialize(content="not rdf", format="rdf")
88 except Exception as e:
89 print(f"{type(e).__name__}")
90 ```
91
92 ```text
93 BadSyntax
94 ```