8000 gh-91330: Tests and docs for dataclass descriptor-typed fields by debonte · Pull Request #94424 · python/cpython · GitHub
[go: up one dir, main page]

Skip to content

gh-91330: Tests and docs for dataclass descriptor-typed fields #94424

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 10 commits into from
Jul 5, 2022
Prev Previous commit
Next Next commit
Add tests for uninitialized field and default value
  • Loading branch information
debonte committed Jun 28, 2022
commit 1ea97fab603cd439f36ae6bd683128ef51e4c984
41 changes: 41 additions & 0 deletions Lib/test/test_dataclasses.py
Original file line number Diff line number Diff line change
Expand Up @@ -3279,6 +3279,47 @@ class C:
c.i = 10
self.assertEqual(D.__set__.call_count, 1)

def test_setting_uninitialized_descriptor_field(self):
class D:
pass

D.__set__ = Mock()

@dataclass
class C:
i: D

# D.__set__ is not called because there's no D instance to call it on
D.__set__.reset_mock()
c = C(5)
self.assertEqual(D.__set__.call_count, 0)

# D.__set__ still isn't called after setting i to an instance of D
# because descriptors don't behave like that when stored as instance vars
c.i = D()
c.i = 5
self.assertEqual(D.__set__.call_count, 0)

def test_default_value(self):
class D:
def __get__(self, instance: Any, owner: object) -> int:
if instance is None:
return 100
return instance._x

def __set__(self, instance: Any, value: int) -> None:
instance._x = value

@dataclass
class C:
i: D = D()

c = C()
self.assertEqual(c.i, 100)

c = C(5)
self.assertEqual(c.i, 5)

class TestStringAnnotations(unittest.TestCase):
def test_classvar(self):
# Some expressions recognized as ClassVar really aren't. But
Expand Down
0