https://github.com/python/cpython/commit/08218030a507b2ef38db9696216bf3eb24d9a6a1
commit: 08218030a507b2ef38db9696216bf3eb24d9a6a1
branch: main
author: Jelle Zijlstra <[email protected]>
committer: JelleZijlstra <[email protected]>
date: 2026-05-19T09:18:56-07:00
summary:

gh-148829: Make sentinels' repr and module customizable (#149654)

Implementation of python/peps#4968; still needs SC approval.

files:
A 
Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-16-43-50.gh-issue-148829.gscS14.rst
M Doc/c-api/sentinel.rst
M Doc/data/refcounts.dat
M Doc/library/functions.rst
M Include/cpython/sentinelobject.h
M Include/internal/pycore_global_objects_fini_generated.h
M Include/internal/pycore_global_strings.h
M Include/internal/pycore_runtime_init_generated.h
M Include/internal/pycore_unicodeobject_generated.h
M Lib/test/test_builtin.py
M Lib/test/test_capi/test_object.py
M Modules/_testcapi/object.c
M Objects/clinic/sentinelobject.c.h
M Objects/sentinelobject.c

diff --git a/Doc/c-api/sentinel.rst b/Doc/c-api/sentinel.rst
index 937cae18e86f50..b1b7329a5d42c5 100644
--- a/Doc/c-api/sentinel.rst
+++ b/Doc/c-api/sentinel.rst
@@ -31,12 +31,12 @@ Sentinel objects
 
    .. versionadded:: 3.15
 
-.. c:function:: PyObject* PySentinel_New(const char *name, const char 
*module_name)
+.. c:function:: PyObject* PySentinel_New(const char *name, const char 
*module_name, const char *repr)
 
    Return a new :class:`sentinel` object with :attr:`~sentinel.__name__` set to
    *name* and :attr:`~sentinel.__module__` set to *module_name*.
    *name* must not be ``NULL``. If *module_name* is ``NULL``, 
:attr:`~sentinel.__module__`
-   is set to ``None``.
+   is set to ``None``. If *repr* is ``NULL``, ``repr()`` returns 
:attr:`~sentinel.__name__`.
    Return ``NULL`` with an exception set on failure.
 
    For pickling to work, *module_name* must be the name of an importable
diff --git a/Doc/data/refcounts.dat b/Doc/data/refcounts.dat
index 663b79e45eec17..60c02aabeb89c5 100644
--- a/Doc/data/refcounts.dat
+++ b/Doc/data/refcounts.dat
@@ -2040,6 +2040,7 @@ PySeqIter_New:PyObject*:seq:0:
 PySentinel_New:PyObject*::+1:
 PySentinel_New:const char*:name::
 PySentinel_New:const char*:module_name::
+PySentinel_New:const char*:repr::
 
 PySequence_Check:int:::
 PySequence_Check:PyObject*:o:0:
diff --git a/Doc/library/functions.rst b/Doc/library/functions.rst
index 1fed142d81b4f7..0393e2dc776db4 100644
--- a/Doc/library/functions.rst
+++ b/Doc/library/functions.rst
@@ -1827,15 +1827,21 @@ are always available.  They are listed here in 
alphabetical order.
       :func:`setattr`.
 
 
-.. class:: sentinel(name, /)
+.. class:: sentinel(name, /, *, repr=None)
 
    Return a new unique sentinel object.  *name* must be a :class:`str`, and is
-   used as the returned object's representation::
+   used by default as the returned object's representation::
 
       >>> MISSING = sentinel("MISSING")
       >>> MISSING
       MISSING
 
+   The optional *repr* argument can be used to specify a different 
representation::
+
+      >>> MISSING = sentinel("MISSING", repr="<MISSING>")
+      >>> MISSING
+      <MISSING>
+
    Sentinel objects are truthy and compare equal only to themselves.  They are
    intended to be compared with the :keyword:`is` operator.
 
@@ -1879,7 +1885,7 @@ are always available.  They are listed here in 
alphabetical order.
 
    .. attribute:: __module__
 
-      The name of the module where the sentinel was created.
+      The name of the module where the sentinel was created. This attribute is 
writable.
 
    .. versionadded:: 3.15
 
