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: RuntimeError

The 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: object

A 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. Call update() when configured ontology files or URLs should be discovered or refreshed. Use OntoEnv(temporary=True) for unsaved in-memory work.

OntoEnv.create, open, adopt, and recover provide narrower lifecycle contracts. The direct constructor’s recreate=True option deletes and rebuilds the target .ontoenv directory; it is not equivalent to connect.

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 as env.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’s get_graph rather 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.Dataset is created.

Works correctly with custom graph_store= backends: every named graph is materialised via the backend’s get_graph path 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.Graph is created.

Works correctly with custom graph_store= backends: triples are fetched via the backend’s get_graph method rather than the internal oxigraph store, so the returned graph always reflects what the Python store holds.

Raises UnresolvedImportError when uri is a currently known unresolved import. An arbitrary unknown graph IRI raises ValueError; 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=True to include each listed graph’s transitive owl:imports closure. The root IRI 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 — matching get_union(). Pass remove_owl_imports=True / rewrite_sh_prefixes=True to 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’s copy_graph when available, otherwise get_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:imports closure 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.Graph view 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 raises ValueError; use copy_closure() for a mutable in-memory merge.

As a closure view (vs get_union()), this returns the same triple set as copy_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:Ontology if it did not declare itself),

  • SHACL sh:prefixes / sh:declare are consolidated onto the root.

Set remove_owl_imports=False to keep resolved owl:imports, or rewrite_sh_prefixes=False to 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:Ontology declarations from the closure are replaced with a single one for this URI and sh:prefixes are rewritten to point at it. If None (default), each ontology in the closure retains its own owl:Ontology declaration (a proper union of the closure graphs); sh:prefixes are 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 raises ValueError; use copy_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 (@prefix in Turtle, PREFIX in SPARQL-style syntaxes, XML namespace declarations) and SHACL sh:declare entries. 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 transitive owl:imports closure of the ontology are included. Ignored when ontology is None.

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.Graph view 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 raises ValueError; use copy_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=True to expand each listed graph’s transitive owl:imports closure into the view. This is the read-only equivalent of copy_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 transitive owl:imports closure of uri. Triples are not de-duplicated across named graphs; wrap in set() if you need set semantics.

iter_triples(uri)

Stream (s, p, o) triples for one named graph as rdflib terms, skipping the rdflib Graph wrapper 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.

uri may be either:

  • a string IRI of an ontology already in the environment, or

  • an rdflib.Graph that has not yet been added to the environment. In that case the closure is computed from the graph’s owl:imports declarations without modifying the environment.

missing_imports(uri=None)

Return IRIs of imports that cannot be resolved in the environment.

uri may 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.Graph not yet in the environment — extracts its direct owl: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 to new_iri (subject and object positions, excluding owl:versionIRI values), 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 .ontoenv directory.

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: Store

A read-only rdflib Store backed by an OntoEnv snapshot.

SPARQL queries are executed by the Rust backend rather than rdflib’s Python query engine. Writes (add, addN, remove) raise ValueError — snapshots are immutable; mutate the underlying ontoenv.OntoEnv and call refresh_dataset_from_env() instead.

Construct via from_env() or, more commonly, via env.get_dataset(). Creating an OntoEnvStore() directly yields an empty store, which is mostly useful as the rdflib plugin Graph(store='ontoenv').

Parameters:
  • configuration (str | None)

  • identifier (Identifier | None)

add(triple, context, quoted=False)[source]
Parameters:
Return type:

None

addN(quads)[source]
Parameters:

quads (Iterable[tuple[rdflib.term.Identifier, rdflib.term.Identifier, rdflib.term.Identifier, Any]])

Return type:

None

add_graph(graph)[source]
Parameters:

graph (Any)

Return type:

None

bind(prefix, namespace, override=True)[source]
Parameters:
Return type:

None

close(commit_pending_transaction=False)[source]
Parameters:

commit_pending_transaction (bool)

Return type:

None

commit()[source]
Return type:

None

context_aware: bool = True
contexts(triple=None)[source]
Parameters:

triple (tuple[rdflib.term.Identifier, rdflib.term.Identifier, rdflib.term.Identifier] | None)

Return type:

Generator[Any | None, None, None]

destroy(configuration)[source]
Parameters:

configuration (str)

Return type:

None

formula_aware: bool = False
classmethod from_env(env, mode='auto')[source]

Build a new OntoEnvStore and bind it to a snapshot of env.

Parameters:
  • env (Any)

  • mode (Literal['auto', 'rdf5d', 'copy'])

Return type:

OntoEnvStore

