Skip to content

Validate constraint keys#277

Open
rwb27 wants to merge 3 commits intomainfrom
validate-constraint-keys
Open

Validate constraint keys#277
rwb27 wants to merge 3 commits intomainfrom
validate-constraint-keys

Conversation

@rwb27
Copy link
Collaborator

@rwb27 rwb27 commented Mar 3, 2026

This adds better validation and typing to BaseProperty.constraints. This should be particularly helpful for functional properties, where it's likely that this property will be accessed directly, rather than through the constructor.

I've changed the type of BaseProperty.constraints to be a TypedDict, because it should retain compatibility with existing code that assigns a (valid) dict literal while also offering type checking and autocompletion in type-aware IDEs. The first commit of this PR implements basic validation without changing any types, the next two swap to TypedDict and use pydantic to validate the dictionary at runtime. This is primarily because converting an untyped dict into a typed one is really ugly, so I'd rather use pydantic than implement my own converter. Switching validation to pydantic also means we now check the types of the constraints, which is a nice bonus.

Closes #275

rwb27 added 3 commits March 2, 2026 22:45
I've upgraded this to a property, and added basic validation to check the dictionary keys.
The `constraints` property is now a typed dictionary. Assigning dictionary literals to it still ought to work, but it should flag type errors if the keys are incorrect.

The method `BaseProperty._validate_constraints` is provided to convert untyped dictionaries with appropriate validation. This now uses `pydantic` to validate the typeddict. It is stricter than what I did before, as it also checks the type of the keys, not just their names.

Pydantic was less ugly than coming up with my own logic to coerce an untyped dictionary into a typeddict. I've added a unit test on validation to check it does what I expect.

It would be lovely to deduplicate the typeddict and the constant with key names in it - but this is hard to do neatly.
While typing has a TypedDict class from Python 3.8, pydantic requires the use of typing_extensions prior to 3.12.
@barecheck
Copy link

barecheck bot commented Mar 3, 2026

Barecheck - Code coverage report

Total: 96.55%

Your code coverage diff: 0.03% ▴

Uncovered files and lines
FileLines
src/labthings_fastapi/properties.py754, 758, 781-784, 856, 875, 1102

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

FunctionalProperty constraints are in the public api but are not validated.

1 participant