Search code examples
pythonvalidationpydantic

How can I generate a UUID in a Pydantic BaseModel subclass?


My code looks a bit like this:

class Error(BaseModel):
     id: uuid.UUID
     code: int

     def __init__(self, code: int) -> None:
        self.id = uuid.uuid4()
        self.code = code

        super().__init__(id=self.id, code=code)

This errors out with:

AttributeError: 'Error' object has no attribute 'pydantic_fields_set'

I just don't want to have the boilerplate of generating the UUID each time I create a new Error(), plus... it should be the Error class' responsibility to instantiate its own UUID.

I'm not sure what I'm doing wrong.


Solution

  • Use Field(default_factory=...):

    import uuid
    
    import pydantic
    
    
    class Error(pydantic.BaseModel):
        id: uuid.UUID = pydantic.Field(default_factory=uuid.uuid4)
        code: int
    
    
    print(Error(code=123))
    print(Error(code=456))
    

    prints out

    id=UUID('dfe3052b-e8bc-4c8b-9f45-d51d2c8c412c') code=123
    id=UUID('b66ba637-6734-47cf-aa91-540306918efe') code=456