Generated API¶
Auto-generated signatures and docstrings for the ontoenv module. See
Python API reference for the same surface organized by purpose.
- exception ontoenv.CatalogRecoveryError¶
Bases:
RuntimeErrorThe catalog cannot be opened because an interrupted mutation requires ontoenv recover or OntoEnv.recover().
- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception ontoenv.ExternalStoreChangedError¶
Bases:
RuntimeError- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class ontoenv.OntoEnv(path=None, recreate=False, create_or_use_cached=False, read_only=False, search_directories=None, require_ontology_names=None, strict=None, offline=None, use_cached_ontologies=None, resolution_policy=None, root=Ellipsis, includes=None, excludes=None, include_ontologies=None, exclude_ontologies=None, temporary=False, remote_cache_ttl_secs=None, graph_store=None, init_from_store=False)¶
Bases:
objectA high-level API for managing and querying RDF ontologies.
The OntoEnv class provides methods for:
Adding ontologies from files, URLs, or in-memory graphs
Managing imports and resolving the dependency closure
Creating merged views over ontology closures
Managing aliases for ontology IRIs
Use
OntoEnv.connect(path)for the normal persistent lifecycle. It creates a missing environment or efficiently reopens an existing one. Callupdate()when configured ontology files or URLs should be discovered or refreshed. UseOntoEnv(temporary=True)for unsaved in-memory work.OntoEnv.create,open,adopt, andrecoverprovide narrower lifecycle contracts. The direct constructor’srecreate=Trueoption deletes and rebuilds the target.ontoenvdirectory; it is not equivalent toconnect.Example
from ontoenv import OntoEnv with OntoEnv.connect("./ontology-env") as env: # Add an ontology env.add("http://example.com/ontology.ttl") # Add an alias - multiple IRIs can refer to one ontology env.add_alias( "http://example.com/B-alias", "http://example.com/B", ) # Resolve an alias to its canonical IRI canonical = env.resolve_alias("http://example.com/B-alias") # Get the closure (all imported ontologies) graph, iris = env.get_closure("http://example.com/ontology")
The OntoEnv uses a snapshot-based approach for consistency: operations see a consistent view of the environment, and the underlying store can be updated without affecting existing queries.
- add(location, overwrite=False, fetch_imports=True, force=False, rename=None)¶
Add a new ontology to the OntoEnv
- add_alias(alias_iri, canonical_iri)¶
Add an alias for a canonical ontology IRI.
The alias will route to the same graph as the canonical IRI. Aliases only point to canonical IRIs (not other aliases) to avoid chains.
- Parameters:
alias_iri – The alias IRI to add
canonical_iri – The canonical IRI that the alias should point to
Example
env.add_alias("http://example.com/B-alias", "http://example.com/B")
After this,
env.get_graph("http://example.com/B-alias")will return the same graph asenv.get_graph("http://example.com/B").
- add_no_imports(location, overwrite=False, force=False, rename=None)¶
Add a new ontology to the OntoEnv without exploring owl:imports.
- adopt(graph_store, overwrite=False, **options)¶
- close()¶
- connect(graph_store=None, sync='auto', read_only=False, **options)¶
Connect to a persistent environment.
sync=”auto” reconciles direct graph-store changes when the backend can identify them. It does not refresh ontology source files or URLs; call update() after connecting for source refresh.
Omitted configuration preserves persisted settings. Explicit values override them; writable connections persist overrides and read-only connections keep them session-local.
- copy_closure(uri, graph=None, rewrite_sh_prefixes=True, remove_owl_imports=True, recursion_depth=Ellipsis)¶
Copy the imports closure of uri into a mutable graph and return it alongside the closure list.
The first element of the returned tuple is either the provided graph after mutation or a brand-new rdflib.Graph. The second element is an ordered list of ontology IRIs in the resolved closure starting with uri. Set rewrite_sh_prefixes or remove_owl_imports to control post-processing of the merged triples.
Works correctly with custom
graph_store=backends: each graph in the closure is fetched via the backend’sget_graphrather than the internal oxigraph store.
- copy_dataset(dataset=None)¶
Copy the environment into a mutable in-memory
rdflib.Dataset.If dataset is provided, quads are added to it and the same object is returned. Otherwise a new
rdflib.Datasetis created.Works correctly with custom
graph_store=backends: every named graph is materialised via the backend’sget_graphpath rather than the internal oxigraph store.
- copy_graph(uri, graph=None)¶
Copy the named graph into a mutable in-memory
rdflib.Graph.If graph is provided, triples are added to it and the same object is returned. Otherwise a new
rdflib.Graphis created.Works correctly with custom
graph_store=backends: triples are fetched via the backend’sget_graphmethod rather than the internal oxigraph store, so the returned graph always reflects what the Python store holds.Raises
UnresolvedImportErrorwhen uri is a currently known unresolved import. An arbitrary unknown graph IRI raisesValueError; parsing and backend failures retain their own error types.
- copy_union(uris, root, graph=None, include_closures=False, rewrite_sh_prefixes=False, remove_owl_imports=False, recursion_depth=Ellipsis)¶
Copy the union of explicitly listed ontology graphs into a mutable graph.
Set
include_closures=Trueto include each listed graph’s transitiveowl:importsclosure. TherootIRI is used for ontology declaration cleanup and optional SHACL prefix rewriting; it does not need to be one of the listed graphs.As a union (vs
copy_closure()), this defaults to a raw merge with no transform applied — matchingget_union(). Passremove_owl_imports=True/rewrite_sh_prefixes=Trueto opt into the closure transforms.Use
get_union()for a read-only store-backed view that avoids materializing triples.Works correctly with custom
graph_store=backends: each graph is fetched via the backend’scopy_graphwhen available, otherwiseget_graph.
- create(graph_store=None, **options)¶
- dump(includes=None)¶
Print the contents of the OntoEnv
- flush()¶
Flush pending changes and rebind cached Graph views to the new snapshot. Graphs returned by prior get_graph calls share the cached Dataset’s store, so they observe post-flush state without re-fetching.
- get_aliases_for(canonical_iri)¶
List all aliases that point to a given canonical IRI.
- Parameters:
canonical_iri – The canonical IRI to list aliases for
- Returns:
A list of all alias IRIs that point to the given canonical IRI
- get_closure(uri, recursion_depth=Ellipsis, remove_owl_imports=True, rewrite_sh_prefixes=True)¶
Return a read-only merged view over the transitive
owl:importsclosure of uri, plus the list of ontology IRIs that contribute to the view (root first, in BFS order).The returned object is a
ontoenv.ViewGraph— a lightweight, non-rdflib.Graphview that delegates triple-pattern lookups to the Rust backend scoped to the closure’s named graphs, so it behaves like a merged graph. Persistent rdf5d environments apply the transform without materializing triples; temporary and custom-store environments use a normalized in-memory fallback. Mutation raisesValueError; usecopy_closure()for a mutable in-memory merge.As a closure view (vs
get_union()), this returns the same triple set ascopy_closure()— a single flattened, de-duplicated graph. The persistent rdf5d path applies these transforms lazily over the mmap scan:resolved
owl:imports(targets inside the closure) are stripped,ontology declarations are collapsed onto the root (and the root is declared
a owl:Ontologyif it did not declare itself),SHACL
sh:prefixes/sh:declareare consolidated onto the root.
Set
remove_owl_imports=Falseto keep resolvedowl:imports, orrewrite_sh_prefixes=Falseto leave SHACL prefixes untouched (ontology declarations are still collapsed onto the root).
- get_dataset()¶
Return a read-only store-backed Dataset view of the environment.
- get_dependencies(graph, graph_name=None, recursion_depth=Ellipsis, fetch_missing=False)¶
Get the dependency closure of a given graph and return it as a new graph.
This method will look for owl:imports statements in the provided graph, then find those ontologies within the OntoEnv and compute the full dependency closure. The triples of all ontologies in the closure are returned as a new graph. The original graph is never modified.
- Parameters:
graph (rdflib.Graph) – The graph to find dependencies for.
graph_name (Optional[str]) – If provided, all
owl:Ontologydeclarations from the closure are replaced with a single one for this URI andsh:prefixesare rewritten to point at it. IfNone(default), each ontology in the closure retains its ownowl:Ontologydeclaration (a proper union of the closure graphs);sh:prefixesare left distributed and no root is imposed.recursion_depth (int) – The maximum depth for recursive import resolution. A negative value (default) means no limit.
fetch_missing (bool) – If True, fetch ontologies that are not in the environment. In non-strict mode unavailable targets are recorded and skipped without leaving a recovery marker; strict mode returns an error.
- Returns:
A tuple containing the populated dependency graph and the sorted list of imported ontology IRIs.
- Return type:
tuple[rdflib.Graph, list[str]]
- get_graph(uri)¶
Get a read-only store-backed view of the named graph as an
rdflib.Graph. Mutation raisesValueError; usecopy_graph()for a mutable in-memory copy.
- get_importers(uri)¶
Get the names of all ontologies that import the given ontology
- get_namespaces(ontology=None, include_closure=False)¶
Get namespace prefix mappings.
Prefixes are extracted from both parser-level declarations (
@prefixin Turtle,PREFIXin SPARQL-style syntaxes, XML namespace declarations) and SHACLsh:declareentries. SHACL entries take precedence when the same prefix appears in both sources.- Parameters:
ontology – The IRI of the ontology to query. If
None, returns merged namespaces from every ontology in the environment.include_closure – When
True, namespaces from the full transitiveowl:importsclosure of the ontology are included. Ignored whenontologyisNone.
- Returns:
A
dict[str, str]mapping prefix names (e.g."owl") to namespace IRIs (e.g."http://www.w3.org/2002/07/owl#").
- get_ontology(uri)¶
Get the ontology metadata with the given URI
- get_ontology_names()¶
Get the names of all ontologies in the OntoEnv
- get_union(uris, include_closures=False, recursion_depth=Ellipsis)¶
Return a read-only merged view over an explicitly listed set of ontology graphs, plus the list of ontology IRIs that contribute to the view (in the order they were resolved).
The returned object is a
ontoenv.ViewGraph— a lightweight, non-rdflib.Graphview that delegates triple-pattern lookups to the Rust backend scoped to the listed named graphs, so it behaves like a merged graph without materializing one. Mutation raisesValueError; usecopy_union()for a mutable in-memory merge.This is a raw merge: no closure transform is applied and triples are not de-duplicated across the named graphs (rdflib merged-graph semantics). For the cleaned, flattened imports closure of a single ontology, use
get_closure()instead.Set
include_closures=Trueto expand each listed graph’s transitiveowl:importsclosure into the view. This is the read-only equivalent ofcopy_union().
- import_dependencies(graph, recursion_depth=Ellipsis, fetch_missing=False)¶
Import the dependencies referenced by owl:imports triples in graph.
When fetch_missing is true, the environment attempts to download unresolved imports before computing the closure. In non-strict mode, unavailable imports are recorded and skipped, and the completed best-effort operation does not leave a recovery marker. In strict mode, an unavailable import aborts the operation. If at least one dependency resolves, its closure is merged into graph and all owl:imports statements are removed; if none resolve, graph is unchanged. The returned list contains the deduplicated ontology IRIs that were successfully imported.
- import_graph(destination_graph, uri, recursion_depth=Ellipsis)¶
- is_offline()¶
- is_strict()¶
- iter_closure_triples(uri, recursion_depth=Ellipsis)¶
Stream
(s, p, o)triples across the transitiveowl:importsclosure of uri. Triples are not de-duplicated across named graphs; wrap inset()if you need set semantics.
- iter_triples(uri)¶
Stream
(s, p, o)triples for one named graph as rdflib terms, skipping the rdflibGraphwrapper entirely.Triples are read from the env once at call time; the iterator yields lazily after that. Use this when you only need to scan and don’t want to pay for hash-set insertion into an rdflib graph.
- list_closure(uri, recursion_depth=Ellipsis)¶
List the ontologies in the imports closure of the given ontology.
urimay be either:a string IRI of an ontology already in the environment, or
an
rdflib.Graphthat has not yet been added to the environment. In that case the closure is computed from the graph’sowl:importsdeclarations without modifying the environment.
- missing_imports(uri=None)¶
Return IRIs of imports that cannot be resolved in the environment.
urimay be:None— scans every ontology and includes currently recorded best-effort fetch failures for transient caller graphs (de-duplicated).a string IRI of an ontology already in the environment — walks its full transitive closure and returns every unresolvable import IRI.
an
rdflib.Graphnot yet in the environment — extracts its directowl:imports, then for each import that is in the environment walks that import’s closure. Imports absent from the environment are themselves reported as missing.
- open(graph_store=None, read_only=False, **options)¶
Open an existing environment without synchronizing its graph store.
Omitted configuration preserves persisted settings. Explicit values override them; writable opens persist overrides and read-only opens keep them session-local.
- recover(graph_store=None, **options)¶
Rebuild a catalog after an interrupted mutation.
The attached graph store is authoritative. The recovery marker is removed only after every graph has been scanned and the new catalog has been published successfully.
- refresh_dataset(dataset)¶
Refresh an existing read-only Dataset view from the current env.
- refresh_from_store(graphs=None, full=False)¶
Reconcile catalog metadata with the attached graph store.
- remote_cache_ttl_secs()¶
- remove_alias(alias_iri)¶
Remove an alias.
- Parameters:
alias_iri – The alias IRI to remove
- rename_graph_iri(uri, new_iri)¶
Rename the IRI of an ontology already in the environment.
Reads the stored graph for
uri, rewrites every occurrence of its current IRI tonew_iri(subject and object positions, excludingowl:versionIRIvalues), stores the result under the new name, removes the old named graph, and rebuilds the import dependency graph.Returns the new IRI string.
- requires_ontology_names()¶
- resolution_policy()¶
- resolve_alias(alias_iri)¶
Get the canonical IRI for an alias.
- Parameters:
alias_iri – The alias IRI to resolve
- Returns:
The canonical IRI if the input is an alias, or None if it’s not an alias
- set_offline(offline)¶
- set_remote_cache_ttl_secs(ttl_secs)¶
- set_require_ontology_names(require)¶
- set_resolution_policy(policy)¶
- set_strict(strict)¶
- set_use_cached_ontologies(enabled)¶
- snapshot_as_dataset(backend='auto', store=None)¶
Deprecated alias for
get_dataset()/copy_dataset().
- store_path()¶
- temporary_snapshot()¶
Return an isolated in-memory copy of this environment.
The catalog metadata and every graph are copied at the time of this call. Changes to either environment afterwards are independent, and the returned environment never writes a
.ontoenvdirectory.
- to_rdflib_dataset(mode='auto')¶
Deprecated alias for
get_dataset()/copy_dataset().
- update(location=None, *, force=False, all=None)¶
Refresh known ontology sources, or one explicit source and its imports.
A provided source replaces its existing stored graph automatically. force=true bypasses timestamp and cache-age checks. all is retained as a deprecated compatibility alias for force.
- uses_cached_ontologies()¶
- class ontoenv.OntoEnvStore(*args, **kwargs)[source]¶
Bases:
StoreA read-only rdflib
Storebacked by an OntoEnv snapshot.SPARQL queries are executed by the Rust backend rather than rdflib’s Python query engine. Writes (
add,addN,remove) raiseValueError— snapshots are immutable; mutate the underlyingontoenv.OntoEnvand callrefresh_dataset_from_env()instead.Construct via
from_env()or, more commonly, viaenv.get_dataset(). Creating anOntoEnvStore()directly yields an empty store, which is mostly useful as the rdflib pluginGraph(store='ontoenv').- Parameters:
configuration (str | None)
identifier (Identifier | None)
- add(triple, context, quoted=False)[source]¶
- Parameters:
triple (tuple[rdflib.term.Identifier, rdflib.term.Identifier, rdflib.term.Identifier])
context (Any)
quoted (bool)
- Return type:
None
- addN(quads)[source]¶
- Parameters:
quads (Iterable[tuple[rdflib.term.Identifier, rdflib.term.Identifier, rdflib.term.Identifier, Any]])
- Return type:
None
- bind(prefix, namespace, override=True)[source]¶
- Parameters:
prefix (str)
namespace (rdflib.URIRef)
override (bool)
- Return type:
None
- close(commit_pending_transaction=False)[source]¶
- Parameters:
commit_pending_transaction (bool)
- Return type:
None
- contexts(triple=None)[source]¶
- Parameters:
triple (tuple[rdflib.term.Identifier, rdflib.term.Identifier, rdflib.term.Identifier] | None)
- Return type:
- classmethod from_env(env, mode='auto')[source]¶
Build a new
OntoEnvStoreand bind it to a snapshot ofenv.- Parameters:
- Return type:
- prefix(namespace)[source]¶
- Parameters:
namespace (rdflib.URIRef)
- Return type:
str | None
- refresh_from_env(env, mode=None)[source]¶
Rebind this store to a fresh snapshot of
env.If
modeis omitted, the previously chosen backend is reused (or"auto"on first call). Namespace bindings are cleared and re-populated fromenv.get_namespaces().
- remove(triple_pattern, context=None)[source]¶
- Parameters:
triple_pattern (tuple[Identifier | None, Identifier | None, Identifier | None])
context (Any | None)
- Return type:
None
- class ontoenv.Ontology¶
Bases:
object- id¶
- imports¶
- last_updated¶
- location¶
- name¶
- namespace_map¶
- version_properties¶
- exception ontoenv.StoreCapabilityError¶
Bases:
RuntimeError- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- exception ontoenv.UnresolvedImportError¶
Bases:
LookupErrorA known owl:imports target could not be resolved or loaded.
- add_note()¶
Exception.add_note(note) – add a note to the exception
- args¶
- with_traceback()¶
Exception.with_traceback(tb) – set self.__traceback__ to tb and return self.
- class ontoenv.ViewGraph(backend, scope=None, namespaces=None)[source]¶
Bases:
objectRead-only, zero-copy view over a set of the snapshot’s named graphs.
Unlike
rdflib.Graph, this class does not inherit fromrdflib.Graph. It delegates triple lookups,__len__,__contains__and SPARQL directly to the Rust backend, reading straight from the rdf5d mmap snapshot without materializing a copy.Two flavours, distinguished by how the backend is configured:
ontoenv.OntoEnv.get_closure()returns a view whose backend carries a closure patch. It presents a single flattened, de-duplicated graph with the same triple set asontoenv.OntoEnv.copy_closure()(resolvedowl:importsstripped, ontology declarations collapsed onto the root, SHACLsh:prefixes/sh:declareconsolidated). Cross-graph duplicate triples collapse, and SPARQL sees one graph.ontoenv.OntoEnv.get_union()returns a raw merge: every triple of each named graph in scope, with no transform and no cross-graph de-duplication (rdflib merged-graph semantics).
Construct via
env.get_closure(uri)orenv.get_union(uris)rather than directly.env.get_graph(uri)still returns a plainrdflib.Graph.- Parameters:
backend (Any) – A
ontoenv._native._RdfLibStoreBackendinstance bound to an env snapshot. For a closure view this is a dedicated backend sharing the same mmap snapshot with a closure patch attached; for a union view it is the shared (raw) backend.scope (tuple[str, ...] | None) – Tuple of graph IRIs to scope against, or
Nonefor all graphs in the backend.namespaces (dict[str, str] | None) – Optional dict of
{prefix: namespace}bindings.
- add(triple)[source]¶
ViewGraph is read-only; mutate the
ontoenv.OntoEnvinstead.
- addN(quads)[source]¶
ViewGraph is read-only; mutate the
ontoenv.OntoEnvinstead.
- remove(triple)[source]¶
ViewGraph is read-only; mutate the
ontoenv.OntoEnvinstead.
- serialize(destination=None, format='turtle', **kwargs)[source]¶
Serialize triples in this view, matching rdflib’s Graph.serialize signature.
- ontoenv.is_debug_build()¶
Whether the native extension was compiled in debug mode (unoptimized).
Benchmarking or perf-sensitive use against a debug build is misleading: the per-triple Rust callbacks (__next__, term decoding) run 5-10x slower than release, so backends that cross the FFI boundary per triple (e.g. ontoenv-get’s ViewGraph) appear massively regressed relative to pure-Python backends (ontoenv-copy, rdflib-memory) that are unaffected by the Rust build profile.
- ontoenv.run_cli(args)¶
Run the Rust CLI implementation and return its process-style exit code.