1

I am trying to write a generic class that takes a pydantic model type, however the model can only have string fields. So i am trying to verify this at runtime.

I looked and found this answer, but it does not seem to work in v2 as the FieldInfo type that is returned as the values of the dict from model_info does not have a type_ property.

1 Answer 1

0

Solution is to use field.annotation (see):

from pydantic import BaseModel


class MyModel(BaseModel):
    a: int
    b: str
    c: list[float]


if __name__ == "__main__":
    for field_name, field in MyModel.model_fields.items():
        print(field_name, field.annotation, type(field.annotation))

gives:

a <class 'int'> <class 'type'>
b <class 'str'> <class 'type'>
c list[float] <class 'types.GenericAlias'>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.