diff --git a/README.md b/README.md index 96041df..5fafb18 100644 --- a/README.md +++ b/README.md @@ -120,16 +120,18 @@ f = model.Foo( Thanks to the resolver mechanism, these IRIs turn into fully-fledged objects as soon as you need them. -Writing a model by hand, declare links with `Link[T]` / `LinkList[T]`. This is the recommended notation: it is the only one a type checker reads correctly in both directions - the resolved object you get back, and the object, IRI or JSON object you may assign: +Writing a model by hand, declare links with `Link[T]` / `LinkList[T]`. This is the recommended notation: it is the only one a type checker reads correctly in both directions - the resolved object you get back, and the object, IRI or JSON object you may assign. Requiredness follows the annotation, as for every other pydantic field: ```python -from oold.model import Link, LinkedBaseModel, LinkList, OoldField +from typing import Optional + +from oold.model import Link, LinkedBaseModel, LinkList class Person(LinkedBaseModel): id: str name: str | None = None - employer: Link["Organization | None"] = OoldField() - knows: LinkList["Person"] = OoldField() + employer: Optional[Link["Organization"]] = None # optional + knows: LinkList["Person"] # required alice = Person(id="ex:alice", knows=["ex:bob", {"id": "ex:carol"}]) alice.knows[0].name # a Person, resolved on access diff --git a/docs/design/graph-object-binding.md b/docs/design/graph-object-binding.md index 72b85ae..d7818dd 100644 --- a/docs/design/graph-object-binding.md +++ b/docs/design/graph-object-binding.md @@ -175,12 +175,12 @@ accepts a literal, a reference or an inline object. #### Optionality is declared, not assumed `Link[T]` reads as `T`, not `T | None`. The declaration is a promise the binding -keeps, so a chain of mandatory links needs no guard per hop: +keeps, so a chain of non-optional links needs no guard per hop: ```python class Person(LinkedBaseModel): - father: Link["Person"] = OoldField() # mandatory - mother: Link["Person | None"] = OoldField() # optional + father: Link["Person"] # required, reads as Person + mother: Optional[Link["Person"]] = None # optional person.father.father.father.name # no guards - the type says it resolves mother = person.mother # guard required, and warranted @@ -193,23 +193,30 @@ declaration denies is the alternative, and that is the same polite fiction the What the promise costs, by case: -| | `Link[T]` | `Link[T \| None]` | +| | `Link[T]` | `Optional[Link[T]] = None` | | --- | --- | --- | -| not set, no IRI | **raises `LinkNotResolved`** | `None` | +| not supplied at construction | **raises `ValueError`** | constructs | +| not set, no IRI | **raises `LinkNotSet`** | `None` | | backend error | propagates | propagates | -| answered, no such entity | **raises `LinkNotResolved`** | `None` | - -All three fire on *access*, not at construction. An earlier version rejected an -absent mandatory link when the object was built - knowable without resolving -anything, and tempting for that reason - but it over-enforces: the annotation -says what *reading* the link yields, not that every instance carries one. Graph -data is routinely partial (most Wikidata people have no recorded father), and -rejecting those objects makes them unloadable. Declaring a link mandatory states -an intent to **traverse** it, so one `try/except` around a whole walk replaces a -guard at every hop. - -The middle row is unchanged and matters: a transport failure is not "has no -father", and conflating the two would be the real bug. +| answered, no such entity | **raises `LinkUnresolvable`** | `None` | + +`LinkNotSet` and `LinkUnresolvable` both derive from `LinkNotResolved`, so one +`try/except` covers a whole walk, and the message names the failing subject +(`Person(ex:p3).father ...`) - in a self-referential chain every hop shares the +class and attribute name, so only the subject identifies the hop. + +The construction row is the #159 decision: a bare annotation means required, +exactly as it does for every other pydantic field. Where data is routinely +partial (most Wikidata people have no recorded father), the required form makes +such records unconstructible - and because resolution constructs target +objects, the failure surfaces one hop from its cause. Those datasets declare +the `None` arm, or decouple the two axes with +`Link["Person"] = OoldField(required=False)`: the read stays strict (the walk +needs no guard and ends in one exception), while construction accepts records +without the property. + +The backend-error row is unchanged and matters: a transport failure is not "has +no father", and conflating the two would be the real bug. #### Coverage @@ -315,7 +322,8 @@ JSON Schema. Measured, not asserted: read types from `ty`, schema keys from | `Optional[List[T]] = Field(None, json_schema_extra={"range": ...})` | yes | no | `range` (legacy) | `list[T] \| None` | no | no | | `= OoldField(range="...")` | no | no | `x-oold-range` as given | as annotated | no | no | | `= OoldField()` | no | **yes** | **`x-oold-range`, derived** | as annotated | no | no | -| `Link[T]` / `LinkList[T]` with `OoldField()` | not yet | **yes** | **`x-oold-range`, derived** | **exact** (`T`, `LinkResultList[T]`) | **yes** | **yes** | +| `Link[T]` / `LinkList[T]`, bare or with `OoldField(...)` | not yet | **yes** | **`x-oold-range`, derived** | **exact** (`T`, `LinkResultList[T]`) | **yes** | **yes** - required | +| `Optional[Link[T]] = None` / `Optional[LinkList[T]] = None` | not yet | **yes** | **`x-oold-range`, derived** | **exact** (`T \| None`, `LinkResultList[T] \| None`) | checker-dependent (see dropped-notations note) | **yes** - optional | | `= Link(T)` / `= LinkList(T)` | no | yes (from the argument) | **field absent from schema** | exact | n/a - not a field | no | | `str \| Location \| None = OoldField(link=True)` | no | yes | **derived** | union as declared | no | via the `None` arm | @@ -326,15 +334,16 @@ unannotated descriptor form is not a pydantic field at all, so it neither appears in the schema nor gets an `__init__` parameter, though its read type is exact. -#### Requiredness is a field argument, not the annotation +#### Requiredness follows the annotation Two different questions - "must the caller supply it?" and "what do I get when I -read it?" - so two carriers: +read it?" - but both answered by the annotation, with one override: | declaration | stored as | enforced | on violation | |---|---|---|---| -| `Link[T]` - no `None` arm | `_AutoLink.optional = False` | on read | `LinkNotResolved` | -| `OoldField(required=True)` | `_AutoLink.required_iri`, precomputed into `cls.__required_links__`; reaches the schema as the standard `required` array | in `__init__` | `ValueError: ... is required but not set` | +| `Link[T]` - no `None` arm, no default | `_AutoLink.optional = False`, and `required_iri = True` derived from it (a declared default cancels the derivation, as a default does for every pydantic field), precomputed into `cls.__required_links__`; reaches the schema as the standard `required` array. Enforced as key presence, so an explicitly empty required `LinkList` constructs - `{"f": []}` satisfies JSON Schema `required` too | in `__init__`, and on read | `ValueError: ... is required but not set`; `LinkNotSet` / `LinkUnresolvable` on read | +| `Optional[Link[T]] = None` | `_AutoLink.optional = True`, `required_iri = False` | - | reading an absent link answers `None` | +| `OoldField(required=...)` | the explicit override of `required_iri`, winning over the derivation | as above | as above | A link is never required at the *pydantic* level, because its value is routed out of the payload before validation - which is why the legacy binding declared @@ -344,46 +353,44 @@ states requiredness through `required` alone, and the annotation exists only to carry the requirement across the point where code generation drops the property from `required` so the emitted field is `Optional`. -A bare `Link[T]` annotation with no default is **optional**. "No default means -required" reads well in plain Python, but requiredness propagates into -resolution - the failure mode described next - and links are declared far more -often than they are required, so the terse form is the common case. - -**Why not put requiredness in the annotation.** `required` -> `Link[T]`, -absence -> `Link[T | None]` reads well and was the first proposal. It fails on a -self-referential link. `father: Link["Person"]` required means every person in -the dataset carries a father IRI, which is only true of a graph with no root - -and resolution constructs target objects, so the failure surfaces one hop from -its cause: reading `alice.father` raises `ValueError: father is required but not -set` about *Bob's* document, which you never asked for. So `father` would have -to be `Link["Person | None"]`, which needs a guard per hop - the thing the -annotation exists to avoid. - -The alternative was to strip the `| None` under `TYPE_CHECKING`, which both -pyright and ty do resolve (a self-type overload on `Link[X | None]` yields `X`). -It was rejected because the runtime would then have to raise instead of -returning `None`, which silently breaks `entity.link is None`, `if entity.link:` -and `getattr(entity, f, None)` - and the last does *not* save the caller, since +**The history, for the record.** A bare `Link[T]` was briefly **optional** +(v2.0.0, option 2 of #159): "no default means required" propagates into +resolution - resolving constructs target objects, so a required link makes +every stored document lacking it unconstructible, and the failure surfaces one +hop from its cause, about a document you never asked for. That argument is +real, and it lost to a stronger one: the optional reading made the terse form +mean something no Python reader expects, and the escape it was protecting +exists anyway. `OoldField(required=False)` keeps the strict read over sparse +data, and the raise names the failing subject so the one-hop-away failure is at +least attributable. Decided in #159 (2026-11-17), shipped with the derivation +in `__pydantic_init_subclass__`. + +Two ways to make an *optional* declaration chain guard-free were examined and +rejected. Stripping the `| None` under `TYPE_CHECKING` - which both pyright and +ty do resolve - would force the runtime to raise instead of returning `None`, +silently breaking `entity.link is None`, `if entity.link:` and +`getattr(entity, f, None)`; the last does *not* save the caller, since `LinkNotResolved` is a `LookupError`, not an `AttributeError`. Pattern A in -`downstream-migration.md` is exactly that shape. - -Suppressing the diagnostic instead is only half-available: pyright separates -`reportOptionalMemberAccess` from `reportAttributeAccessIssue`, so it can be -turned off without losing typo detection, but ty reports both under -`unresolved-attribute` (checked on 0.0.49 and 0.0.80). Either way it is a -setting every downstream consumer would have to make. - -**Open:** nothing emits the read-side promise, so a model -> schema -> model -round trip loses the distinction between `Link[T]` and `Link[T | None]`. Code -generation can default to `Link[T]` for required properties and -`Link[T | None]` otherwise; expressing it exactly needs a keyword of its own. +`downstream-migration.md` is exactly that shape. And suppressing the diagnostic +is only half-available: pyright separates `reportOptionalMemberAccess` from +`reportAttributeAccessIssue`, so it can be turned off without losing typo +detection, but ty reports both under one rule. Either way it is a setting every +downstream consumer would have to make. `OoldField(required=False)` is what +remains of this demand, and it changes the declaration rather than lying about +one. + +**Round trip:** the schema side carries exactly the `required` array, so a +model -> schema -> model trip maps `required: [f]` to `Link[T]` and everything +else to `Optional[Link[T]]`. `OoldField(required=False)` - strict read, not +required - is not expressible in JSON Schema and never round-trips; "every +element resolves" is a promise about dereferencing, not a document constraint. #### Notations considered and dropped | notation | why it is not used | |---|---| | `list[Link[T]]` - `Link` nested inside a container | Silently degrades. A descriptor nested in a `list` is not treated as one, so the read type comes back as `list[Link[T]]` - not merely untyped but **wrong**. Superseded by `LinkList[T]`, which carries the to-many-ness itself. Still works at runtime, which is what makes it dangerous. | -| `Optional[Link[T]]` - `Link` nested inside a union | Half-degrades: the read type narrows to `T \| None` correctly, but the descriptor's `__set__` is not seen through the wrapper, so assigning an IRI is rejected (`Expected Link[T] \| None`). `Link[T \| None]` states the same thing and types both directions. | +| `Link[T \| None]` - the `None` arm inside the parameter | Works in both directions, but says optionality in a place no other pydantic field does. Deprecated in favour of `Optional[Link[T]] = None`, which reads identically; note the recommended form's *write* side is checker-dependent - pyright and current ty apply `__set__` through the union, older ty versions see a plain union slot and reject an IRI on write (read narrowing is correct everywhere). | | `Annotated[Person, OoldRange(...)]` wrapping a `Ref` value | The static type is not backed by the runtime value: a checker reads `Person`, `isinstance` says `Ref`. Rejected in 3(c). | | `Ref[T]` as the field type | Honest, but `p.knows[0]` is a `Ref`, not a `Person` - `isinstance` fails and the list operations, polymorphic dispatch and query DSL go with it (3.6). Kept only as an opt-in handle for visible or async resolution. | | `~Person.name == "x"` for match filters | `~` binds tighter than `==`, so this parses and would work - but pandas established `~` as NOT, and colliding with that is worse than a method. | diff --git a/docs/how-to/object-graph-mapping.md b/docs/how-to/object-graph-mapping.md index 4320bc4..43a3090 100644 --- a/docs/how-to/object-graph-mapping.md +++ b/docs/how-to/object-graph-mapping.md @@ -4,24 +4,28 @@ oold-python's core feature is *IRI-transparent references*: a link field can hol ## Recommended declaration -Declare a link with `Link[T]` or `LinkList[T]`, and `OoldField()` with no -arguments: +Declare a link with `Link[T]` or `LinkList[T]` as the annotation; nothing else +is needed: ```python -from oold.model import Link, LinkedBaseModel, LinkList, OoldField +from typing import Optional + +from oold.model import Link, LinkedBaseModel, LinkList class Person(LinkedBaseModel): id: str name: str | None = None - employer: Link["Organization | None"] = OoldField() - knows: LinkList["Person"] = OoldField() + employer: Optional[Link["Organization"]] = None # optional, like any other field + knows: LinkList["Person"] # required, like a bare `id: str` ``` The annotation is the single source of truth. It names the target, so `x-oold-range` is derived from it and written into the emitted schema - passing `range=` would state the same thing twice and let the two disagree. It says the -field is a link, so `link=True` is redundant. And it declares optionality: -`Link[T]` reads as `T`, `Link[T | None]` as `T | None`. +field is a link, so `link=True` is redundant. And it declares requiredness and +optionality, following the pydantic convention: a bare `Link[T]` is required +and reads as `T`; `Optional[Link[T]] = None` is optional and reads as +`T | None`. This is also the only form a type checker reads correctly in **both** directions - the resolved object you get back, and the object, IRI or JSON @@ -212,13 +216,15 @@ rejects `knows=["ex:bob"]` even though the library accepts it at runtime. `Link[T]` and `LinkList[T]` carry both. They are exported from `oold.model`: ```python -from oold.model import Link, LinkedBaseModel, LinkList, OoldField +from typing import Optional + +from oold.model import Link, LinkedBaseModel, LinkList class Person(LinkedBaseModel): id: str name: str | None = None - employer: Link["Organization | None"] = OoldField() - knows: LinkList["Person"] = OoldField() + employer: Optional[Link["Organization"]] = None + knows: LinkList["Person"] # accepted: an object, an IRI, or a JSON object alice = Person(id="ex:alice", knows=["ex:bob", {"id": "ex:carol"}]) @@ -250,23 +256,37 @@ the schema. ### Optionality is declared -`Link[T]` reads as `T`, so a chain needs no guard at every hop. `Link[T | None]` -reads as `T | None`, because absence is then part of the model: +`Link[T]` reads as `T`, so a chain needs no guard at every hop. +`Optional[Link[T]] = None` reads as `T | None`, because absence is then part of +the model: ```python class Person(LinkedBaseModel): - father: Link["Person"] = OoldField() # promises a Person - mother: Link["Person | None"] = OoldField() # may legitimately be absent + father: Link["Person"] # required; promises a Person + mother: Optional[Link["Person"]] = None # may legitimately be absent person.father.father.father.name # no guards ``` -A link declared mandatory raises `LinkNotResolved` when it is unset or when the -backend cannot place the reference, so one `try/except` covers a whole walk: +A link whose read type is non-optional raises when the read cannot keep the +promise - `LinkNotSet` when nothing is stored, `LinkUnresolvable` when a +reference is stored but the backend does not return the object. Both derive +from `LinkNotResolved`, so one `try/except` covers a whole walk. The message +names the failing subject, `Person(ex:p3).father ...`, because in a +self-referential chain every hop shares the class and attribute name. + +Over sparse data - where a record may genuinely lack the property - the +required form would make such records unconstructible. Either declare the +`None` arm and terminate the walk on `None`, or decouple the two axes with the +escape hatch: ```python from oold.model import LinkNotResolved +class Person(LinkedBaseModel): + # reads as Person (chains guard-free), but the schema does not demand it + father: Link["Person"] = OoldField(required=False) + try: while True: person = person.father @@ -276,7 +296,12 @@ except LinkNotResolved: ``` A **transport failure is not absence** - a connection error propagates unchanged -rather than being reported as a missing link. +rather than being reported as a missing link. And the single `except` covers the +walk's own links, not everything resolution does: constructing a traversed +document that is missing a *different* required link raises that class's plain +`ValueError`, which `except LinkNotResolved` does not catch. Where the walked +documents are allowed to be partial, their required links need `required=False` +too. ### `OoldField` arguments @@ -288,26 +313,23 @@ OoldField(required=None, range=None, link=None, **field_kwargs) | argument | effect | |---|---| -| `required` | the link must be supplied at construction; omitting it raises `ValueError`. Reaches the schema as the standard `required` array, and nothing else | +| `required` | **override** for what the annotation already states. Omitted, requiredness follows the annotation; `required=False` on a non-optional annotation keeps the strict read while the property stays out of the schema's `required` array | | `range` | target schema IRI, emitted as `x-oold-range`. **Do not pass it**: omitted, it is derived from the annotation, which already names the target | | `link` | marks the field a link where the annotation does not imply it, as in a union arm. Redundant with `Link[T]` / `LinkList[T]` | | `required_iri` | deprecated spelling of `required`, kept because generated packages pass it | | `**field_kwargs` | passed to `pydantic.Field` (`alias`, `description`, `default_factory`, ...). `default=None` is supplied unless you pass a `default_factory` | -Requiredness is always explicit. A link annotation with no default is optional, -like one with a bare `OoldField()`: +Requiredness follows the annotation, exactly as for every other pydantic field: ```python -father: Link["Person"] # optional -father: Link["Person"] = OoldField() # optional -father: Link["Person"] = OoldField(required=True) # required, explicit +father: Link["Person"] # required +father: Optional[Link["Person"]] = None # optional +father: Link["Person"] | None = None # optional, same statement +father: Link["Person"] = OoldField(required=False) # escape hatch, see below ``` -"No default means required" reads well in plain Python, but requiredness -propagates into resolution - reading a link constructs the target - so a -required link makes every stored document lacking it unconstructible. A -self-referential link like `father` could then never be satisfied by a real -dataset, and links are declared far more often than they are required. +A required link raises `ValueError` at construction when it is not supplied, +and the property appears in the emitted schema's `required` array. !!! note "`x-oold-required-iri` is internal" A schema states requiredness through `required` and nothing else. @@ -317,37 +339,71 @@ dataset, and links are declared far more often than they are required. never be required at the pydantic level, because its value is routed out of the payload before validation. It does not appear in a published schema. -### Requiredness is a field argument, not the annotation - -"Must the caller supply it?" and "what do I get when I read it?" are different -questions, and they need separate carriers - a self-referential link needs them -to differ. All four combinations are available: - -| | `OoldField()` | `OoldField(required=True)` | -|---|---|---| -| `Link[T]` | may omit; reading raises `LinkNotResolved` if absent | must supply; reading raises if absent | -| `Link[T \| None]` | may omit; reading yields `None` | must supply; reading may still yield `None` | - -```python -class Person(LinkedBaseModel): - father: Link["Person"] = OoldField() # chain it, no guards - employer: Link["Organization"] = OoldField(required=True) - advisor: Link["Person | None"] = OoldField() # guard it -``` - -`father` is the case that forces the split. Reading it must yield a `Person` so -that `person.father.father.father` needs no guard per hop - but no real dataset -can require *every* person to name a father, so it cannot be required at -construction. Requiredness in the annotation would tie those together. - -A link is never required at the *pydantic* level, because its value is routed -out of the payload before validation. That is what `required` exists to express, -and why it is also written into the schema's `required` array - otherwise the -constraint would be invisible to any plain JSON Schema validator. - -!!! note "Write the whole annotation" - Spell the union inside: `Link[T | None]`, not `Optional[Link[T]]`, and - `LinkList[T]`, not `list[Link[T]]`. Nested in another annotation a checker - stops applying descriptor rules - `list[Link[T]]` reads as a list of - descriptors, and `Optional[Link[T]]` narrows on read but rejects an IRI on - write. Both keep working at runtime, which is what makes them easy to miss. +### The notation table + +Every supported spelling, with what each column means: *required* is the +construction contract (`ValueError` when omitted), *read type* is what the +attribute yields, *unset read* is what reading an absent link does, and +*in `required[]`* is the emitted schema. + +| spelling | required | read type | unset read | in `required[]` | +|---|---|---|---|---| +| `Link[Org]` | yes | `Org` | raises | yes | +| `Link[Org] = OoldField(...)` | yes | `Org` | raises | yes | +| `Optional[Link[Org]] = None` | no | `Org \| None` | `None` | no | +| `Link[Org] \| None = None` | no | `Org \| None` | `None` | no | +| `Optional[Link[Org]] = OoldField(...)` | no | `Org \| None` | `None` | no | +| `Link[Org] = OoldField(required=False)` | no | `Org` | raises | no | +| `Link[Org] = OoldField(default="ex:o")` | no | `Org` | never unset - the default resolves | no | +| `LinkList[Org]` | yes | `LinkResultList[Org]` | raises | yes | +| `LinkList[Org] = OoldField(required=False)` | no | `LinkResultList[Org]` | raises | no | +| `Optional[LinkList[Org]] = None` | no | `LinkResultList[Org] \| None` | `[]` | no | +| `LinkList[Org \| None] = OoldField()` | no | `LinkResultList[Org \| None]` | element is `None` | no | + +A declared default makes a link not required, as it does for every pydantic +field; `required` means the *key* must be present, so an explicitly empty list +satisfies a required `LinkList` - exactly what JSON Schema `required` says +about the document `{"f": []}`. + +The three optional `LinkList` forms say different things: the list itself may +be absent, an element may not resolve, every element resolves. The first two +are the same at runtime - both read `[]` when unset - and differ only +statically. Two deprecated spellings keep working: `Link[T | None]` for the +to-one case (prefer `Optional[Link[T]]`), and `list[Link[T]]` for the to-many +case (prefer `LinkList[T]`) - note the latter now derives requiredness like +`LinkList[T]` does, so a bare `list[Link[T]]` is required and needs a `None` +arm or a default to stay optional. One deliberate deviation from plain +pydantic: a bare `Optional[Link[T]]` *without* `= None` is treated as optional, +because a link's value never reaches pydantic's own required check - write the +`= None`. + +`OoldField(required=False)` is the one escape that decouples the two axes: the +read still promises an `Org` - a chain needs no guard, an unset read raises +`LinkNotSet` - while the schema does not demand the property. It is **not +expressible in JSON Schema**, so it never round-trips through a schema and the +generator never emits it. Prefer `Optional[Link[T]] = None` unless the +guard-free chain is the point. + +### List access and filters + +Element access and the query DSL act on `LinkResultList[T]` and preserve `T`, +so the declaration decides what a filtered result holds: + +| declaration | `links[0]` | `links[0:2]` | `links[Person.name == "x"]` | `links["@name=='x'"]` | +|---|---|---|---|---| +| `LinkList[Org]` | `Org` | `LinkResultList[Org]` | `LinkResultList[Org]` | `Any` | +| `LinkList[Org \| None]` | `Org \| None` | `LinkResultList[Org \| None]` | `LinkResultList[Org \| None]` | `Any` | +| `Optional[LinkList[Org]] = None` | gate with `is not None` first: the attribute reads `LinkResultList[Org] \| None` | same | same | same | + +Two static imprecisions, stated rather than fixed: a condition filter over +`LinkList[Org | None]` keeps the `None` arm although a `None` element can never +match a condition, and the inline string form returns `Any`, which ends type +checking downstream - prefer the `Person.name == "x"` form. + +!!! note "Write `LinkList[T]`, not `list[Link[T]]`" + The to-many form is its own type. `list[Link[T]]` keeps working at runtime + but a checker reads it as a list of descriptors. For the to-one optional + form, `Optional[Link[T]]` is the recommended spelling; note that its + *write* side is checker-dependent - pyright and current ty apply the + descriptor's assignment type through the union, older ty versions see a + plain union slot and reject an IRI on write. diff --git a/examples/notation_example.py b/examples/notation_example.py index 9c34718..cbf6d95 100644 --- a/examples/notation_example.py +++ b/examples/notation_example.py @@ -47,8 +47,10 @@ class Person(OoldModel): # 1. Link[T] / LinkList[T] as the whole annotation - the recommended form. # Reads give the resolved object, writes accept an object, an IRI or a # JSON object, and a type checker sees both (see the coverage note below). - knows: LinkList["Person"] = OoldField() - employer: Link[Organization] = OoldField() + # A bare `Link[T]` is required, exactly like a bare `id: str`; the None + # arm declares the link optional, as it does for every pydantic field. + knows: LinkList["Person"] | None = None + employer: Link[Organization] | None = None # 2. the plain form: identical at runtime, no range= needed either, but a # type checker only sees list[Person] and so rejects a list of IRIs diff --git a/examples/wiki_data.py b/examples/wiki_data.py index b0af159..26ca6e2 100644 --- a/examples/wiki_data.py +++ b/examples/wiki_data.py @@ -27,7 +27,7 @@ from oold.backend.sparql import WikiDataSparqlResolver # based on pydantic v2 -from oold.model import Link, LinkedBaseModel, LinkNotResolved, OoldField +from oold.model import Link, LinkedBaseModel WD_ENTITY = "http://www.wikidata.org/entity/" ENTITY_SCHEMA = "https://oo-ld.org/examples/wikidata/Entity" @@ -89,16 +89,17 @@ class Person(WikiDataEntity): } ) type: str | None = "Item:Q5" - # Link[T] rather than "Person | None": the annotation says what *reading* - # the link yields, so a chain can be written plainly and guarded once. - # Ancestry does run out - that is what the try/except in main() is for. - father: Link["Person"] = OoldField() + # Optional, as for any other pydantic field: most Wikidata records carry no + # P22, so absence is data and reading an absent father answers None. A bare + # Link["Person"] would make the property required - every record would have + # to name a father, which no real dataset satisfies. + father: Link["Person"] | None = None # Extension, step 2 of 3: LinkList[T] is the to-many form. It reads as a - # list of Person - never None, an unset link is an empty list - so the + # list of Person - never None, an unset optional list reads as [] - so the # elements need no guard either. Add LinkList to the oold.model import # above when uncommenting. - # children: LinkList["Person"] = OoldField() + # children: LinkList["Person"] | None = None Person.model_rebuild() @@ -136,21 +137,31 @@ def main() -> None: # for child in father.children: # print(" resolved: ", child.id, "-", child.name) - print("\nplain chaining - no guard, no narrowing, no cast") - ggf = person.father.father.father - print(" great-grandfather:", ggf.name) + print("\nplain chaining - the ignore trades the per-hop guard for a runtime error") + try: + # An optional link reads as Person | None, so a checker wants a guard at + # every hop. The ignore keeps the dot syntax; the price is that a hop + # without a father surfaces as AttributeError on None - without naming + # which hop. Where the chain must stay guard-free AND raise with the + # failing subject named, decouple the axes with + # `father: Link["Person"] = OoldField(required=False)` instead. + # The bare ignore is deliberate: it is the one spelling pyright and + # both ty generations all honour - ty skips mypy-style codes, and its + # own rule name changed between releases. + ggf = person.father.father.father # type: ignore # noqa: PGH003 + print(" great-grandfather:", ggf.name) + except AttributeError: + print(" ancestry ran out before the great-grandfather") print("\nthe same walk, until the data runs out") ancestor, generations = person, 0 - try: - while True: - ancestor = ancestor.father - generations += 1 - print(f" {generations} generation(s) back:", ancestor.name) - except LinkNotResolved: - # Ancestry runs out. Declaring the link mandatory is what turns that - # into one exception at the end rather than a guard at every hop. - print(f" no father recorded for {ancestor.name} - walked {generations} generation(s)") + while (father_ := ancestor.father) is not None: + ancestor = father_ + generations += 1 + print(f" {generations} generation(s) back:", ancestor.name) + # Ancestry runs out as data, not as an exception: an optional link answers + # None both for "no P22 recorded" and for "could not be resolved". + print(f" no father recorded for {ancestor.name} - walked {generations} generation(s)") print("\nquery: the same DSL, translated to SPARQL by the resolver") found = Person[Person.name == "Tim Berners-Lee"] diff --git a/src/oold/model/__init__.py b/src/oold/model/__init__.py index b566d46..c706c17 100644 --- a/src/oold/model/__init__.py +++ b/src/oold/model/__init__.py @@ -793,7 +793,9 @@ def __init__(self, *a, **kw): # pydantic v2 extra = self.model_fields[name].json_schema_extra - if extra and "x-oold-required-iri" in extra and name not in self.__iris__: + # the value decides, not the key: OoldField(required=False) writes + # x-oold-required-iri: False to say the opposite of required + if extra and extra.get("x-oold-required-iri") and name not in self.__iris__: raise ValueError(f"{name} is required but not set") def _handle_value(self, name, value): @@ -1468,7 +1470,9 @@ def to_jsonld(self): from oold.model._descriptor import Link as Link # noqa: E402 from oold.model._descriptor import LinkList as LinkList # noqa: E402 from oold.model._descriptor import LinkNotResolved as LinkNotResolved # noqa: E402 +from oold.model._descriptor import LinkNotSet as LinkNotSet # noqa: E402 from oold.model._descriptor import LinkResultList as LinkResultList # noqa: E402 +from oold.model._descriptor import LinkUnresolvable as LinkUnresolvable # noqa: E402 from oold.model._descriptor import OoldExtra as OoldExtra # noqa: E402 from oold.model._descriptor import OoldField as OoldField # noqa: E402 diff --git a/src/oold/model/_descriptor.py b/src/oold/model/_descriptor.py index 2fb9727..3820ef5 100644 --- a/src/oold/model/_descriptor.py +++ b/src/oold/model/_descriptor.py @@ -42,6 +42,7 @@ class Person(LinkedBaseModel): import contextlib import logging import os +import re import sys import types from collections import defaultdict @@ -114,12 +115,23 @@ def is_active(cls) -> bool: class LinkNotResolved(LookupError): """A mandatory link did not yield an object. - Raised only for links declared ``Link[T]`` rather than ``Link[T | None]``: - the declaration promises a ``T``, so handing back a ``None`` the type denies - would be the real error. Declare the ``None`` arm where absence is data. + Raised only for links whose annotation promises a ``T`` - a bare ``Link[T]`` + rather than ``Optional[Link[T]]`` - so handing back a ``None`` the type + denies would be the real error. Declare ``Optional`` where absence is data. + + The two failure modes raise distinct subclasses; catching this base covers + both. """ +class LinkNotSet(LinkNotResolved): + """Nothing is stored for the link: the document never carried it.""" + + +class LinkUnresolvable(LinkNotResolved): + """A reference is stored, but the backend did not return the object.""" + + def links_enabled() -> bool: """Whether OO-LD link behaviour is active. @@ -189,20 +201,17 @@ def _neutralised(info: Any) -> Any: _record_default(field_name, info) namespace[field_name] = _neutralised(info) continue - if field_name not in namespace and _is_link_annotation(annotation): + if field_name not in namespace and (_is_link_annotation(annotation) or _is_link_annotation_string(annotation)): # `manager: Link[Org]` with nothing assigned. It still needs a field # carrying default=None - a link cannot be required at the pydantic # level, because its value never reaches validation, and left alone # every construction failed with a misleading "Field required" about # a value that had in fact been supplied. # - # It is *not* required in the OO-LD sense: that is what - # OoldField(required=True) says. Requiredness propagates into - # resolution - resolving a link constructs the target - so a - # required link makes every stored document lacking it - # unconstructible, and a self-referential link could never be - # satisfied by a real dataset. Links are declared far more often - # than they are required, so the terse form is the common case. + # Requiredness is NOT decided here: the install site derives it from + # the annotation, so a bare Link[T] is required exactly as a bare + # `x: int` is, and Optional[Link[T]] is not. This injection only + # keeps pydantic out of the way. namespace[field_name] = OoldField() continue # A Field() living in Annotated metadata rather than as the assigned @@ -414,16 +423,16 @@ def OoldField( OoldField(range=None, link=None, required=None, **field_kwargs) ``required`` - The link must be supplied when the model is constructed; omitting it - raises ``ValueError``. Written to the schema as ``x-oold-required-iri`` - and into the standard ``required`` array. - - This is the knob for requiredness, **not** the annotation. The two are - different questions - "must the caller supply it?" and "what do I get - when I read it?" - and a self-referential link needs them to differ: - ``father: Link["Person"]`` reads as a ``Person`` so an ancestry walk - needs no guard per hop, while no real dataset can require every person - to name a father. + Override for what the annotation already says. Requiredness follows the + annotation, as for every other pydantic field: a bare ``Link[T]`` is + required - construction without it raises ``ValueError``, and the + property lands in the schema's ``required`` array - while + ``Optional[Link[T]] = None`` is not. Pass ``required=`` only to make the + two axes differ: ``required=False`` on a non-optional annotation keeps + the ``T`` read (a chain needs no guard, an unset read raises) without + the schema demanding the property. That escape is not expressible in + JSON Schema and is not recommended; sparse data wants + ``Optional[Link[T]] = None``. ``range`` Target schema IRI, written as ``x-oold-range``. **Do not pass it**: it is derived from the annotation, which already names the target, and @@ -445,9 +454,9 @@ def OoldField( The recommended declaration pairs it with :class:`Link` / :class:`LinkList`, which are what give a type checker both the read and the write type:: - father: Link["Person"] = OoldField() # chains guard-free - manager: Link[Organization] = OoldField(required=True) - advisor: Link["Organization | None"] = OoldField() # may read as None + manager: Link[Organization] # required, chains guard-free + father: Optional[Link["Person"]] = None # optional, reads as None when absent + extras: Link[Organization] = OoldField(description="...") # required, plus field kwargs """ if required is None: required = required_iri @@ -473,6 +482,19 @@ def _has_default(value: Any) -> bool: return value is not None and value is not ... and value is not PydanticUndefined +def _derive_required_iri(optional: bool, explicit: Any, has_default: bool) -> bool: + """Requiredness, the way pydantic decides it for every other field. + + A bare non-optional annotation is required; a ``None`` arm or a declared + default makes it not. An explicit ``OoldField(required=)`` is the override. + One function, because two install sites derive this and drifting apart would + desynchronise construction from the descriptors. + """ + if explicit is not None: + return bool(explicit) + return not optional and not has_default + + class FieldProxy: """Class-level field handle enabling ``Person.name == "John"``. @@ -546,14 +568,21 @@ def __new__(mcs, name, bases, namespace, **kwargs): defaults: dict[str, Any] = {} if links_enabled(): defaults = _neutralise_link_defaults(namespace) + if defaults: + # Into the namespace, not onto the finished class: the requiredness + # derivation in __pydantic_init_subclass__ runs inside + # super().__new__ and has to see the class's own defaults - a + # defaulted link is not required, like any other defaulted field. + # Merge the bases' defaults so a subclass may add without restating. + inherited: dict[str, Any] = {} + for base in bases: + inherited.update(getattr(base, "__link_defaults__", {}) or {}) + namespace["__link_defaults__"] = {**inherited, **defaults} _Constructing.enter() try: cls = super().__new__(mcs, name, bases, namespace, **kwargs) finally: _Constructing.leave() - if defaults: - # a subclass may add defaults without restating the inherited ones - cls.__link_defaults__ = {**getattr(cls, "__link_defaults__", {}), **defaults} return cls def __getattr__(cls, name: str) -> Any: @@ -634,6 +663,24 @@ def _extract_target(annotation: Any) -> tuple[Any, bool, bool]: return target, many, optional +_LINK_ANNOTATION_STRING = re.compile(r"(?:^|[^\w.])(?:Link|LinkList)\[") + + +def _is_link_annotation_string(annotation: Any) -> bool: + """The stringized form of :func:`_is_link_annotation`. + + Under ``from __future__ import annotations`` the class namespace holds the + annotation as source text, and the type-based walk sees nothing. The field + cannot be resolved here - forward references are not importable yet - so + the text is matched instead. Only the default injection consults this. A + false positive takes a subscripted type that is literally named ``Link`` or + ``LinkList`` but is not ours; the injected ``OoldField()`` then marks it a + link. Accepted: without the match, every model under the future import + fails construction with a misleading "Field required". + """ + return isinstance(annotation, str) and bool(_LINK_ANNOTATION_STRING.search(annotation)) + + def _is_link_annotation(annotation: Any) -> bool: """Whether ``Link[...]`` / ``LinkList[...]`` appears anywhere in an annotation. @@ -1091,11 +1138,20 @@ def __get__(self, obj: Any, objtype: Any = None) -> Any: stored = obj._links.get(self.name) target = self._target_cls(objtype or type(obj)) if self.many: + if stored is None and not self.optional: + # Never set, as opposed to explicitly empty - [] is a statement + # about the elements, absence of the key is not. Same promise as + # the to-one branch below, so the required=False escape keeps + # its one-exception walk for lists too. + raise LinkNotSet( + f"{self._subject(obj)}.{self.name} is declared mandatory but is " + f"not set. Declare it as Optional[LinkList[T]] if absence is data." + ) items = _batch_resolve(stored, target) if stored else [] if not self.optional and any(item is None for item in items): # the declaration promised every element resolves missing = [r.iri for r, item in zip(stored, items, strict=False) if item is None] - raise LinkNotResolved(self._message(obj, missing)) + raise LinkUnresolvable(self._message(obj, missing)) result = LinkResultList(items)._bind(obj, self.name, stored) elif stored is None: if not self.optional: @@ -1105,15 +1161,15 @@ def __get__(self, obj: Any, objtype: Any = None) -> Any: # they are built would make them unloadable. Declaring the link # mandatory states an intent to traverse it, so one try/except # around a whole chain replaces a guard at every hop. - raise LinkNotResolved( - f"{type(obj).__name__}.{self.name} is declared mandatory but is " - f"not set. Declare it as Link[T | None] if absence is data." + raise LinkNotSet( + f"{self._subject(obj)}.{self.name} is declared mandatory but is " + f"not set. Declare it as Optional[Link[T]] if absence is data." ) result = None else: result = _batch_resolve([stored], target)[0] if result is None and not self.optional: - raise LinkNotResolved(self._message(obj, [stored.iri])) + raise LinkUnresolvable(self._message(obj, [stored.iri])) # Store the resolved value in the instance __dict__. This descriptor is # deliberately NON-data (no __set__), so from now on normal attribute # lookup finds the instance dict first and never calls back into Python: @@ -1122,10 +1178,22 @@ def __get__(self, obj: Any, objtype: Any = None) -> Any: obj.__dict__[self.name] = result return result + @staticmethod + def _subject(obj: Any) -> str: + """``Person(ex:p3)``, or the class name alone when there is no IRI. + + In ``a.father.father.father`` every hop shares the class and attribute + name, so only the subject identifies which hop failed. + """ + get_iri = getattr(obj, "get_iri", None) + iri = get_iri() if callable(get_iri) else None + name = type(obj).__name__ + return f"{name}({iri})" if iri else name + def _message(self, obj: Any, iris: list[Any]) -> str: listed = ", ".join(str(iri) for iri in iris if iri) return ( - f"{type(obj).__name__}.{self.name} is declared mandatory, but " + f"{self._subject(obj)}.{self.name} is declared mandatory, but " f"{listed or 'the reference'} could not be resolved. The backend " f"answered without it - declare the link as optional if that is a " f"legitimate answer." @@ -1184,14 +1252,16 @@ class Link(_AutoLink, _LinkAnnotation, Generic[T]): Two spellings, not equivalent to a type checker:: - employer: Link[Organization] = OoldField() # recommended + employer: Link[Organization] # recommended employer = Link(Organization) # not a pydantic field The annotation form types both directions: it reads as ``T`` and accepts a - ``T``, an IRI or a JSON object on assignment. ``Link[T]`` promises a ``T``, - so a chain needs no guard per hop; write ``Link[T | None]`` where absence is - part of the model. Nested - ``Optional[Link[T]]`` - the read type still - narrows but the write type does not, so spell the union inside. + ``T``, an IRI or a JSON object on assignment. A bare ``Link[T]`` is + required, like any other bare annotation, and promises a ``T`` - so a chain + needs no guard per hop. ``Optional[Link[T]] = None`` declares the link + optional, reading as ``T | None``. (``Link[T | None]`` says the same and + keeps working, but is deprecated: optionality belongs outside, where every + other pydantic field declares it.) """ _many: ClassVar[bool] = False @@ -1222,12 +1292,14 @@ class LinkList(_AutoLink, _LinkAnnotation, Generic[T]): Two spellings, not equivalent to a type checker:: - knows: LinkList["Person"] = OoldField() # recommended + knows: LinkList["Person"] # recommended knows = LinkList("Person") # not a pydantic field - The annotation form reads as ``LinkResultList[T]`` - never ``None`` itself, - an unset link is an empty list - and accepts objects, IRIs or JSON objects - on assignment. Prefer it to ``list[Link[T]]``, which a checker reads as a + The annotation form reads as ``LinkResultList[T]`` and accepts objects, IRIs + or JSON objects on assignment. A bare ``LinkList[T]`` is required; + ``Optional[LinkList[T]] = None`` says the list itself may be absent, while + ``LinkList[T | None]`` says an element may not resolve - two different + statements. Prefer either to ``list[Link[T]]``, which a checker reads as a list of descriptors. """ @@ -1449,7 +1521,18 @@ def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: target, many, optional = _extract_target(field.annotation) if isinstance(rng, str) and not isinstance(target, type): target = rng - descr = _AutoLink(name, target, many, optional, bool(extra.get("x-oold-required-iri"))) + # Requiredness follows the annotation, as it does for every other + # pydantic field: a bare Link[T] is required, Optional[Link[T]] or a + # declared default is not. An explicit required= stays the + # override - which is also what keeps the legacy keyword form + # unchanged, since there the annotation never says Link[...] and + # `optional` is always True. + required_iri = _derive_required_iri( + optional, + extra.get("x-oold-required-iri"), + name in getattr(cls, "__link_defaults__", {}), + ) + descr = _AutoLink(name, target, many, optional, required_iri) setattr(cls, name, descr) links[name] = descr cls.__link_fields__ = links @@ -1495,7 +1578,11 @@ def __init__(self, *args: Any, **data: Any) -> None: link_data[_name] = _iris for key, value in link_data.items(): self._set_link(key, value) - missing = [name for name in type(self).__required_links__ if not self._links.get(name)] + # Presence, not truthiness: JSON Schema `required` demands the key, and + # an explicitly empty list satisfies it - the emitted schema accepts + # {"f": []}, so construction must too, or stored documents with an + # empty-but-present list become unconstructible during resolution. + missing = [name for name in type(self).__required_links__ if name not in self._links] if missing: # x-oold-required-iri, enforced as the legacy binding did. It raised # on the mere presence of the keyword; this raises on a true value, diff --git a/src/oold/model/_notation.py b/src/oold/model/_notation.py index fb965b9..131a094 100644 --- a/src/oold/model/_notation.py +++ b/src/oold/model/_notation.py @@ -4,17 +4,18 @@ target is inferred from the annotation, so the schema IRI is not repeated in Python. Note the trade-off: nothing then writes ``x-oold-range`` into the emitted schema, so pass ``range=`` where the schema is the artifact. -2. ``Link[T]`` / ``LinkList[T]`` as the **whole** annotation, e.g. +2. ``Link[T]`` / ``LinkList[T]`` as the annotation, e.g. ``employer: Link[Organization]`` or ``knows: LinkList["Person"]``. These are descriptor types, so a checker takes the ``__init__`` parameter and the assignment type from ``__set__`` and the attribute type from ``__get__`` (PEP 681) - which is how one field carries both the resolved read type and - the IRI-or-object write type. Optionality is declared in the parameter: - ``Link[T]`` reads as ``T``, ``Link[T | None]`` as ``T | None``. + the IRI-or-object write type. Requiredness and optionality follow the + annotation like everywhere else in pydantic: a bare ``Link[T]`` is required + and reads as ``T``; ``Optional[Link[T]] = None`` is optional and reads as + ``T | None``. - They must be the whole annotation. Nested - ``list[Link[T]]`` or - ``Optional[Link[T]]`` - a checker does not apply descriptor rules and the - read type comes back wrong; use ``LinkList[T]`` and ``Link[T | None]``. + For the to-many form use ``LinkList[T]``, not ``list[Link[T]]`` - a checker + reads the latter as a list of descriptors. 3. **Union forms** mixing literal, inline object and reference, e.g. ``location: Union[str, Location, None] = OoldField(link=True)``. @@ -44,6 +45,7 @@ LinkList, OoldField, _AutoLink, + _derive_required_iri, _extract_target, _LinkAnnotation, _register_class, @@ -185,15 +187,19 @@ def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: continue if explicit_range and not isinstance(target, type): target = explicit_range - # carry the same promises the binding computes, so Link[T] is - # mandatory here too and x-oold-required-iri is enforced + # carry the same promises the binding computes: requiredness follows + # the annotation, and an explicit required= stays the override _, _, optional = _extract_target(field.annotation) descr = _AutoLink( name, target, many=many, optional=optional, - required_iri=bool(extra.get("x-oold-required-iri")), + required_iri=_derive_required_iri( + optional, + extra.get("x-oold-required-iri"), + name in getattr(cls, "__link_defaults__", {}), + ), ) setattr(cls, name, descr) links[name] = descr @@ -201,6 +207,10 @@ def __pydantic_init_subclass__(cls, **kwargs: Any) -> None: literals[name] = lits cls.__link_fields__ = links cls.__link_literals__ = literals + # This hook rebuilds the descriptor set from its own scan, so the + # construction-time enforcement has to follow the same set - the tuple + # computed by super() reflects the binding's scan, not this one. + cls.__required_links__ = tuple(n for n, d in links.items() if d.required_iri) # Register the way the binding does - including the inherited-IRI # guard - rather than writing the type default straight in, which let a # subclass that only narrows a field replace its parent in the registry. diff --git a/src/oold/model/v1/__init__.py b/src/oold/model/v1/__init__.py index ae95f27..3edbbc4 100644 --- a/src/oold/model/v1/__init__.py +++ b/src/oold/model/v1/__init__.py @@ -585,7 +585,8 @@ def __init__(self, *a, **kw): # pydantic v2 # extra = self.model_fields[name].json_schema_extra - if extra and "x_oold_required_iri" in extra and name not in self.__iris__: + # the value decides, not the key: required=False states the opposite + if extra and extra.get("x_oold_required_iri") and name not in self.__iris__: raise ValueError(f"{name} is required but not set") def _handle_value(self, name, value): diff --git a/src/oold/model/v1/_descriptor.py b/src/oold/model/v1/_descriptor.py index 23b7372..2e554d2 100644 --- a/src/oold/model/v1/_descriptor.py +++ b/src/oold/model/v1/_descriptor.py @@ -261,7 +261,8 @@ def __init__(self, *args: Any, **data: Any) -> None: link_data[_name] = _iris for key, value in link_data.items(): link_fields[key].set_value(self, value) - missing = [name for name, d in link_fields.items() if d.required_iri and not self._links.get(name)] + # presence, not truthiness: an explicitly empty list satisfies `required` + missing = [name for name, d in link_fields.items() if d.required_iri and name not in self._links] if missing: # see the v2 note: enforced on a true value, not on key presence raise ValueError(f"{', '.join(sorted(missing))} is required but not set") diff --git a/tests/test_compat_parity.py b/tests/test_compat_parity.py index 4d59558..a24e594 100644 --- a/tests/test_compat_parity.py +++ b/tests/test_compat_parity.py @@ -299,3 +299,23 @@ class M(base): seen.append(M(id=f"ex:{tag}", nested={"n": 5})._raw_dict()["nested"]) assert seen[0] == seen[1] == {"n": 5} + + +def test_required_false_constructs_unset_in_both_bindings(): + """OoldField(required=False) writes x-oold-required-iri: False. The legacy + binding raised on mere key presence, inverting the stated meaning.""" + from oold.model import OoldField + + for base, tag in ((LegacyLinkedBaseModel, "SRF"), (LinkedBaseModel, "ARF")): + + class T(base): + id: str + type: str | None = f"ex:{tag}T" + + class M(base): + id: str + type: str | None = f"ex:{tag}M" + loose: T | None = OoldField(required=False, range="T") + + m = M(id=f"ex:{tag}") # must construct unset in both bindings + assert m.get_iri_ref("loose") is None diff --git a/tests/test_downstream_shapes.py b/tests/test_downstream_shapes.py index 421319d..1fa904b 100644 --- a/tests/test_downstream_shapes.py +++ b/tests/test_downstream_shapes.py @@ -159,7 +159,8 @@ class M(LinkedBaseModel): def test_optional_wrapping_a_link_is_optional(): """Optional[Link[T]] and Link[T | None] mean the same thing; the union was - only honoured when it came *after* the Link.""" + only honoured when it came *after* the Link. A bare Link[T] is required, + as a bare annotation is everywhere else in pydantic.""" from typing import Optional from oold.model import Link, LinkNotResolved @@ -171,11 +172,21 @@ class M(LinkedBaseModel): mandatory: Link[Target] = OoldField() M.model_rebuild() - m = M(id="ex:m") + with pytest.raises(ValueError, match="mandatory is required"): + M(id="ex:m") + m = M(id="ex:m", mandatory="ex:1") assert m.outer is None assert m.inner is None + + class Sparse(LinkedBaseModel): + id: str + # the escape hatch: reads as Target, but the schema does not demand it + loose: Link[Target] = OoldField(required=False) + + Sparse.model_rebuild() + s = Sparse(id="ex:s") with pytest.raises(LinkNotResolved): - _ = m.mandatory + _ = s.loose def test_a_shared_field_info_is_not_mutated(): diff --git a/tests/test_future_annotations.py b/tests/test_future_annotations.py new file mode 100644 index 0000000..8b9200d --- /dev/null +++ b/tests/test_future_annotations.py @@ -0,0 +1,40 @@ +"""Link declarations under ``from __future__ import annotations``. + +The future import stringizes every annotation in the module, so the metaclass +default injection cannot see ``Link[...]`` as a type - it has to recognise the +source text, or a bare link field stays pydantic-required and construction +fails with a misleading "Field required" about a value that was supplied. +""" + +from __future__ import annotations + +import pytest + +from oold.model._descriptor import Link, LinkedBaseModel, LinkList + + +class Org(LinkedBaseModel): + id: str + type: str | None = "fut:Org" + + +class Person(LinkedBaseModel): + id: str + type: str | None = "fut:Person" + employer: Link[Org] + knows: LinkList[Person] | None = None + + +Person.model_rebuild() + + +def test_a_bare_link_constructs_under_the_future_import(): + p = Person(id="fut:p", employer="fut:acme") + assert p.link_iris("employer") == "fut:acme" + + +def test_requiredness_still_follows_the_annotation(): + with pytest.raises(ValueError, match="employer is required"): + Person(id="fut:p") + assert "employer" in (Person.export_schema().get("required") or []) + assert "knows" not in (Person.export_schema().get("required") or []) diff --git a/tests/test_link_annotation.py b/tests/test_link_annotation.py index 2031611..fceecfe 100644 --- a/tests/test_link_annotation.py +++ b/tests/test_link_annotation.py @@ -40,13 +40,23 @@ class Person(LinkedBaseModel): class Employee(LinkedBaseModel): - """Every employee has an employer - declared, and enforced.""" + """Every employee has an employer - declared, and enforced at construction. + + ``required=False`` decouples the two axes for ``Loose``: the read still + promises an ``Org``, but partial data constructs. + """ id: str type: str | None = "annot:Employee" employer: Link[Org] = OoldField() +class Loose(LinkedBaseModel): + id: str + type: str | None = "annot:Loose" + employer: Link[Org] = OoldField(required=False) + + class Plain(LinkedBaseModel): id: str type: str | None = "annot:Plain" @@ -55,6 +65,7 @@ class Plain(LinkedBaseModel): Person.model_rebuild() Employee.model_rebuild() +Loose.model_rebuild() Plain.model_rebuild() @@ -155,20 +166,28 @@ def test_optional_link_keeps_the_slot_of_an_unresolvable_reference(store): assert p.link_iris("knows") == ["annot:bob", "annot:nobody"] -def test_mandatory_link_unset_raises_on_access_not_on_construction(store): - """Partial graph data must still load; the promise is about reading.""" - e = Employee(id="annot:e") # builds fine +def test_a_bare_link_is_required_at_construction(store): + """A bare Link[T] is required like any other bare annotation.""" + with pytest.raises(ValueError, match="employer is required"): + Employee(id="annot:e") + + +def test_required_false_unset_raises_on_access_not_on_construction(store): + """The escape hatch: partial data still loads; the promise is about + reading, so the raise moves to the access.""" + e = Loose(id="annot:e") # builds fine with pytest.raises(LinkNotResolved, match="not set"): _ = e.employer def test_a_whole_chain_needs_one_except_not_a_guard_per_hop(store): - """The point of declaring a link mandatory.""" + """The point of a non-optional read type. required=False lets partial + data construct while every hop still reads as a Node.""" class Node(LinkedBaseModel): id: str type: str | None = "annot:Node" - parent: Link["Node"] = OoldField() + parent: Link["Node"] = OoldField(required=False) Node.model_rebuild() leaf = Node(id="annot:leaf", parent={"id": "annot:mid"}) diff --git a/tests/test_link_notation_matrix.py b/tests/test_link_notation_matrix.py new file mode 100644 index 0000000..f5c5cb0 --- /dev/null +++ b/tests/test_link_notation_matrix.py @@ -0,0 +1,244 @@ +"""The notation table, row by row - issue #159. + +One test per runtime column of the table in +``docs/how-to/object-graph-mapping.md``: *required* (construction outcome), +*unset read* and *in required[]*. The read-type columns are static and live in +``tests/typing/links.py``, checked by pyright and ty via ``test_typing.py``. + +Each row is a parameter whose id is the spelling, so a missing row is visible +in the test names. Type IRIs are prefixed ``mx:`` to stay out of the +process-wide registry's way. +""" + +from typing import Optional + +import pytest +from pydantic import ConfigDict + +# The descriptor binding directly, not the OOLD_DESCRIPTOR_BINDING-dependent +# name: the table is about the annotation form, which only this binding has. +from oold.model._descriptor import ( + Link, + LinkedBaseModel, + LinkList, + LinkNotResolved, + LinkNotSet, + LinkUnresolvable, + OoldField, +) + + +class Org(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/Org"}) + id: str + type: str | None = "mx:Org" + + +# The classes are literal bodies, not type() calls: annotation capture differs +# between the two, and the table documents the form a user writes. + + +class M0(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M0"}) + id: str + type: str | None = "mx:M0" + f: Link[Org] + + +class M1(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M1"}) + id: str + type: str | None = "mx:M1" + f: Link[Org] = OoldField() + + +class M2(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M2"}) + id: str + type: str | None = "mx:M2" + f: Optional[Link[Org]] = None # noqa: UP045 - the spelling under test + + +class M3(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M3"}) + id: str + type: str | None = "mx:M3" + f: Link[Org] | None = None + + +class M4(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M4"}) + id: str + type: str | None = "mx:M4" + f: Optional[Link[Org]] = OoldField() # noqa: UP045 - the spelling under test + + +class M5(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M5"}) + id: str + type: str | None = "mx:M5" + f: Link[Org] = OoldField(required=False) + + +class M6(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M6"}) + id: str + type: str | None = "mx:M6" + f: LinkList[Org] + + +class M7(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M7"}) + id: str + type: str | None = "mx:M7" + f: Optional[LinkList[Org]] = None # noqa: UP045 - the spelling under test + + +class M8(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M8"}) + id: str + type: str | None = "mx:M8" + f: LinkList[Org | None] = OoldField() + + +class M9(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M9"}) + id: str + type: str | None = "mx:M9" + f: LinkList[Org] = OoldField(required=False) + + +class M10(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/M10"}) + id: str + type: str | None = "mx:M10" + f: Link[Org] = OoldField(default="mx:o1") + + +# spelling -> class and expected columns +ROWS = { + "Link[Org]": {"cls": M0, "required": True}, + "Link[Org] = OoldField()": {"cls": M1, "required": True}, + "Optional[Link[Org]] = None": {"cls": M2, "required": False}, + "Link[Org] | None = None": {"cls": M3, "required": False}, + "Optional[Link[Org]] = OoldField()": {"cls": M4, "required": False}, + "Link[Org] = OoldField(required=False)": {"cls": M5, "required": False, "strict_read": True}, + "LinkList[Org]": {"cls": M6, "required": True, "many": True}, + "Optional[LinkList[Org]] = None": {"cls": M7, "required": False, "many": True}, + "LinkList[Org | None] = OoldField()": {"cls": M8, "required": False, "many": True}, + "LinkList[Org] = OoldField(required=False)": {"cls": M9, "required": False, "many": True, "strict_read": True}, + 'Link[Org] = OoldField(default="mx:o1")': {"cls": M10, "required": False, "defaulted": True}, +} + +_CLASSES = {label: row["cls"] for label, row in ROWS.items()} + + +@pytest.mark.parametrize("label", ROWS) +def test_column_required(label): + """Column *required*: construction without the link.""" + cls, row = _CLASSES[label], ROWS[label] + if row["required"]: + with pytest.raises(ValueError, match="f is required"): + cls(id="mx:i") + else: + assert cls(id="mx:i").id == "mx:i" + + +@pytest.mark.parametrize("label", ROWS) +def test_column_in_required_array(label): + """Column *in required[]*: the emitted schema states the same thing.""" + cls, row = _CLASSES[label], ROWS[label] + assert ("f" in (cls.export_schema().get("required") or [])) is row["required"] + + +@pytest.mark.parametrize( + "label", + [label for label, row in ROWS.items() if not row["required"] and not row.get("defaulted")], +) +def test_column_unset_read(label): + """Column *unset read*, for the rows that construct unset. + + A non-optional read type raises; an optional one answers None for a + to-one and [] for a to-many ([] is "no elements", not "no list" - the + None-list statement needs the value actually set to None, which an unset + descriptor does not distinguish today; documented as a known gap). + """ + cls, row = _CLASSES[label], ROWS[label] + instance = cls(id="mx:i") + if row.get("strict_read"): + with pytest.raises(LinkNotSet): + _ = instance.f + elif row.get("many"): + assert list(instance.f) == [] + else: + assert instance.f is None + + +def test_required_rows_read_after_construction(linked_store): + """Column *unset read* is unreachable for required rows - construction + already demands the value - so the read contract is checked supplied.""" + linked_store("mx", {"mx:o1": {"id": "mx:o1", "type": "mx:Org"}}) + one = _CLASSES["Link[Org]"](id="mx:i", f="mx:o1") + assert isinstance(one.f, Org) + many = _CLASSES["LinkList[Org]"](id="mx:i", f=["mx:o1"]) + assert [type(v).__name__ for v in many.f] == ["Org"] + + +def test_a_required_list_accepts_an_explicitly_empty_one(linked_store): + """JSON Schema `required` demands the key, and {"f": []} has it - so the + schema the class emits accepts the document, and construction must too.""" + linked_store("mx", {}) + instance = _CLASSES["LinkList[Org]"](id="mx:i", f=[]) + assert list(instance.f) == [] + + +def test_a_defaulted_link_is_not_required(linked_store): + """A field with a default is never required in pydantic; the declared IRI + is seeded instead and resolves lazily.""" + linked_store("mx", {"mx:o1": {"id": "mx:o1", "type": "mx:Org"}}) + cls = _CLASSES['Link[Org] = OoldField(default="mx:o1")'] + instance = cls(id="mx:i") # constructs: the default satisfies the link + assert instance.link_iris("f") == "mx:o1" + assert isinstance(instance.f, Org) + + +def test_not_set_and_unresolvable_are_distinct(linked_store): + """The two failure modes carry their own class; the base catches both.""" + linked_store("mx", {"mx:o1": {"id": "mx:o1", "type": "mx:Org"}}) + strict = _CLASSES["Link[Org] = OoldField(required=False)"] + + unset = strict(id="mx:i") + with pytest.raises(LinkNotSet): + _ = unset.f + with pytest.raises(LinkNotResolved): + _ = unset.f + + ghost = strict(id="mx:i", f="mx:ghost") + with pytest.raises(LinkUnresolvable): + _ = ghost.f + with pytest.raises(LinkNotResolved): + _ = ghost.f + + assert not issubclass(LinkNotSet, LinkUnresolvable) + assert not issubclass(LinkUnresolvable, LinkNotSet) + + +def test_the_message_names_the_failing_hop(linked_store): + """Every hop of a self-referential chain shares the class and attribute + name, so the subject IRI is what identifies the failing one.""" + linked_store("mx", {}) + + class Hop(LinkedBaseModel): + model_config = ConfigDict(json_schema_extra={"$id": "https://example.org/mx/Hop"}) + id: str + type: str | None = "mx:Hop" + parent: Link["Hop"] = OoldField(required=False) + + Hop.model_rebuild() + leaf = Hop(id="mx:leaf", parent={"id": "mx:mid", "type": "mx:Hop"}) + with pytest.raises(LinkNotSet, match=r"Hop\(mx:mid\)\.parent"): + _ = leaf.parent.parent.parent + + ghost = Hop(id="mx:g0", parent="mx:ghost") + with pytest.raises(LinkUnresolvable, match=r"Hop\(mx:g0\)\.parent.*mx:ghost"): + _ = ghost.parent diff --git a/tests/test_notation.py b/tests/test_notation.py index 421aa1c..1bf21c8 100644 --- a/tests/test_notation.py +++ b/tests/test_notation.py @@ -37,9 +37,10 @@ class Person(OoldModel): type: str | None = "ex:NPerson" # target inferred from the annotation, no range= needed knows: list["Person"] = OoldField() - # Link[T] inside the annotation + # Link[T] inside the annotation; the None arm keeps it optional, since a + # bare Link annotation is required like any other bare annotation employer: Link[Org] | None = Field(default=None) - friends: list[Link["Person"]] = OoldField() + friends: list[Link["Person"]] | None = OoldField() # union: literal text | inline object | reference location: str | Location | None = OoldField(link=True) @@ -259,16 +260,17 @@ class Explicit(OoldModel): assert _properties(Explicit)["target"]["x-oold-range"] == "Legacy.json" -def test_required_is_a_field_argument_not_the_annotation(): - """Requiredness and the read type are separate questions. A self-link needs - them to differ: father reads as a Person so a walk needs no guard per hop, - while no real dataset can require every person to name one.""" +def test_required_follows_the_annotation_and_the_field_argument_overrides(): + """Requiredness follows the annotation, as it does for every other pydantic + field. The field argument exists only to make the two axes differ: a + self-link over sparse data reads as a Chain so a walk needs no guard per + hop, while the schema does not demand that every record names one.""" class Chain(OoldModel): id: str type: str | None = "ex:NChain" - father: Link["Chain"] = OoldField() - manager: Link["Org"] = OoldField(required=True) + father: Link["Chain"] = OoldField(required=False) + manager: Link["Org"] Chain.model_rebuild() @@ -301,15 +303,11 @@ class Old(OoldModel): assert Old.__link_fields__["manager"].required_iri is True -def test_a_link_annotation_without_a_default_is_optional(): - """Links are declared far more often than they are required, so the terse - form is the common case. - - Requiredness is explicit because it propagates into resolution: resolving a - link constructs the target, so a required link makes every stored document - lacking it unconstructible - and a self-referential link, `father`, could - then never be satisfied by a real dataset. - """ +def test_a_bare_link_annotation_is_required(): + """A bare ``Link[T]`` is required, exactly as a bare ``x: int`` is - + optionality is declared with ``Optional[...]``, not inferred from the kind + of field. Sparse data declares the ``None`` arm or passes + ``required=False``; see issue #159.""" class Bare(OoldModel): id: str @@ -317,6 +315,18 @@ class Bare(OoldModel): manager: Link["Org"] Bare.model_rebuild() - assert Bare(id="ex:b").link_iris("manager") is None # constructs unset + with pytest.raises(ValueError, match="manager is required"): + Bare(id="ex:b") assert Bare(id="ex:b", manager="ex:acme").link_iris("manager") == "ex:acme" - assert Bare.__link_fields__["manager"].required_iri is False + assert Bare.__link_fields__["manager"].required_iri is True + assert "manager" in _required(Bare) + + class Sparse(OoldModel): + id: str + type: str | None = "ex:NSparse" + manager: Link["Org"] | None = None + + Sparse.model_rebuild() + assert Sparse(id="ex:s").link_iris("manager") is None # constructs unset + assert Sparse.__link_fields__["manager"].required_iri is False + assert "manager" not in _required(Sparse) diff --git a/tests/typing/links.py b/tests/typing/links.py index 087bb78..a0104c0 100644 --- a/tests/typing/links.py +++ b/tests/typing/links.py @@ -10,13 +10,20 @@ ``__init__`` parameter and the assignment type from ``__set__`` and the attribute type from ``__get__`` (PEP 681). -Optionality is **declared**, not assumed. ``Link[T]`` reads as ``T`` and the -binding keeps that promise - a reference that cannot be resolved raises rather -than returning a ``None`` the type denies. ``Link[T | None]`` reads as -``T | None``, because absence is then part of the model. That is what lets a -chain of mandatory links be written without a guard at every hop. +Optionality follows the annotation, as it does for every other pydantic field. +A bare ``Link[T]`` is required and reads as ``T`` - the binding keeps that +promise by raising rather than returning a ``None`` the type denies, which is +what lets a chain of mandatory links be written without a guard at every hop. +``Optional[Link[T]] = None`` is the optional form and reads as ``T | None``, +because absence is then part of the model. + +The read-type and filter columns of the notation table in +``docs/how-to/object-graph-mapping.md`` are asserted here; the runtime columns +live in ``tests/test_link_notation_matrix.py``. """ +from typing import Any + from typing_extensions import assert_type from oold.model import Link, LinkedBaseModel, LinkList, LinkResultList, OoldField @@ -30,13 +37,18 @@ class Org(LinkedBaseModel): class Entity(LinkedBaseModel): id: str name: str | None = None - # mandatory: every reference resolves, or the read raises - owner: Link[Org] = OoldField() - parent: Link["Entity"] = OoldField() - links: LinkList["Entity"] = OoldField() - # optional: absence is data - sponsor: Link["Org | None"] = OoldField() - maybe_links: LinkList["Entity | None"] = OoldField() + # required: the bare annotation, exactly like a bare `x: int` + owner: Link[Org] + parent: Link["Entity"] + links: LinkList["Entity"] + # required with field kwargs: OoldField() does not change requiredness + boss: Link[Org] = OoldField(description="demonstrates field kwargs") + # optional: absence is data, declared as everywhere else in pydantic + sponsor: Link[Org] | None = None + other: Link[Org] | None = None + # to-many, three distinct statements + maybe_links: LinkList["Entity | None"] = OoldField() # an element may be absent + no_list: LinkList["Entity"] | None = None # the list itself may be absent # plain spelling: runtime-identical, but a checker only sees list[Entity] plain: list["Entity"] = OoldField() @@ -44,33 +56,59 @@ class Entity(LinkedBaseModel): # -- writes: an object, an IRI or a JSON object are all accepted ------------- written = Entity( id="ex:e1", - links=["ex:a", Entity(id="ex:b"), {"id": "ex:c"}], owner="ex:acme", + parent={"id": "ex:p"}, + links=["ex:a", Entity(id="ex:b", owner="ex:acme", parent="ex:p", links=[]), {"id": "ex:c"}], sponsor=None, ) written.links = ["ex:d", {"id": "ex:e"}] written.owner = {"id": "ex:other"} +# Writes through the Optional wrapper are checker-dependent: pyright and +# current ty apply the descriptor's __set__ through the union, so an IRI, a +# dict and an object are all accepted; the ty pinned here sees a plain +# `Link[Org] | None` slot and rejects every reference form. The probe asserts +# only the intersection - `None` at construction - and the runtime acceptance +# of the reference forms is covered by tests/test_link_notation_matrix.py. -# -- reads: exactly what was declared --------------------------------------- +# -- reads: exactly what the annotation declares ------------------------------ # A separate instance: ty narrows an attribute to the assigned type after a # write, which would otherwise mask what __get__ declares. -read = Entity(id="ex:e2") +read = Entity(id="ex:e2", owner="ex:acme", parent="ex:p", links=[]) assert_type(read.owner, Org) +assert_type(read.boss, Org) assert_type(read.links, LinkResultList[Entity]) assert_type(read.links[0], Entity) assert_type(read.links[0].name, str | None) -# the point of declaring a link mandatory: chaining needs no guard per hop +# the point of a required link: chaining needs no guard per hop assert_type(read.parent.parent.parent, Entity) assert_type(read.parent.parent.owner.name, str | None) # declared optional, so the guard is required - and warranted assert_type(read.sponsor, Org | None) -assert_type(read.maybe_links[0], Entity | None) +assert_type(read.other, Org | None) sponsor = read.sponsor if sponsor is not None: assert_type(sponsor.name, str | None) +# -- the list-access and filter columns --------------------------------------- +# element access and filters preserve the declared element type +assert_type(read.links[0:2], LinkResultList[Entity]) +assert_type(read.links[Entity.name == "x"], LinkResultList[Entity]) +assert_type(read.links["@name=='x'"], Any) # the string form ends type checking + +assert_type(read.maybe_links, LinkResultList[Entity | None]) +assert_type(read.maybe_links[0], Entity | None) +assert_type(read.maybe_links[0:2], LinkResultList[Entity | None]) +assert_type(read.maybe_links[Entity.name == "x"], LinkResultList[Entity | None]) + +# the absent-list form must be gated before any subscript +assert_type(read.no_list, LinkResultList[Entity] | None) +no_list = read.no_list +if no_list is not None: + assert_type(no_list[0], Entity) + assert_type(no_list[Entity.name == "x"], LinkResultList[Entity]) + # The plain spelling reads as declared - which is why an IRI cannot be assigned # to it statically, and why it cannot express either promise. assert_type(read.plain, list[Entity])