Quantcast
Viewing all articles
Browse latest Browse all 14011

How to make pydantic class fields immutable?

I am trying to create a pydantic class with Immutable class fields (not instance fields).

Here is my base code:

from pydantic import BaseModelclass ImmutableModel(BaseModel):    _name: str = "My Name"    _age: int = 25ImmutableModel._age = 26print("Class variables:")print(f"Name: {ImmutableModel._name}")print(f"Age: {ImmutableModel._age}")

Output:

Class variables:Name: My NameAge: 26

I tried using the Config class inside my ImmutableModel to make fields immutable. But it seems like it only works for instance class fields.

class Config:    allow_mutation = False

FYI, I use Python 3.6.13 and pydantic==1.9.2


Viewing all articles
Browse latest Browse all 14011

Trending Articles