Repository navigation
Description
Feature or enhancement
I propose adding an optional keyword-only doc parameter to the sentinel constructor, so that individual sentinels can have a docstring:
UNKNOWN = sentinel("UNKNOWN", doc="Represents a value that cannot be calculated.")>>> UNKNOWN.__doc__
'Represents a value that cannot be calculated.'
>>> sentinel("MISSING").__doc__ is None
TrueThe signature would then be sentinel(name, /, *, repr=None, doc=None).
Motivation
Sentinels are often part of a module's public API, but there is currently no way to attach documentation to one at runtime. Currently, __doc__ on a sentinel object is read-only and returns the __doc__ on the sentinel constructor itself:
>>> UNKNOWN = sentinel("UNKNOWN")
>>> UNKNOWN.__doc__
'Create a unique sentinel object with the given name.'
>>> UNKNOWN.__doc__ = "Represents a value that cannot be calculated."
AttributeError: 'sentinel' object attribute '__doc__' is read-onlyI originally suggested making __doc__ writable, but I now think a constructor argument is better, because:
- A string literal in the
sentinel(...)call is easy for static tools to find, for example for hover text in an IDE. - Sentinels are otherwise fixed at construction (
__name__and the repr are read-only), so having__doc__be the same makes sense. - There is precedent in
property(fget, doc=...)anddataclasses.field(doc=...).
Proposed behaviour
- Default is
None. I think there is precedence for this. (This is technically a breaking change in the sense that previously,__doc__on a sentinel object was guaranteed to be a string, and now isn't, but I hope that's okay.) __doc__is read-only on sentinel objects. Could be relaxed later.
C API
If __doc__ is read-only, there is no way to set a docstring on a sentinel created with PySentinel_New(). One could therefore add
PyObject *PySentinel_NewWithDoc(const char *name, const char *module_name,
const char *repr, const char *doc);following the naming of PyErr_NewExceptionWithDoc().
Has this already been discussed elsewhere?
I have already discussed this feature proposal on Discourse
Links to previous discussion of this feature:
https://discuss.python.org/t/make-doc-on-sentinels-writable/109067
Activity