8000 Fix pickling of RootModel by dmontagu · Pull Request #6457 · pydantic/pydantic · GitHub
[go: up one dir, main page]

Skip to content
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.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changes/6457-dmontagu.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
Fix bug where round-trip pickling/unpickling a `RootModel` would change the value of `__dict__`.
2 changes: 1 addition & 1 deletion pydantic/main.py
Original file line number Diff line number Diff line change
Expand Up @@ -782,10 +782,10 @@ def __getstate__(self) -> dict[Any, Any]:
}

def __setstate__(self, state: dict[Any, Any]) -> None:
_object_setattr(self, '__dict__', state['__dict__'])
_object_setattr(self, '__pydantic_fields_set__', state['__pydantic_fields_set__'])
_object_setattr(self, '__pydantic_extra__', state['__pydantic_extra__'])
_object_setattr(self, '__pydantic_private__', state['__pydantic_private__'])
_object_setattr(self, '__dict__', state['__dict__'])

def __eq__(self, other: Any) -> bool:
if isinstance(other, BaseModel):
Expand Down
13 changes: 13 additions & 0 deletions tests/test_root_model.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import pickle
from typing import Any, Dict, List, Optional, Union

import pytest
Expand Down Expand Up @@ -548,3 +549,15 @@ class BModel(BaseModel):
match='"RootModel.__init__" accepts either a single positional argument or arbitrary keyword arguments',
):
Model({'value': 42}, other_value='abc')


def test_pickle_root_model(create_module):
@create_module
def module():
from pydantic import RootModel

class MyRootModel(RootModel[str]):
pass

MyRootModel = module.MyRootModel
assert MyRootModel(root='abc') == pickle.loads(pickle.dumps(MyRootModel(root='abc')))
0