diff --git a/Include/cpython/sentinelobject.h b/Include/cpython/sentinelobject.h
index 15643ef966af86..e621d6abbfed8a 100644
--- a/Include/cpython/sentinelobject.h
+++ b/Include/cpython/sentinelobject.h
@@ -16,7 +16,8 @@ PyAPI_DATA(PyTypeObject) PySentinel_Type;
 
 PyAPI_FUNC(PyObject *) PySentinel_New(
     const char *name,
-    const char *module_name);
+    const char *module_name,
+    const char *repr);
 
 #ifdef __cplusplus
 }
diff --git a/Include/internal/pycore_global_objects_fini_generated.h 
b/Include/internal/pycore_global_objects_fini_generated.h
index 7e6107e54a0ab6..99a1ffb8ad5229 100644
--- a/Include/internal/pycore_global_objects_fini_generated.h
+++ b/Include/internal/pycore_global_objects_fini_generated.h
@@ -2032,6 +2032,7 @@ _PyStaticObjects_CheckRefcnt(PyInterpreterState *interp) {
     _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(repeat));
     _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(repl));
     _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(replace));
+    _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(repr));
     _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(reqrefs));
     _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(require_ready));
     _PyStaticObject_CheckRefcnt((PyObject *)&_Py_ID(reserved));
