Skip to content
Open
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
2 changes: 1 addition & 1 deletion docs/design/graph-object-binding.md
Original file line number Diff line number Diff line change
Expand Up @@ -390,7 +390,7 @@ element resolves" is a promise about dereferencing, not a document constraint.
| 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. |
| `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). |
| `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 applies `__set__` through the union; ty does not (checked on 0.0.49 and 0.0.107), so attribute writes through the wrapper type only under pyright (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. |
Expand Down
7 changes: 4 additions & 3 deletions docs/how-to/object-graph-mapping.md
Original file line number Diff line number Diff line change
Expand Up @@ -404,6 +404,7 @@ checking downstream - prefer the `Person.name == "x"` form.
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.
*write* side is checker-dependent - pyright applies the descriptor's
assignment type through the union, ty does not, so an attribute write
through the wrapper types only under pyright; pass the reference at
construction instead (read narrowing is correct everywhere).
29 changes: 24 additions & 5 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -193,7 +193,10 @@ exclude = [
# (Model["iri"], obj.links[Field == ...]). The following checks fire on these
# intentional, runtime-valid metaprogramming patterns rather than real bugs, so
# they are downgraded to keep `ty check` meaningful without mass inline ignores.
unresolved-attribute = "ignore"
# ty 0.0.107 split the old unresolved-attribute into missing-attribute and
# missing-union-attribute; both stay down for the same reason.
missing-attribute = "ignore"
missing-union-attribute = "ignore"
not-subscriptable = "ignore"
# Assigning an IRI to a link field is no longer a reason for this one: the
# Link[T] / LinkList[T] annotations type both directions, and the override below
Expand All @@ -202,16 +205,20 @@ not-subscriptable = "ignore"
invalid-argument-type = "ignore"
invalid-assignment = "ignore"
unknown-argument = "ignore"
invalid-return-type = "ignore"
invalid-explicit-return = "ignore"
unsupported-operator = "ignore"
no-matching-overload = "ignore"
invalid-method-override = "ignore"
incompatible-method-override = "ignore"
not-iterable = "ignore"
invalid-type-form = "ignore"
missing-argument = "ignore"
call-non-callable = "ignore"
not-callable = "ignore"
too-many-positional-arguments = "ignore"
subclass-of-final-class = "ignore"
# pydantic v1 models override `Config` with a narrower class on purpose - that
# is how pydantic v1 configuration works, so the override rule has nothing to
# say about it.
incompatible-attribute-override = "ignore"

[tool.pytest.ini_options]
testpaths = ["tests"]
Expand Down Expand Up @@ -333,6 +340,17 @@ skip_empty = true
branch = true
source = ["src"]

[[tool.ty.overrides]]
# The examples carry one deliberate blanket `# type: ignore` on an ungated
# optional chain (wiki_data). Under this repo's config the silenced rule is
# already off, so ty reports the directive as unused - but it is load-bearing
# for every downstream config where the rule runs, which is who examples are
# written for.
include = ["examples/**"]

[tool.ty.overrides.rules]
unused-type-ignore-comment = "ignore"

[[tool.ty.overrides]]
# The static contract of the link and query API is asserted here, so the rules
# it exercises must actually run - the repo-wide downgrades above would
Expand All @@ -342,5 +360,6 @@ include = ["tests/typing/**"]
[tool.ty.overrides.rules]
invalid-argument-type = "error"
invalid-assignment = "error"
unresolved-attribute = "error"
missing-attribute = "error"
missing-union-attribute = "error"
not-subscriptable = "error"
2 changes: 1 addition & 1 deletion scripts/check_markdown_extensions.py
Original file line number Diff line number Diff line change
Expand Up @@ -30,7 +30,7 @@
import sys

try:
import tomllib # ty: ignore[unresolved-import] # stdlib on 3.11+; ty type-checks against the 3.10 floor
import tomllib # ty: ignore[import-not-found] # stdlib on 3.11+; ty type-checks against the 3.10 floor
except ModuleNotFoundError:
sys.exit(
"This check needs Python 3.11+ for the stdlib tomllib parser (the project "
Expand Down
8 changes: 6 additions & 2 deletions src/oold/backend/document_store.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,9 @@ class SimpleDictDocumentStore(Backend):

_store: dict[str, dict] | None = None
file_path: Path | str | None = None
format: LinkedDataFormat = LinkedDataFormat.JSON
# LinkedDataFormat | None matches the base attribute: a narrower mutable
# override would reject writes the base type allows
format: LinkedDataFormat | None = LinkedDataFormat.JSON

def __init__(self, **kwargs):
super().__init__(**kwargs)
Expand Down Expand Up @@ -111,7 +113,9 @@ def query(self, param: QueryParam) -> ResolveResult:

class SqliteDocumentStore(Backend):
db_path: Path | str
format: LinkedDataFormat = LinkedDataFormat.JSON
# LinkedDataFormat | None matches the base attribute: a narrower mutable
# override would reject writes the base type allows
format: LinkedDataFormat | None = LinkedDataFormat.JSON
persist_connection: bool = False
_conn: sqlite3.Connection | None = None

Expand Down
6 changes: 4 additions & 2 deletions src/oold/model/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -686,8 +686,10 @@ def model_validate(
if node:
node_list.append(node)
return node_list
elif isinstance(obj, dict):
super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context)
# Everything else is pydantic's own job - and the result has to be
# returned: the dict branch used to call super() and fall off the end,
# so model_validate({...}) answered None on the legacy binding.
return super().model_validate(obj, strict=strict, from_attributes=from_attributes, context=context)

def __init__(self, *a, **kw):
# Accept a model instance as first positional arg:
Expand Down
8 changes: 4 additions & 4 deletions src/oold/model/v1/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -481,8 +481,8 @@ def parse_obj(cls, obj: Any) -> "_LinkedBaseModelLegacy":
if node:
node_list.append(node)
return node_list
elif isinstance(obj, dict):
return super().parse_obj(obj)
# everything else is pydantic's job; falling off the end answered None
return super().parse_obj(obj)

def __init__(self, *a, **kw):
# Accept a model instance as first positional arg:
Expand Down Expand Up @@ -989,9 +989,9 @@ def to_json(self, exclude_defaults: bool = False) -> builtins.dict:
return result

@classmethod
def from_json(cls, json_dict: builtins.dict) -> "_LinkedBaseModelLegacy":
def from_json(cls, data: builtins.dict) -> "_LinkedBaseModelLegacy":
"""Constructs a model instance from a JSON representation."""
return import_json(BaseModel, _LinkedBaseModelLegacy, cls, json_dict, _types, _controller_types)
return import_json(BaseModel, _LinkedBaseModelLegacy, cls, data, _types, _controller_types)


# Re-export BaseController from v2 module (it's a plain class, no Pydantic dep)
Expand Down
7 changes: 7 additions & 0 deletions src/oold/model/v1/_descriptor.py
Original file line number Diff line number Diff line change
Expand Up @@ -295,6 +295,13 @@ def __iris__(self) -> dict[str, Any]:
out[name] = iris
return out

@__iris__.setter
def __iris__(self, value: dict[str, Any]) -> None:
# The getter-only redefinition silently dropped the mixin's setter, so
# a direct property assignment lost writes that __setattr__'s special
# case still honoured - keep both paths on the mixin's semantics.
LinkedApiMixin.__iris__.fset(self, value)

@classmethod
def _fields(cls) -> dict:
return cls.__fields__
Expand Down
7 changes: 5 additions & 2 deletions src/oold/static.py
Original file line number Diff line number Diff line change
Expand Up @@ -226,10 +226,13 @@ def to_jsonld(self) -> dict:

@classmethod
@abstractmethod
def from_json(cls, json_dict: dict) -> "GenericLinkedBaseModel":
def from_json(cls, data: dict) -> "GenericLinkedBaseModel":
"""Constructs a model instance from a JSON representation.
Note: the given JSON must contain a field to identify the model class,
default is 'type'."""
default is 'type'.

The parameter is named ``data`` because every override names it that,
and an override must not reject a keyword the base accepts."""
pass

@abstractmethod
Expand Down
2 changes: 1 addition & 1 deletion src/oold/utils/environment.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ def is_running_in_pyodide() -> bool:

def get_ipython_source() -> str:
"""Get the source code of the running notebook."""
from IPython import get_ipython # ty: ignore[unresolved-import] # optional, only present in IPython/Jupyter
from IPython import get_ipython # ty: ignore[import-not-found] # optional, only present in IPython/Jupyter

shell = get_ipython()
if shell is None:
Expand Down
2 changes: 1 addition & 1 deletion src/oold/validation/mcp_server.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
except ImportError: # pragma: no cover - depends on the installed mcp major version
# mcp 1.x, where the same class is called FastMCP. The parts used here - the `tool`
# decorator and `run(transport=...)` - are identical across both.
from mcp.server.fastmcp import FastMCP as _Server # ty: ignore[unresolved-import]
from mcp.server.fastmcp import FastMCP as _Server # ty: ignore[import-not-found]

from .cli import SPEC_RULE_URL
from .generate import generate
Expand Down
12 changes: 6 additions & 6 deletions tests/typing/links.py
Original file line number Diff line number Diff line change
Expand Up @@ -63,12 +63,12 @@ class Entity(LinkedBaseModel):
)
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.
# Attribute writes through the Optional wrapper are pyright-only: ty does not
# apply the descriptor's __set__ inside a union (0.0.49 rejected the reference
# forms, 0.0.107 rejects every assignment including None), so the probe asserts
# the constructor direction, which both checkers type, and the runtime
# acceptance of all reference forms is covered by
# tests/test_link_notation_matrix.py.

# -- reads: exactly what the annotation declares ------------------------------
# A separate instance: ty narrows an attribute to the assigned type after a
Expand Down
Loading
Loading