]> git.ipfire.org Git - thirdparty/Python/cpython.git/commitdiff
gh-149083: Convert dataclasses.MISSING and dataclasses.KW_ONLY to sentinels (#149086)
authorJelle Zijlstra <jelle.zijlstra@gmail.com>
Thu, 30 Apr 2026 02:39:29 +0000 (19:39 -0700)
committerGitHub <noreply@github.com>
Thu, 30 Apr 2026 02:39:29 +0000 (19:39 -0700)
There were comments claiming these were implemented as custom classes to give a nicer
repr(), but the repr() wasn't all that nice:

>>> repr(dataclasses.MISSING)
'<dataclasses._MISSING_TYPE object at 0x1005e7e00>'
>>> repr(dataclasses.KW_ONLY)
'<dataclasses._KW_ONLY_TYPE object at 0x100884050>'

Sentinels are conceptually the right tool for these, so let's use them.

This does change the repr() of these two objects.

Lib/dataclasses.py
Lib/test/test_dataclasses/__init__.py
Misc/NEWS.d/next/Library/2026-04-27-20-15-54.gh-issue-149083.BdrpU8.rst [new file with mode: 0644]

index df192763c5bd15a8595b17211bc9d4544bd620d0..e9810d6bd5d57b36fe52c61a32fdf4fcbfb42450 100644 (file)
@@ -178,17 +178,12 @@ class _HAS_DEFAULT_FACTORY_CLASS:
         return '<factory>'
 _HAS_DEFAULT_FACTORY = _HAS_DEFAULT_FACTORY_CLASS()
 
-# A sentinel object to detect if a parameter is supplied or not.  Use
-# a class to give it a better repr.
-class _MISSING_TYPE:
-    pass
-MISSING = _MISSING_TYPE()
+# A sentinel object to detect if a parameter is supplied or not.
+MISSING = sentinel("MISSING")
 
 # A sentinel object to indicate that following fields are keyword-only by
-# default.  Use a class to give it a better repr.
-class _KW_ONLY_TYPE:
-    pass
-KW_ONLY = _KW_ONLY_TYPE()
+# default.
+KW_ONLY = sentinel("KW_ONLY")
 
 # Since most per-field metadata will be unused, create an empty
 # read-only dictionary that can be shared among all fields.
index 5eec9e23cd414b62921a813d16325f192fcdc438..8a0a7d12c04aa4adfd2a6c8a9836fe188374199a 100644 (file)
@@ -995,7 +995,7 @@ class TestCase(unittest.TestCase):
         self.assertNotIn('x', D.__dict__)
 
     def test_missing_repr(self):
-        self.assertIn('MISSING_TYPE object', repr(MISSING))
+        self.assertEqual(repr(MISSING), 'MISSING')
 
     def test_dont_include_other_annotations(self):
         @dataclass
diff --git a/Misc/NEWS.d/next/Library/2026-04-27-20-15-54.gh-issue-149083.BdrpU8.rst b/Misc/NEWS.d/next/Library/2026-04-27-20-15-54.gh-issue-149083.BdrpU8.rst
new file mode 100644 (file)
index 0000000..7ad8161
--- /dev/null
@@ -0,0 +1,2 @@
+:data:`dataclasses.MISSING` and :data:`dataclasses.KW_ONLY` are now
+instances of :class:`sentinel`.