Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 4 additions & 3 deletions CONTEXT.md
Original file line number Diff line number Diff line change
Expand Up @@ -305,9 +305,9 @@ from rdflib import URIRef


class PersonBinding(BindingModel):
person: Uri # maps to/from URIRef, serialized as <...>
name: Literal[str] # maps to/from Python str, serialized as "..."^^xsd:string
age: Literal[int] # maps to/from Python int, serialized as "..."^^xsd:integer
person: Uri = None # URIRef, serialized as <...>
name: Literal[str] = None # Python str, serialized as "..."^^xsd:string
age: Literal[int] = None # Python int, serialized as "..."^^xsd:integer
```

- **`Uri`**: Accepts `URIRef` or N3-encoded string (`<...>`), serializes to N3 `<...>`.
Expand All @@ -316,6 +316,7 @@ class PersonBinding(BindingModel):
- **`RdfLiteral`**: Keeps the `rdflib.Literal` as-is (no conversion to Python), preserving lexical form, datatype and language tag. Accepts only `rdflib.Literal` or N3 literal strings.
- Values are validated on construction **and** on attribute assignment (`validate_assignment=True`), so e.g. assigning an ISO string to a `Literal[datetime]` field coerces it to `datetime` and serializes with `^^xsd:dateTime`.
- All fields default to `None` — use `dump_result_binding()` to validate all fields are set before returning, or `dump_partial_binding()` for partial/query bindings.
- The `None` default lives in `Field(default=None)` inside each `Annotated` alias. Pyright ignores defaults declared there (it only recognises assigned defaults), so binding model fields are written with an explicit `= None` (issue #77). A custom `__init__` or `dataclass_transform` metaclass on `BindingModel` does not help: pyright still synthesizes `__init__` per subclass from assigned defaults only.
- **`UNDEFINED` / `UNDEFINED_LITERAL`** (issue #75): The KE has no optional values, so every variable must be bound. Both sentinels serialize as `<http://www.knowledge-engine.eu/mapper/undefined>`; incoming bindings with that URI deserialize to the sentinel matching the field type (test with `is`), never to `None`.
- `UNDEFINED = URIRef(...)` is for `Uri` fields.
- `UNDEFINED_LITERAL` (single member of enum `UndefinedLiteral`) is for `Literal[T]`, `RdfLiteral` and `Datatype` fields. It is an enum member rather than a `URIRef` so pyright accepts it in literal fields (their hint is `T | UndefinedLiteral | None`) and narrows it away with `is not UNDEFINED_LITERAL`. A wrap validator short-circuits it before the field's own validation; the enum branch is `Strict()` so the bare URI string is not coerced into the sentinel.
Expand Down
15 changes: 10 additions & 5 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -184,11 +184,13 @@ from knowledge_mapper import BindingModel, Uri, Literal


class PersonBinding(BindingModel):
person: Uri # URIRef, serialized as <...>
name: Literal[str] # Python str, serialized as "..."^^xsd:string
age: Literal[int] # Python int, serialized as "..."^^xsd:integer
person: Uri = None # URIRef, serialized as <...>
name: Literal[str] = None # Python str, serialized as "..."^^xsd:string
age: Literal[int] = None # Python int, serialized as "..."^^xsd:integer
```

All fields default to `None`, so partial bindings such as `PersonBinding(person=...)` (e.g. for ASK queries) work at runtime. Write `= None` explicitly anyway: static type checkers such as pyright do not see defaults declared inside `Annotated`, and would otherwise report every field as a required argument.

Use `BindingModel` for type safety and automatic serialization. Use raw `BindingSet` (`Sequence[dict[str, str]]`) for passthrough data.

`Literal[T]` infers an XSD datatype from the Python value. For custom (non-XSD) datatypes:
Expand All @@ -198,11 +200,14 @@ from typing import Annotated
from knowledge_mapper import BindingModel, Datatype, Literal, RdfLiteral


CELSIUS = "http://example.org/celsius"


class ObservationBinding(BindingModel):
# Python float, serialized as "..."^^ex:celsius; other incoming datatypes are rejected
temperature: Annotated[Literal[float], Datatype("http://example.org/celsius")]
temperature: Annotated[Literal[float], Datatype(CELSIUS)] = None
# rdflib.Literal kept as-is; any datatype or language tag is preserved
remark: RdfLiteral
remark: RdfLiteral = None
```