graph_aware: bool = True
namespace(prefix)[source]
Parameters:

prefix (str)

Return type:

URIRef | None

namespaces()[source]
Return type:

Iterable[tuple[str, rdflib.URIRef]]

open(configuration, create=False)[source]
Parameters:
  • configuration (str | None)

  • create (bool)

Return type:

int

prefix(namespace)[source]
Parameters:

namespace (rdflib.URIRef)

Return type:

str | None

query(query, initNs, initBindings, queryGraph, **kwargs)[source]
Parameters:
Return type:

rdflib.query.Result

refresh_from_env(env, mode=None)[source]

Rebind this store to a fresh snapshot of env.

If mode is omitted, the previously chosen backend is reused (or "auto" on first call). Namespace bindings are cleared and re-populated from env.get_namespaces().

Parameters:
  • env (Any)

  • mode (Literal['auto', 'rdf5d', 'copy'] | None)

Return type:

None

remove(triple_pattern, context=None)[source]
Parameters:
  • triple_pattern (tuple[Identifier | None, Identifier | None, Identifier | None])

  • context (Any | None)

Return type:

None

remove_graph(graph)[source]
Parameters:

graph (Any)

Return type:

None

rollback()[source]
Return type:

None

transaction_aware: bool = False
triples(triple_pattern, context=None)[source]
Parameters:
  • triple_pattern (tuple[Identifier | None, Identifier | None, Identifier | None])

  • context (Any | None)

Return type:

Generator[tuple[tuple[Identifier, Identifier, Identifier], Generator[Any | None, None, None]], None, None]

update(update, initNs, initBindings, queryGraph, **kwargs)[source]
Parameters:
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.

class ontoenv.SyncReport

Bases: object

added
changed
mode
removed
still_pending
unchanged
exception ontoenv.UnresolvedImportError

Bases: LookupError

A 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: object

Read-only, zero-copy view over a set of the snapshot’s named graphs.

Unlike rdflib.Graph, this class does not inherit from rdflib.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 as ontoenv.OntoEnv.copy_closure() (resolved owl:imports stripped, ontology declarations collapsed onto the root, SHACL sh:prefixes/sh:declare consolidated). 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) or env.get_union(uris) rather than directly. env.get_graph(uri) still returns a plain rdflib.Graph.

Parameters:
  • backend (Any) – A ontoenv._native._RdfLibStoreBackend instance 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 None for 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.OntoEnv instead.

Parameters:

triple (tuple[Any, Any, Any])

Return type:

None

addN(quads)[source]

ViewGraph is read-only; mutate the ontoenv.OntoEnv instead.

Parameters:

quads (Iterable[tuple[Any, Any, Any, Any]])

Return type:

None

bind(prefix, namespace, override=True)[source]

Bind a prefix to a namespace.

Parameters:
Return type:

None

namespace(prefix)[source]

Resolve a prefix to a namespace IRI.

Parameters:

prefix (str)

Return type:

str | None

property namespaces: dict[str, str]

{prefix: namespace} bindings.

objects(subject=None, predicate=None)[source]

Yield unique objects matching the pattern.

Parameters:
  • subject (Any)

  • predicate (Any)

Return type:

Generator[Any, None, None]

predicates(subject=None, object=None)[source]

Yield unique predicates matching the pattern.

Parameters:
Return type:

Generator[Any, None, None]

prefix(namespace)[source]

Resolve a namespace IRI to a prefix.

Parameters:

namespace (str)

Return type:

str | None

query(query_text, init_bindings=None)[source]

Run a SPARQL query scoped to this view’s graphs.

Parameters:
Return type:

Any

remove(triple)[source]

ViewGraph is read-only; mutate the ontoenv.OntoEnv instead.

Parameters:

triple (tuple[Any, Any, Any])

Return type:

None

serialize(destination=None, format='turtle', **kwargs)[source]

Serialize triples in this view, matching rdflib’s Graph.serialize signature.

Parameters:
  • destination (Any | None)

  • format (str)

  • kwargs (Any)

Return type:

bytes | str

subjects(predicate=None, object=None)[source]

Yield unique subjects matching the pattern.

Parameters:
  • predicate (Any)

  • object (Any)

Return type:

Generator[Any, None, None]

triples(subject=None, predicate=None, obj=None)[source]

Iterate (s, p, o) triples matching the pattern.

Accepts both the rdflib convention triples((s, p, o)) (a single 3-tuple) and the three-arg form triples(s, p, o). Any term may be None (unbound).

Parameters:
Return type:

Generator[tuple[Any, Any, Any], None, None]

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.