I would like to add some metadata to model fields. This is not necessary for validation or serialisation but might be user for data display or perhaps as a hint when entering data.
For instance one might want to add a unit to a field.
I came up with this:
from pydantic import BaseModel, Field
from typing import Annotated
from dataclasses import dataclass
@dataclass
class MyFieldMetadata:
unit: str
class MyModel(BaseModel):
length: Annotated[float, Field(gte=0.0), MyFieldMetadata(unit="meter")]
duration: Annotated[float, Field(gte=0.0), MyFieldMetadata(unit="seconds")]
and in order to print all fields with the unit postfixed:
m = MyModel(length=10.0, duration=60.0)
for field_name, field_info in m.model_fields.items():
extra_info = next(
(m for m in field_info.metadata if isinstance(m, MyFieldMetadata)), None
)
print(
f"{field_name}: {getattr(m, field_name)} {extra_info.unit if extra_info else ''}"
)
This works, but the question is if this is correct?
And the second question: The way to retrieve MyFieldMetadata from the model seems a convoluted (iterating through meta_data and finding the first instance of MyFieldMetadata). Is there a cleaner or standard way to achieve this?
I’m using pydantic 2.7.1