Implementation of python/peps#4968; still needs SC approval.
.. 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
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:
: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.
.. 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
PyAPI_FUNC(PyObject *) PySentinel_New(
const char *name,
- const char *module_name);
+ const char *module_name,
+ const char *repr);
#ifdef __cplusplus
}
_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));
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)
INIT_ID(repeat), \
INIT_ID(repl), \
INIT_ID(replace), \
+ INIT_ID(repr), \
INIT_ID(reqrefs), \
INIT_ID(require_ready), \
INIT_ID(reserved), \
_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));
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):
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)
--- /dev/null
+:class:`sentinel` objects now support a ``repr=`` argument and their
+:attr:`~sentinel.__module__` attribute is writable.
{
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 *
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]*/
PyObject_HEAD
PyObject *name;
PyObject *module;
+ PyObject *repr;
} sentinelobject;
#define sentinelobject_CAST(op) \
}
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));
}
self->name = Py_NewRef(name);
self->module = Py_NewRef(module);
+ self->repr = Py_XNewRef(repr);
_PyObject_GC_TRACK(self);
return (PyObject *)self;
}
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;
}
sentinelobject *self = sentinelobject_CAST(op);
Py_CLEAR(self->name);
Py_CLEAR(self->module);
+ Py_CLEAR(self->repr);
return 0;
}
sentinelobject *self = sentinelobject_CAST(op);
Py_VISIT(self->name);
Py_VISIT(self->module);
+ Py_VISIT(self->repr);
return 0;
}
sentinel_repr(PyObject *op)
{
sentinelobject *self = sentinelobject_CAST(op);
+ if (self->repr != NULL) {
+ return Py_NewRef(self->repr);
+ }
return Py_NewRef(self->name);
}
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}
};
};
PyDoc_STRVAR(sentinel_doc,
-"sentinel(name, /)\n"
+"sentinel(name, /, *, repr=None)\n"
"--\n\n"
"Create a unique sentinel object with the given name.");