Getting started
This guide walks through installing TripleModel, defining a small model, and round-tripping it through an in-memory Store (pyoxigraph-backed graph).
Install
pip install triplemodel
Requirements: Python 3.10+, Pydantic v2, pyoxigraph 0.5+.
Define a model
Subclass TripleModel and declare RDF metadata on a nested Rdf class. Map each RDF property with rdf_field():
from triplemodel import TripleModel, rdf_field
FOAF = "http://xmlns.com/foaf/0.1/"
class Person(TripleModel):
class Rdf:
namespace = "http://example.org/people/"
type_uri = f"{FOAF}Person"
id_field = "slug"
slug: str
name: str = rdf_field(f"{FOAF}name")
age: int | None = rdf_field(f"{FOAF}age", default=None)
|
Purpose |
|---|---|
|
Base IRI; subject = namespace + encoded |
|
Written as |
|
Python field used to build the subject IRI |
Fields without a predicate (no rdf_field / Predicate) are ignored on export and import — useful for computed or application-only data.
Export to a graph
alice = Person(slug="alice", name="Alice", age=30)
graph = alice.to_graph()
print(alice.subject_uri())
Output:
http://example.org/people/alice
to_graph() returns a new Store when you do not pass one. Optional fields set to None (here age when omitted) produce no triple on export.
Import from a graph
Load one resource by subject IRI:
restored = Person.from_graph(graph, alice.subject_uri())
assert restored == alice
Load every resource with the configured type_uri:
people = Person.all_from_graph(graph)
assert len(people) == 1
Module-level functions
You can export without calling instance methods:
from triplemodel import model_to_graph, graph_to_model
graph = model_to_graph(alice)
restored = graph_to_model(graph, Person, alice.subject_uri())
File I/O
ttl = alice.serialize(format="turtle")
restored = Person.parse(data=ttl, format="turtle")[0]
See File I/O (parse and serialize) for parse_file, parse_url, and format autodetection.
See the guides index for multi-value fields, sync/update semantics, nested models, and prefixes.