diff --git a/Include/internal/pycore_global_strings.h 
b/Include/internal/pycore_global_strings.h
index e0b05dde8fa377..d5818402a508cb 100644
--- a/Include/internal/pycore_global_strings.h
+++ b/Include/internal/pycore_global_strings.h
@@ -755,6 +755,7 @@ struct _Py_global_strings {
         STRUCT_FOR_ID(repeat)
         STRUCT_FOR_ID(repl)
         STRUCT_FOR_ID(replace)
+        STRUCT_FOR_ID(repr)
         STRUCT_FOR_ID(reqrefs)
         STRUCT_FOR_ID(require_ready)
         STRUCT_FOR_ID(reserved)
diff --git a/Include/internal/pycore_runtime_init_generated.h 
b/Include/internal/pycore_runtime_init_generated.h
index 47c6226a7d2216..8227f3fa9eedcf 100644
--- a/Include/internal/pycore_runtime_init_generated.h
+++ b/Include/internal/pycore_runtime_init_generated.h
@@ -2030,6 +2030,7 @@ extern "C" {
     INIT_ID(repeat), \
     INIT_ID(repl), \
     INIT_ID(replace), \
+    INIT_ID(repr), \
     INIT_ID(reqrefs), \
     INIT_ID(require_ready), \
     INIT_ID(reserved), \
diff --git a/Include/internal/pycore_unicodeobject_generated.h 
b/Include/internal/pycore_unicodeobject_generated.h
index acad87c5045338..cb731e9a688878 100644
--- a/Include/internal/pycore_unicodeobject_generated.h
+++ b/Include/internal/pycore_unicodeobject_generated.h
@@ -2800,6 +2800,10 @@ _PyUnicode_InitStaticStrings(PyInterpreterState *interp) 
{
     _PyUnicode_InternStatic(interp, &string);
     assert(_PyUnicode_CheckConsistency(string, 1));
     assert(PyUnicode_GET_LENGTH(string) != 1);
+    string = &_Py_ID(repr);
+    _PyUnicode_InternStatic(interp, &string);
+    assert(_PyUnicode_CheckConsistency(string, 1));
+    assert(PyUnicode_GET_LENGTH(string) != 1);
     string = &_Py_ID(reqrefs);
     _PyUnicode_InternStatic(interp, &string);
     assert(_PyUnicode_CheckConsistency(string, 1));
diff --git a/Lib/test/test_builtin.py b/Lib/test/test_builtin.py
index 81967fb8a83740..d62a3a4f17f85e 100644
--- a/Lib/test/test_builtin.py
+++ b/Lib/test/test_builtin.py
@@ -1956,16 +1956,33 @@ def test_sentinel(self):
         with self.assertRaises(TypeError):
             class SubSentinel(sentinel):
                 pass
+
+    def test_sentinel_attributes(self):
+        missing = sentinel("MISSING")
         with self.assertRaises(TypeError):
             sentinel.attribute = "value"
         with self.assertRaises(AttributeError):
-            missing.__name__ = "CHANGED"
+            missing.attribute = "value"
         with self.assertRaises(AttributeError):
-            missing.__module__ = "changed"
+            missing.__name__ = "CHANGED"
+        missing.__module__ = "changed"
+        self.assertEqual(missing.__module__, "changed")
         with self.assertRaises(AttributeError):
             del missing.__name__
+        del missing.__module__
         with self.assertRaises(AttributeError):
-            del missing.__module__
+            missing.__module__
+
+    def test_sentinel_repr(self):
+        with_repr = sentinel("WITH_REPR", repr="custom")
+        without_repr = sentinel("WITHOUT_REPR", repr=None)
+        self.assertEqual(repr(with_repr), "custom")
+        self.assertEqual(repr(without_repr), "WITHOUT_REPR")
+        self.assertEqual(str(with_repr), "custom")
+        self.assertEqual(str(without_repr), "WITHOUT_REPR")
+
+        with self.assertRaisesRegex(TypeError, "repr.*str or None"):
+            sentinel("BAD_REPR", repr=42)
 
     def test_sentinel_pickle(self):
         for proto in range(pickle.HIGHEST_PROTOCOL + 1):
diff --git a/Lib/test/test_capi/test_object.py 
b/Lib/test/test_capi/test_object.py
index e6fd068dc20d8d..e5c50902a0118d 100644
--- a/Lib/test/test_capi/test_object.py
+++ b/Lib/test/test_capi/test_object.py
@@ -82,6 +82,12 @@ def test_pysentinel_new(self):
         self.assertEqual(no_module.__name__, "NO_MODULE")
         self.assertIs(no_module.__module__, None)
 
+        with_repr = _testcapi.pysentinel_new("WITH_REPR", __name__, "custom 
repr")
+        self.assertIs(type(with_repr), sentinel)
+        self.assertEqual(with_repr.__name__, "WITH_REPR")
+        self.assertEqual(with_repr.__module__, __name__)
+        self.assertEqual(repr(with_repr), "custom repr")
+
         globals()["CAPI_SENTINEL"] = marker
         self.addCleanup(globals().pop, "CAPI_SENTINEL", None)
         self.assertIs(pickle.loads(pickle.dumps(marker)), marker)
diff --git 
a/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-16-43-50.gh-issue-148829.gscS14.rst
 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-16-43-50.gh-issue-148829.gscS14.rst
new file mode 100644
index 00000000000000..3f9b1ccb518787
--- /dev/null
+++ 
b/Misc/NEWS.d/next/Core_and_Builtins/2026-05-10-16-43-50.gh-issue-148829.gscS14.rst
@@ -0,0 +1,2 @@
+:class:`sentinel` objects now support a ``repr=`` argument and their
+:attr:`~sentinel.__module__` attribute is writable.
diff --git a/Modules/_testcapi/object.c b/Modules/_testcapi/object.c
index c62dc1144df688..09a548fd2e2448 100644
--- a/Modules/_testcapi/object.c
+++ b/Modules/_testcapi/object.c
@@ -560,10 +560,11 @@ pysentinel_new(PyObject *self, PyObject *args)
 {
     const char *name;
     const char *module_name = NULL;
-    if (!PyArg_ParseTuple(args, "s|s", &name, &module_name)) {
+    const char *repr = NULL;
+    if (!PyArg_ParseTuple(args, "s|ss", &name, &module_name, &repr)) {
         return NULL;
     }
-    return PySentinel_New(name, module_name);
+    return PySentinel_New(name, module_name, repr);
 }
 
 static PyObject *
diff --git a/Objects/clinic/sentinelobject.c.h 
b/Objects/clinic/sentinelobject.c.h
index 51fd35a5979e31..f8503194ae5c74 100644
--- a/Objects/clinic/sentinelobject.c.h
+++ b/Objects/clinic/sentinelobject.c.h
@@ -2,33 +2,71 @@
 preserve
 [clinic start generated code]*/
 
-#include "pycore_modsupport.h"    // _PyArg_CheckPositional()
+#if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+#  include "pycore_gc.h"          // PyGC_Head
+#  include "pycore_runtime.h"     // _Py_ID()
+#endif
+#include "pycore_modsupport.h"    // _PyArg_UnpackKeywords()
 
 static PyObject *
-sentinel_new_impl(PyTypeObject *type, PyObject *name);
+sentinel_new_impl(PyTypeObject *type, PyObject *name, PyObject *repr);
 
 static PyObject *
 sentinel_new(PyTypeObject *type, PyObject *args, PyObject *kwargs)
 {
     PyObject *return_value = NULL;
-    PyTypeObject *base_tp = &PySentinel_Type;
+    #if defined(Py_BUILD_CORE) && !defined(Py_BUILD_CORE_MODULE)
+
+    #define NUM_KEYWORDS 1
+    static struct {
+        PyGC_Head _this_is_not_used;
+        PyObject_VAR_HEAD
+        Py_hash_t ob_hash;
+        PyObject *ob_item[NUM_KEYWORDS];
+    } _kwtuple = {
+        .ob_base = PyVarObject_HEAD_INIT(&PyTuple_Type, NUM_KEYWORDS)
+        .ob_hash = -1,
+        .ob_item = { &_Py_ID(repr), },
+    };
+    #undef NUM_KEYWORDS
+    #define KWTUPLE (&_kwtuple.ob_base.ob_base)
+
+    #else  // !Py_BUILD_CORE
+    #  define KWTUPLE NULL
+    #endif  // !Py_BUILD_CORE
+
+    static const char * const _keywords[] = {"", "repr", NULL};
+    static _PyArg_Parser _parser = {
+        .keywords = _keywords,
+        .fname = "sentinel",
+        .kwtuple = KWTUPLE,
+    };
+    #undef KWTUPLE
+    PyObject *argsbuf[2];
+    PyObject * const *fastargs;
+    Py_ssize_t nargs = PyTuple_GET_SIZE(args);
+    Py_ssize_t noptargs = nargs + (kwargs ? PyDict_GET_SIZE(kwargs) : 0) - 1;
     PyObject *name;
+    PyObject *repr = Py_None;
 
-    if ((type == base_tp || type->tp_init == base_tp->tp_init) &&
-        !_PyArg_NoKeywords("sentinel", kwargs)) {
+    fastargs = _PyArg_UnpackKeywords(_PyTuple_CAST(args)->ob_item, nargs, 
kwargs, NULL, &_parser,
+            /*minpos*/ 1, /*maxpos*/ 1, /*minkw*/ 0, /*varpos*/ 0, argsbuf);
+    if (!fastargs) {
         goto exit;
     }
-    if (!_PyArg_CheckPositional("sentinel", PyTuple_GET_SIZE(args), 1, 1)) {
+    if (!PyUnicode_Check(fastargs[0])) {
+        _PyArg_BadArgument("sentinel", "argument 1", "str", fastargs[0]);
         goto exit;
     }
-    if (!PyUnicode_Check(PyTuple_GET_ITEM(args, 0))) {
-        _PyArg_BadArgument("sentinel", "argument 1", "str", 
PyTuple_GET_ITEM(args, 0));
-        goto exit;
+    name = fastargs[0];
+    if (!noptargs) {
+        goto skip_optional_kwonly;
     }
-    name = PyTuple_GET_ITEM(args, 0);
-    return_value = sentinel_new_impl(type, name);
+    repr = fastargs[1];
+skip_optional_kwonly:
+    return_value = sentinel_new_impl(type, name, repr);
 
 exit:
     return return_value;
 }
-/*[clinic end generated code: output=7f28fc0bf0259cba input=a9049054013a1b77]*/
+/*[clinic end generated code: output=958842ece254c82f input=a9049054013a1b77]*/
diff --git a/Objects/sentinelobject.c b/Objects/sentinelobject.c
index e7e9f60e3edfbe..77bffbc397be58 100644
--- a/Objects/sentinelobject.c
+++ b/Objects/sentinelobject.c
@@ -14,6 +14,7 @@ typedef struct {
     PyObject_HEAD
     PyObject *name;
     PyObject *module;
+    PyObject *repr;
 } sentinelobject;
 
 #define sentinelobject_CAST(op) \
@@ -46,7 +47,7 @@ caller(void)
 }
 
 static PyObject *
-sentinel_new_with_module(PyTypeObject *type, PyObject *name, PyObject *module)
+sentinel_new_with_module(PyTypeObject *type, PyObject *name, PyObject *module, 
PyObject *repr)
 {
     assert(PyUnicode_Check(name));
 
@@ -56,6 +57,7 @@ sentinel_new_with_module(PyTypeObject *type, PyObject *name, 
PyObject *module)
     }
     self->name = Py_NewRef(name);
     self->module = Py_NewRef(module);
+    self->repr = Py_XNewRef(repr);
     _PyObject_GC_TRACK(self);
     return (PyObject *)self;
 }
@@ -66,37 +68,56 @@ sentinel.__new__ as sentinel_new
 
     name: object(subclass_of='&PyUnicode_Type')
     /
+    *
+    repr: object = None
 [clinic start generated code]*/
 
 static PyObject *
-sentinel_new_impl(PyTypeObject *type, PyObject *name)
-/*[clinic end generated code: output=4af55c6048bed30d input=3ab75704f39c119c]*/
+sentinel_new_impl(PyTypeObject *type, PyObject *name, PyObject *repr)
+/*[clinic end generated code: output=1eb7fab52e57d8c8 input=28cab6c468997b35]*/
 {
+    if (repr == Py_None) {
+        repr = NULL;
+    }
+    else if (!PyUnicode_Check(repr)) {
+        _PyArg_BadArgument("sentinel", "argument 'repr'", "str or None", repr);
+        return NULL;
+    }
     PyObject *module = caller();
-    PyObject *self = sentinel_new_with_module(type, name, module);
+    PyObject *self = sentinel_new_with_module(type, name, module, repr);
     Py_DECREF(module);
     return self;
 }
 
 PyObject *
-PySentinel_New(const char *name, const char *module_name)
+PySentinel_New(const char *name, const char *module_name, const char *repr)
 {
     PyObject *name_obj = PyUnicode_FromString(name);
     if (name_obj == NULL) {
         return NULL;
     }
+    PyObject *repr_obj = NULL;
+    if (repr != NULL) {
+        repr_obj = PyUnicode_FromString(repr);
+        if (repr_obj == NULL) {
+            Py_DECREF(name_obj);
+            return NULL;
+        }
+    }
     PyObject *module_obj = module_name == NULL
         ? Py_None
         : PyUnicode_FromString(module_name);
     if (module_obj == NULL) {
         Py_DECREF(name_obj);
+        Py_XDECREF(repr_obj);
         return NULL;
     }
 
     PyObject *sentinel = sentinel_new_with_module(
-        &PySentinel_Type, name_obj, module_obj);
+        &PySentinel_Type, name_obj, module_obj, repr_obj);
     Py_DECREF(module_obj);
     Py_DECREF(name_obj);
+    Py_XDECREF(repr_obj);
     return sentinel;
 }
 
@@ -106,6 +127,7 @@ sentinel_clear(PyObject *op)
     sentinelobject *self = sentinelobject_CAST(op);
     Py_CLEAR(self->name);
     Py_CLEAR(self->module);
+    Py_CLEAR(self->repr);
     return 0;
 }
 
@@ -123,6 +145,7 @@ sentinel_traverse(PyObject *op, visitproc visit, void *arg)
     sentinelobject *self = sentinelobject_CAST(op);
     Py_VISIT(self->name);
     Py_VISIT(self->module);
+    Py_VISIT(self->repr);
     return 0;
 }
 
@@ -130,6 +153,9 @@ static PyObject *
 sentinel_repr(PyObject *op)
 {
     sentinelobject *self = sentinelobject_CAST(op);
+    if (self->repr != NULL) {
+        return Py_NewRef(self->repr);
+    }
     return Py_NewRef(self->name);
 }
 
@@ -161,7 +187,7 @@ static PyMethodDef sentinel_methods[] = {
 
 static PyMemberDef sentinel_members[] = {
     {"__name__", Py_T_OBJECT_EX, offsetof(sentinelobject, name), Py_READONLY},
-    {"__module__", Py_T_OBJECT_EX, offsetof(sentinelobject, module), 
Py_READONLY},
+    {"__module__", Py_T_OBJECT_EX, offsetof(sentinelobject, module), 0},
     {NULL}
 };
 
@@ -170,7 +196,7 @@ static PyNumberMethods sentinel_as_number = {
 };
 
 PyDoc_STRVAR(sentinel_doc,
-"sentinel(name, /)\n"
+"sentinel(name, /, *, repr=None)\n"
 "--\n\n"
 "Create a unique sentinel object with the given name.");
 

_______________________________________________
Python-checkins mailing list -- [email protected]
To unsubscribe send an email to [email protected]
https://mail.python.org/mailman3//lists/python-checkins.python.org
Member address: [email protected]

Reply via email to