[issue44123] make function parameter sentinel value true singletons

Tal Einat report at bugs.python.org
Thu May 13 17:09:32 EDT 2021


Tal Einat <taleinat+python at gmail.com> added the comment:

... and they can be given excellent reprs by using a meta-class:

class Sentinel(type):
    @classmethod
    def __prepare__(cls, name, bases, **kwds):
        d = super().__prepare__(name, bases, **kwds)
        def __new__(cls_, *args, **kwargs):
            raise TypeError(
                f'{cls_!r} is a sentinel and cannot be instantiated')
        d.update(__new__=__new__)
        return d

    def __repr__(cls):
        return f'{cls.__module__}.{cls.__qualname__}'


class MISSING(metaclass=Sentinel): pass


This also has another nice benefit:

>>> type(MISSING)
<class 'sentinels.Sentinel'>

----------

_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue44123>
_______________________________________


More information about the Python-bugs-list mailing list