Skip to content

[3.13] gh-89683: add tests for deepcopy on frozen dataclasses (GH-123098) #124678

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

Merged
Merged
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
43 changes: 43 additions & 0 deletions Lib/test/test_dataclasses/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@
from typing import ClassVar, Any, List, Union, Tuple, Dict, Generic, TypeVar, Optional, Protocol, DefaultDict
from typing import get_type_hints
from collections import deque, OrderedDict, namedtuple, defaultdict
from copy import deepcopy
from functools import total_ordering

import typing # Needed for the string "typing.ClassVar[int]" to work as an annotation.
Expand Down Expand Up @@ -3175,6 +3176,48 @@ class C:
with self.assertRaisesRegex(TypeError, 'unhashable type'):
hash(C({}))

def test_frozen_deepcopy_without_slots(self):
# see: https://github.com/python/cpython/issues/89683
@dataclass(frozen=True, slots=False)
class C:
s: str

c = C('hello')
self.assertEqual(deepcopy(c), c)

def test_frozen_deepcopy_with_slots(self):
# see: https://github.com/python/cpython/issues/89683
with self.subTest('generated __slots__'):
@dataclass(frozen=True, slots=True)
class C:
s: str

c = C('hello')
self.assertEqual(deepcopy(c), c)

with self.subTest('user-defined __slots__ and no __{get,set}state__'):
@dataclass(frozen=True, slots=False)
class C:
__slots__ = ('s',)
s: str

# with user-defined slots, __getstate__ and __setstate__ are not
# automatically added, hence the error
err = r"^cannot\ assign\ to\ field\ 's'$"
self.assertRaisesRegex(FrozenInstanceError, err, deepcopy, C(''))

with self.subTest('user-defined __slots__ and __{get,set}state__'):
@dataclass(frozen=True, slots=False)
class C:
__slots__ = ('s',)
__getstate__ = dataclasses._dataclass_getstate
__setstate__ = dataclasses._dataclass_setstate

s: str

c = C('hello')
self.assertEqual(deepcopy(c), c)


class TestSlots(unittest.TestCase):
def test_simple(self):
Expand Down
Loading