Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Do not require validate_assignment to use Field.frozen #7103

Merged
merged 8 commits into from Aug 15, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
7 changes: 2 additions & 5 deletions docs/errors/validation_errors.md
Expand Up @@ -606,18 +606,15 @@ except ValidationError as exc:

## `frozen_field`

This error is raised when `model_config['validate_assignment'] == True` and you attempt to assign
a value to a field with `frozen=True`:
This error is raised when you attempt to assign a value to a field with `frozen=True`:

```py
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from pydantic import BaseModel, Field, ValidationError


class Model(BaseModel):
x: str = Field('test', frozen=True)

model_config = ConfigDict(validate_assignment=True)


model = Model()
try:
Expand Down
12 changes: 3 additions & 9 deletions docs/usage/fields.md
Expand Up @@ -623,20 +623,18 @@ assigned a new value after the model is created (immutability).
See the [frozen dataclass documentation] for more details.

```py
from pydantic import BaseModel, ConfigDict, Field, ValidationError
from pydantic import BaseModel, Field, ValidationError


class User(BaseModel):
model_config = ConfigDict(validate_assignment=True) # (1)!

name: str = Field(frozen=True)
age: int


user = User(name='John', age=42)

try:
user.name = 'Jane' # (2)!
user.name = 'Jane' # (1)!
except ValidationError as e:
print(e)
"""
Expand All @@ -646,11 +644,7 @@ except ValidationError as e:
"""
```

1. The `model_config` field is used to enable the validation of assignments.

See the [Validate Assignment] section for more details.

2. Since `validate_assignment` is enabled, and the `name` field is frozen, the assignment is not allowed.
1. Since `name` field is frozen, the assignment is not allowed.

## Exclude

Expand Down
7 changes: 7 additions & 0 deletions pydantic/main.py
Expand Up @@ -748,6 +748,13 @@ def __setattr__(self, name: str, value: Any) -> None:
'input': value,
}
raise pydantic_core.ValidationError.from_exception_data(self.__class__.__name__, [error])
elif getattr(self.model_fields.get(name), 'frozen', False):
error: pydantic_core.InitErrorDetails = {
'type': 'frozen_field',
'loc': (name,),
'input': value,
}
raise pydantic_core.ValidationError.from_exception_data(self.__class__.__name__, [error])

attr = getattr(self.__class__, name, None)
if isinstance(attr, property):
Expand Down
15 changes: 14 additions & 1 deletion tests/test_main.py
Expand Up @@ -503,6 +503,19 @@ class FrozenModel(BaseModel):
]


def test_frozen_field():
class FrozenModel(BaseModel):
a: int = Field(10, frozen=True)

m = FrozenModel()

with pytest.raises(ValidationError) as exc_info:
m.a = 11
assert exc_info.value.errors(include_url=False) == [
{'type': 'frozen_field', 'loc': ('a',), 'msg': 'Field is frozen', 'input': 11}
]


def test_not_frozen_are_not_hashable():
class TestModel(BaseModel):
a: int = 10
Expand Down Expand Up @@ -1660,7 +1673,7 @@ class M(BaseModel):
get_type_hints(type(M.model_config))


def test_frozen_field():
def test_frozen_field_with_validate_assignment():
"""assigning a frozen=True field should raise a TypeError"""

class Entry(BaseModel):
Expand Down