The Knowledge Engine requires every variable in a binding to have a value. When there is none, assign a sentinel instead of `None`: `UNDEFINED` for `Uri` fields, `UNDEFINED_LITERAL` for `Literal[T]`, `RdfLiteral` and `Datatype` fields. Both are sent as `<http://www.knowledge-engine.eu/mapper/undefined>`, and incoming bindings with this URI deserialize back to the sentinel matching the field type. Pyright narrows the field type after an `is not UNDEFINED_LITERAL` check:
Expand Down
11 changes: 7 additions & 4 deletions examples/02-binding_models.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,11 +31,14 @@


# Define strongly-typed bindings for variables in the graph pattern.
# Fields already default to None at runtime; the explicit `= None` lets type
# checkers such as pyright accept partial bindings like
# `CurrentTemperatureBinding(measurement=...)`.
class CurrentTemperatureBinding(BindingModel):
measurement: Uri
value: Literal[float]
unit: Uri
time: Literal[datetime]
measurement: Uri = None
value: Literal[float] = None
unit: Uri = None
time: Literal[datetime] = None


@kb.answer_ki(
Expand Down
6 changes: 3 additions & 3 deletions examples/03-ask_interaction.py
Original file line number Diff line number Diff line change
Expand Up @@ -28,9 +28,9 @@

# Binding model for variables used in the ASK graph pattern.
class PersonBinding(BindingModel):
person: Uri
name: Literal[str]
age: Literal[int]
person: Uri = None
name: Literal[str] = None
age: Literal[int] = None


# Register an ASK KI that can be called via kb.ask(...).
Expand Down
12 changes: 6 additions & 6 deletions examples/04-post_measurement.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,16 +27,16 @@

# Argument bindings for the POST interaction input pattern.
class MeasurementBinding(BindingModel):
measurement: Uri
value: Literal[float]
unit: Uri
time: Literal[datetime]
measurement: Uri = None
value: Literal[float] = None
unit: Uri = None
time: Literal[datetime] = None


# Result bindings for the POST interaction result pattern.
class ResultBinding(BindingModel):
measurement: Uri
kb: Uri
measurement: Uri = None
kb: Uri = None


# Register a POST KI with separate argument and result graph patterns.
Expand Down
4 changes: 2 additions & 2 deletions examples/06-dependency_injection.py
Original file line number Diff line number Diff line change
Expand Up @@ -113,8 +113,8 @@ def get_sensor_repository(


class SensorReadingBinding(BindingModel):
sensor: Uri
temperature: Literal[float]
sensor: Uri = None
temperature: Literal[float] = None


# ---------------------------------------------------------------------------
Expand Down
8 changes: 4 additions & 4 deletions examples/07-testing/kb.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,8 +31,8 @@


class ExampleBinding(BindingModel):
s: Uri
value: Literal[str]
s: Uri = None
value: Literal[str] = None


kb.ask_ki(
Expand Down Expand Up @@ -65,8 +65,8 @@ async def ask_for_values_of_subject(subject_name: str) -> list[str]:


class ResultBinding(BindingModel):
s: Uri
other: Uri
s: Uri = None
other: Uri = None


kb.post_ki(
Expand Down
10 changes: 5 additions & 5 deletions examples/08-async_handlers.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,14 +27,14 @@


class DeviceCommandBinding(BindingModel):
device: Uri
desired_state: Literal[str]
device: Uri = None
desired_state: Literal[str] = None


class DeviceAckBinding(BindingModel):
device: Uri
accepted: Literal[bool]
source: Literal[str]
device: Uri = None
accepted: Literal[bool] = None
source: Literal[str] = None


kb = KnowledgeBase(
Expand Down
8 changes: 4 additions & 4 deletions examples/11-custom_datatypes.py
Original file line number Diff line number Diff line change
Expand Up @@ -39,13 +39,13 @@


class ObservationBinding(BindingModel):
observation: Uri
timestamp: Literal[datetime]
observation: Uri = None
timestamp: Literal[datetime] = None
# Python float in code, serialized as "..."^^ex:celsius. Incoming literals
# with any other datatype are rejected.
temperature: Annotated[Literal[float], Datatype(EX.celsius)]
temperature: Annotated[Literal[float], Datatype(EX.celsius)] = None
# Raw rdflib Literal: any datatype or language tag is passed through.
remark: RdfLiteral
remark: RdfLiteral = None


@kb.answer_ki(
Expand Down
8 changes: 4 additions & 4 deletions examples/13-undefined_values.py
Original file line number Diff line number Diff line change
Expand Up @@ -40,10 +40,10 @@


class PersonBinding(BindingModel):
person: Uri
name: Literal[str]
age: Literal[int]
employer: Uri
person: Uri = None
name: Literal[str] = None
age: Literal[int] = None
employer: Uri = None


# Ages and employers are not known for everyone.
Expand Down
88 changes: 59 additions & 29 deletions tests/test_bindings.py
Original file line number Diff line number Diff line change
Expand Up @@ -68,9 +68,9 @@ def test_serialize_literal():

def test_serialize_binding():
class TestBinding(BindingModel):
sensor: Uri
year_of_manufacture: Literal[int]
manufacturer_name: Literal[str]
sensor: Uri = None
year_of_manufacture: Literal[int] = None
manufacturer_name: Literal[str] = None

binding = TestBinding(
sensor=URIRef("http://example.org/test#sensor"),
Expand All @@ -87,9 +87,9 @@ class TestBinding(BindingModel):

def test_validate_binding():
class TestBinding(BindingModel):
sensor: Uri
year_of_manufacture: Literal[int]
manufacturer_name: Literal[str]
sensor: Uri = None
year_of_manufacture: Literal[int] = None
manufacturer_name: Literal[str] = None

binding = TestBinding.model_validate(
{
Expand All @@ -106,7 +106,7 @@ class TestBinding(BindingModel):

def test_assigned_datetime_string_dumps_with_datetime_datatype():
class TestBinding(BindingModel):
timestamp: Literal[datetime]
timestamp: Literal[datetime] = None

binding = TestBinding()
binding.timestamp = "2026-07-14T20:30:00+0200"
Expand All @@ -119,7 +119,7 @@ class TestBinding(BindingModel):

def test_assigned_datetime_dumps_with_datetime_datatype():
class TestBinding(BindingModel):
timestamp: Literal[datetime]
timestamp: Literal[datetime] = None

binding = TestBinding()
binding.timestamp = datetime.fromisoformat("2026-07-14T20:30:00+02:00")
Expand All @@ -132,7 +132,7 @@ class TestBinding(BindingModel):

def test_assigning_invalid_value_to_typed_literal_raises():
class TestBinding(BindingModel):
timestamp: Literal[datetime]
timestamp: Literal[datetime] = None

binding = TestBinding()

Expand All @@ -144,7 +144,7 @@ class TestBinding(BindingModel):


class RdfLiteralBinding(BindingModel):
value: RdfLiteral
value: RdfLiteral = None


@pytest.mark.parametrize(
Expand Down Expand Up @@ -204,7 +204,7 @@ def test_rdf_literal_rejects_non_literals(value):

def test_plain_literal_still_coerces_custom_datatype():
class FloatBinding(BindingModel):
value: Literal[float]
value: Literal[float] = None

binding = FloatBinding.model_validate(
{"value": '"12.5"^^<http://example.org/units#celsius>'}
Expand All @@ -217,7 +217,7 @@ class FloatBinding(BindingModel):


class CelsiusBinding(BindingModel):
temperature: Annotated[Literal[float], Datatype(CELSIUS)]
temperature: Annotated[Literal[float], Datatype(CELSIUS)] = None


def test_datatype_validates_custom_literal():
Expand Down Expand Up @@ -268,8 +268,8 @@ def test_datatype_with_str_and_datetime():
code_type = URIRef("http://example.org/types#code")

class Binding(BindingModel):
timestamp: Annotated[Literal[datetime], Datatype(timestamp_type)]
code: Annotated[Literal[str], Datatype(code_type)]
timestamp: Annotated[Literal[datetime], Datatype(timestamp_type)] = None
code: Annotated[Literal[str], Datatype(code_type)] = None

n3 = {
"timestamp": '"2020-01-02T03:04:05"^^<http://example.org/types#timestamp>',
Expand All @@ -284,7 +284,7 @@ class Binding(BindingModel):

def test_datatype_accepts_string_iri():
class Binding(BindingModel):
temperature: Annotated[Literal[float], Datatype(str(CELSIUS))]
temperature: Annotated[Literal[float], Datatype(str(CELSIUS))] = None

assert Binding(temperature=1.5).dump_result_binding() == {
"temperature": '"1.5"^^<http://example.org/units#celsius>'
Expand All @@ -293,8 +293,8 @@ class Binding(BindingModel):

def test_datatype_and_rdf_literal_validate_on_assignment():
class Binding(BindingModel):
temperature: Annotated[Literal[float], Datatype(CELSIUS)]
remark: RdfLiteral
temperature: Annotated[Literal[float], Datatype(CELSIUS)] = None
remark: RdfLiteral = None

binding = Binding()
binding.temperature = '"12.5"^^<http://example.org/units#celsius>'
Expand All @@ -310,12 +310,12 @@ class Binding(BindingModel):


class MatchBinding(BindingModel):
person: Uri
age: Literal[int]
name: Literal[str]
born: Literal[datetime]
remark: RdfLiteral
temperature: Annotated[Literal[float], Datatype(CELSIUS)]
person: Uri = None
age: Literal[int] = None
name: Literal[str] = None
born: Literal[datetime] = None
remark: RdfLiteral = None
temperature: Annotated[Literal[float], Datatype(CELSIUS)] = None


FULL_MATCH_BINDING = MatchBinding(
Expand Down Expand Up @@ -374,18 +374,48 @@ def test_matches_with_binding_for_all_field_types():
assert not FULL_MATCH_BINDING.matches_with_binding(other)


# ---------- Explicit None defaults


def test_explicit_none_defaults_behave_like_implicit_ones():
"""`= None` is the recommended pattern for type checkers (issue #77)."""

class Binding(BindingModel):
person: Uri = None
age: Literal[int] = None
remark: RdfLiteral = None
temperature: Annotated[Literal[float], Datatype(CELSIUS)] = None

partial = Binding(person=URIRef("http://example.org/a"))
validated = Binding.model_validate(
{
"age": '"3"^^<http://www.w3.org/2001/XMLSchema#integer>',
"remark": '"foo"@de',
"temperature": '"12.5"^^<http://example.org/units#celsius>',
}
)

assert partial.dump_partial_binding() == {"person": "<http://example.org/a>"}
assert validated.age == 3
assert validated.dump_partial_binding() == {
"age": '"3"^^<http://www.w3.org/2001/XMLSchema#integer>',
"remark": '"foo"@de',
"temperature": '"12.5"^^<http://example.org/units#celsius>',
}


# ---------- UNDEFINED sentinels

UNDEFINED_N3 = "<http://www.knowledge-engine.eu/mapper/undefined>"


class OptionalValuesBinding(BindingModel):
uri: Uri
count: Literal[int]
name: Literal[str]
timestamp: Literal[datetime]
temperature: Annotated[Literal[float], Datatype(CELSIUS)]
remark: RdfLiteral
uri: Uri = None
count: Literal[int] = None
name: Literal[str] = None
timestamp: Literal[datetime] = None
temperature: Annotated[Literal[float], Datatype(CELSIUS)] = None
remark: RdfLiteral = None


LITERAL_FIELDS = ["count", "name", "timestamp", "temperature", "remark"]
Expand Down
Loading