Search code examples
pythonfastapipython-typingpydantic

Can't use Pydantic model attributes on type hinting


Like I used to do with FastAPI routes, I want to make a function that is expecting a dict. I want to type hint like in FastAPI with a Pydantic model.

Note that I am just using FastAPI as a reference here and this app serves a total different purpose.

What I did:

models.py

from pydantic import BaseModel

class Mymodel(BaseModel):
  name:str
  age:int

main.py

def myfunc(m:Mymodel):
  print(m)
  print(m.name)

myfunc({"name":"abcd","age":3})

It prints m as a normal dict and not Mymodel and m.name just throws an AttributeError. I don't understand why it is behaving like this because the same code would work in FastAPI. Am I missing something here? What should I do to make this work.

I am expecting a dict arg in the func, I want to type hint with a class inherited from pydantic BaseModel. Then I want to acccess the attributes of that class.

I don't want to do:

def myfunc(m):
  m = Mymodel(**m)

Thank You.


Solution

  • from pydantic import BaseModel
    from pydantic import validate_arguments
    
    class Mymodel(BaseModel):
      name:str
      age:int
    
    @validate_arguments
    def myfunc(m:Mymodel):
       print(m)
       print(m.name)
    
    myfunc({"name":"abcd","age":3})
    

    This might be what you are looking for: https://pydantic-docs.helpmanual.io/usage/validation_decorator/