Tal Einat <taleinat+pyt...@gmail.com> added the comment:

Here is what I suggest working with sentinels would look like:


>>> from dataclasses import MISSING
>>> MISSING
dataclasses.MISSING
>>> M2 = pickle.loads(pickle.dumps(MISSING))
>>> M2
dataclasses.MISSING
>>> M2 is MISSING
True


Here's an implementation which ensures a single instance is used, even 
considering multi-threading and pickling, which sets a nice repr according to 
the module and class name:


try:
    from threading import Lock
except ImportError:
    class Lock:
        def __enter__(self):
            pass
        def __exit__(self, exc_type, exc_value, traceback):
            pass


class Sentinel:
    _instance = None
    _lock = Lock()
    def __new__(cls):
        if cls._instance is None:
            with cls._lock:
                if cls._instance is None:
                    cls._instance = super().__new__(cls)
        return cls._instance
    def __repr__(self):
        *path_parts, classname = self.__class__.__qualname__.split('.')
        return '.'.join([self.__class__.__module__, *path_parts, 
classname.removeprefix('_')])


class _MISSING(Sentinel):
    pass
MISSING = _MISSING()

----------

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue44123>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to