diff --git a/CONTEXT.md b/CONTEXT.md index 4cdb814..4fa0d8f 100644 --- a/CONTEXT.md +++ b/CONTEXT.md @@ -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 `<...>`. @@ -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 ``; 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. diff --git a/README.md b/README.md index ed6fdb3..2451d9f 100644 --- a/README.md +++ b/README.md @@ -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: @@ -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 ``, 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: diff --git a/examples/02-binding_models.py b/examples/02-binding_models.py index ce99d6d..c4123a7 100644 --- a/examples/02-binding_models.py +++ b/examples/02-binding_models.py @@ -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( diff --git a/examples/03-ask_interaction.py b/examples/03-ask_interaction.py index ffb905b..9d7dc77 100644 --- a/examples/03-ask_interaction.py +++ b/examples/03-ask_interaction.py @@ -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(...). diff --git a/examples/04-post_measurement.py b/examples/04-post_measurement.py index 494aa2e..0e137d0 100644 --- a/examples/04-post_measurement.py +++ b/examples/04-post_measurement.py @@ -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. diff --git a/examples/06-dependency_injection.py b/examples/06-dependency_injection.py index 4353918..ee50930 100644 --- a/examples/06-dependency_injection.py +++ b/examples/06-dependency_injection.py @@ -113,8 +113,8 @@ def get_sensor_repository( class SensorReadingBinding(BindingModel): - sensor: Uri - temperature: Literal[float] + sensor: Uri = None + temperature: Literal[float] = None # --------------------------------------------------------------------------- diff --git a/examples/07-testing/kb.py b/examples/07-testing/kb.py index 4985e51..ab9976e 100644 --- a/examples/07-testing/kb.py +++ b/examples/07-testing/kb.py @@ -31,8 +31,8 @@ class ExampleBinding(BindingModel): - s: Uri - value: Literal[str] + s: Uri = None + value: Literal[str] = None kb.ask_ki( @@ -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( diff --git a/examples/08-async_handlers.py b/examples/08-async_handlers.py index 7df4306..462ae36 100644 --- a/examples/08-async_handlers.py +++ b/examples/08-async_handlers.py @@ -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( diff --git a/examples/11-custom_datatypes.py b/examples/11-custom_datatypes.py index 25499c5..5efb15a 100644 --- a/examples/11-custom_datatypes.py +++ b/examples/11-custom_datatypes.py @@ -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( diff --git a/examples/13-undefined_values.py b/examples/13-undefined_values.py index b38098c..1fdcc78 100644 --- a/examples/13-undefined_values.py +++ b/examples/13-undefined_values.py @@ -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. diff --git a/tests/test_bindings.py b/tests/test_bindings.py index b3ccf1e..520e079 100644 --- a/tests/test_bindings.py +++ b/tests/test_bindings.py @@ -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"), @@ -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( { @@ -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" @@ -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") @@ -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() @@ -144,7 +144,7 @@ class TestBinding(BindingModel): class RdfLiteralBinding(BindingModel): - value: RdfLiteral + value: RdfLiteral = None @pytest.mark.parametrize( @@ -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"^^'} @@ -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(): @@ -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"^^', @@ -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"^^' @@ -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"^^' @@ -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( @@ -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"^^', + "remark": '"foo"@de', + "temperature": '"12.5"^^', + } + ) + + assert partial.dump_partial_binding() == {"person": ""} + assert validated.age == 3 + assert validated.dump_partial_binding() == { + "age": '"3"^^', + "remark": '"foo"@de', + "temperature": '"12.5"^^', + } + + # ---------- UNDEFINED sentinels UNDEFINED_N3 = "" 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"]