How to get Pydantic model types?

Question:

Consider the following model:

from pydantic import BaseModel

class Cirle(BaseModel):
    radius: int
    pi = 3.14

If I run the following code, I can see the fields of this model:

print(Circle.__fields__)

# Output:

{
  'radius': ModelField(name='radius', type=int, required=True), 
  'pi': ModelField(name='pi', type=float, required=False, default=3.14)
}

The question is: how can I get the type (or inferred type hint) from the ModelField type? These all give errors:

Circle.__fields__['pi'].type
# AttributeError: 'ModelField' object has no attribute 'type'

Circle.__fields__['pi'].__dict__
# AttributeError: 'ModelField' object has no attribute '__dict__'

type(Circle.__fields__['pi'])
# <class 'pydantic.fields.ModelField'>

import typing
typing.get_type_hints(Circle.__fields__['pi'])
# TypeError: ModelField(name='pi', type=float, required=False, default=3.14)
# is not a module, class, method, or function.

typing.get_type_hints(Circle)
# This does not include the "pi" field because it has no type hints
# {'radius': <class 'int'>}

I don’t even see where the ModelField type is defined in github.

How can I iterate over the fields of a pydantic model and find the types?

Asked By: poundifdef

||

Answers:

You can use the type_ variable of the pydantic fields. The variable is masked with an underscore to prevent collision with the Python internal type keyword.

from pydantic import BaseModel

class Cirle(BaseModel):
    radius: int
    pi = 3.14

for key, value in Cirle.__fields__.items():
    print(key, value.type_)

# Output:
# radius <class 'int'>
# pi <class 'float'>
Answered By: Georg Stricker
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.