Quantcast
Channel: User Louis Maddox - Stack Overflow
Viewing all articles
Browse latest Browse all 51

Answer by Louis Maddox for Create a field which is immutable after being set

$
0
0

You now do this (in Pydantic v2) with the Field(frozen=True) kwarg (docs)

Immutability ¶

The parameter frozen is used to emulate the [frozen dataclass]behaviour. It is used to prevent the field from being assigned a newvalue after the model is created (immutability).

See the frozen dataclass documentation for more details.

from pydantic import BaseModel, Field, ValidationErrorclass User(BaseModel):    name: str = Field(frozen=True)    age: intuser = User(name='John', age=42)try:    user.name = 'Jane'except ValidationError as e:    print(e)"""    1 validation error for User    name      Field is frozen [type=frozen_field, input_value='Jane', input_type=str]"""

Viewing all articles
Browse latest Browse all 51

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>