Wednesday 13 October 2021

Pydantic: Define immutable models

By setting 'allow_mutation' to False, we can define immutable models.

 

immutable_models.py

from pydantic import BaseModel

class Employee(BaseModel):
    id: int
    name: str
    age: int

    class Config:
        allow_mutation = False

emp1 = Employee(id = 1, name = 'Krishna', age = 23)

print('updating employee name')
emp1.name = 'Ram'

 

Output

Traceback (most recent call last):
  File "/Users/krishna/pydantic/immutable_models.py", line 14, in <module>
    emp1.name = 'Ram'
  File "pydantic/main.py", line 424, in pydantic.main.BaseModel.__setattr__
TypeError: "Employee" is immutable and does not support item assignment

 

 

  

Previous                                                    Next                                                    Home

No comments:

Post a Comment