Details¶
Py-Horned-OWL provides Python bindings via PyO3. This bridge presents some challenges.
The model classes¶
Each class of pyhornedowl.model is a plain Rust struct in src/model/ with a #[model] attribute, which generates the Python class, its conversions from and to the Horned-OWL type and the methods every class has (__repr__, __match_args__, pickling, copy.replace, …):
#[model(variant_of = ClassExpression)]
pub struct ObjectSomeValuesFrom {
#[model(horned = ope)]
pub object_property_expression: ObjectPropertyExpression,
#[model(horned = bce)]
pub class_expression: BoxWrap<ClassExpression>,
}
#[model(horned = ...)] maps a field to the Horned-OWL field it wraps, so the Python names can be descriptive. The classes are frozen: they compare, hash and order by value.
A Horned-OWL enum whose variants are classes of their own, such as ClassExpression, has an enum with #[model_enum]. It generates an abstract Python base class of the same name, which the variants extend, so isinstance(ObjectUnionOf([]), ClassExpression) holds. PyO3 classes have a single base class, so a class belonging to two such enums is not possible; the enums that are neither (AnnotationValue, PropertyExpression, …) are #[model_union] enums, which are unions of their members in Python, defined in python/pyhornedowl/model.py.
Methods beyond the generated ones are ordinary #[pymethods] blocks next to the struct (for example ClassExpression’s &, | and ~). Other Python values a class converts from are given with coerce: a str names an entity, and str, bool, int and float are literals. lib/macros/src/lib.rs documents all options.
Python documentation¶
Unfortunately, the documentation of rust datatypes vanishes at compile time. Therefore, we cannot simply copy the documentation of Horned-OWL data types to the wrapped data types. But a helper script extracts the doc strings from Horned-OWL and provides them in a form of a macro. Additionally, Py-Horned-OWL datatypes and functions follow the convention to include their signature as the first line of their documentation.
Python stubs / type hints¶
The type stubs are generated by PyO3 itself with its experimental-inspect feature. maturin build --generate-stubs (or maturin develop --generate-stubs) with Maturin 1.15 or newer generates .pyi files next to the native module in python/pyhornedowl/pyhornedowl.
PyO3 cannot express type aliases, so the unions such as AnnotationValue are defined in Python, in python/pyhornedowl/model.py.