Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading