[New-bugs-announce] [issue44123] make function parameter sentinel value true singletons

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

New submission from Tal Einat <taleinat+python at gmail.com>:

I recently noticed that some functions use sentinel values to differentiate between not having been passed any value vs. None. One example of this is traceback.print_exception(), hence I'm adding Irit to the nosy list.

However, using e.g. `sentinel = object()` or a single instance of a dedicated class/type can break when combined with pickling (see examples below).

Since these sentinel are usually compared using the `is` operator, having more than a single instance will break things, sometimes in very confusing ways.

I suggest ensuring that a single instance is always used, probably by using a class with a __new__() method making sure to always return a single instance.

>>> sentinel = object()
>>> sentinel2 = pickle.loads(pickle.dumps(sentinel))
>>> sentinel is sentinel2
>>> sentinel
<object object at 0x7fd00a986560>
>>> sentinel2
<object object at 0x7fd00a986500>

>>> class A:
...     pass
>>> a = A()
>>> a2 = pickle.loads(pickle.dumps(a))
>>> a is a2
>>> a
<__main__.A object at 0x7fd00a9972f0>
>>> a2
<__main__.A object at 0x7fd009599450>

components: Library (Lib)
messages: 393580
nosy: iritkatriel, taleinat
priority: normal
severity: normal
status: open
title: make function parameter sentinel value true singletons
type: behavior
versions: Python 3.10, Python 3.11

Python tracker <report at bugs.python.org>

More information about the New-bugs-announce mailing list