Skip to content

Pass pydantic.Field constraints through lt.property #186

@rwb27

Description

@rwb27

pydantic.Field accepts arguments that capture constraints. For example:

from pydantic import BaseModel, Field

class Example(BaseModel):
    less_than_ten: int = Field(lt=10)
    also_less_than_ten: Annotated[int, Field(lt=10)]

It's already possible to do this in LabThings:

import labthings_fastapi as lt
from pydantic import Field
from typing import Annotated

class Example(lt.Thing):
    less_than_ten: Annotated[int, Field(lt=10)] = lt.property(default=0)

The Thing Description for this property already includes an exclusiveMaximum property, so the metadata propagates without code changes.

Click for TD
{
  "title": "Example",
  "properties": {
    "less_than_ten": {
      "description": "This property should be less than ten.",
      "title": "This property should be less than ten.",
      "type": "integer",
      "exclusiveMaximum": 10,
      "forms": [
        {
          "href": "/example/less_than_ten",
          "op": [
            "readproperty",
            "writeproperty"
          ]
        }
      ]
    }
  },
  "actions": {

  },
  "base": "http://127.0.0.1:8000/",
  "securityDefinitions": {
    "no_security": {
      "description": "No security",
      "scheme": "nosec"
    }
  },
  "security": "no_security",
  "@context": "https://www.w3.org/2022/wot/td/v1.1"
}

It would be lovely if those constraint arguments could be passed through lt.property so we could instead use the earlier form, i.e.

import labthings_fastapi as lt
from pydantic import Field


class Example(lt.Thing):
    less_than_ten:int = lt.property(default=0, lt=10)

This may be relatively straightforward to implement.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions