
On Thu, May 13, 2021 at 8:46 PM Eric V. Smith <eric@trueblade.com> wrote:
On 5/13/2021 1:39 PM, Tal Einat wrote:
Here is my suggestion (also posted on the related bpo-44123), which is also simple, ensures a single instance is used, even considering multi-threading and pickling, and has a better repr:
class Sentinel: def __new__(cls, *args, **kwargs): raise TypeError(f'{cls.__qualname__} cannot be instantiated')
class MISSING(Sentinel): pass
MISSING <class '__main__.MISSING'>
I think a repr of just "MISSING", or maybe "dataclasses.MISSING" would be better.
The repr uses whatever module the class is defined in, so we'd get:
from dataclasses import MISSING MISSING <class 'dataclasses.MISSING'>
We could override that to something even cleaner with a meta-class. For example: 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__}' Which results in:
from dataclasses import MISSING MISSING dataclasses.MISSING type(MISSING) <class 'sentinels.Sentinel'> MISSING() Traceback (most recent call last): ... TypeError: dataclasses.MISSING is a sentinel and cannot be instantiated
- Tal - Tal