bids-specification icon indicating copy to clipboard operation
bids-specification copied to clipboard

feat: Generate context types from schema

Open effigies opened this issue 5 months ago • 2 comments

This PR follows-up #2115 by procedurally generating Python types from the schema.meta.context object. This uses structural subtyping to allow for a variety of implementations to satisfy type-checkers, while also providing default standard library dataclass implementations.

The dataclass fields are annotated with protocols instead of one another, so that you can flexibly mix-and-match the provided dataclasses and your own classes, for example:

from functools import cached_property
import json

import attrs
from bidsschematools.types import context as ctx

@attrs.define
class Dataset:
    tree: FileTree
    ignored: list[str]

    @cached_property
    def dataset_description(self) -> dict[str, Any]:
        with open(tree['dataset_description.json']) as fobj:
            return json.load(fobj)

    @cached_property
    def modalities(self) -> list[str]:
        ...

    @cached_property
    def datatypes(self) -> list[str]:
        ...

    @cached_property
    def subjects(self) -> ctx.Subjects:
        ...

Dataset is assignable to a variable annotated as bidsschematools.types.protocols.Dataset, but not bidsschematools.types.context.Dataset.

Protocols doc: https://bidsschematools--2133.org.readthedocs.build/en/2133/api/bidsschematools.types.protocols.html Dataclasses doc: https://bidsschematools--2133.org.readthedocs.build/en/2133/api/bidsschematools.types.context.html

As with #2115, the goal here is to remain dynamic in editable installation mode, constructing and execing the module on-the-fly, while freezing a copy for optimal loading when performing full installations or building packages.

effigies avatar Jun 07 '25 15:06 effigies

Documentation here: https://bidsschematools--2133.org.readthedocs.build/en/2133/api/bidsschematools.types.context.html

image

effigies avatar Jun 07 '25 16:06 effigies

@ubdbra001 Just a heads up on this. This is going to replace much of https://github.com/bids-standard/python-validator/pull/24, which will instead do something like what I have above.

effigies avatar Jun 11 '25 04:06 effigies