PEP 661: Sentinel Values

I think __bool__ is also important. Sentinels often represent “empty” values that are convenient to handle as falsy, e.g.
def f(value: List | None | Unknown): return value or []. Something like Unknown = sentinel("Unknown", bool=False) would be very useful and convenient.

Use case example
NoAnswer = sentinel("NoAnswer", False)

@dataclass
class ClientSurveyResponse:
    interesting_items: List[Item] | None | NoAnswer = NoAnswer
    # None = no particular preference, [] = interested in nothing
    ...
    
    def items_proposable_to_client(self):
        return [item for item in self.interesting_items or [] if item in inventory]

The alternative is type(Unknown).__bool__ = lambda self: False, but it appears to me that “empty” sentinels are extremely common – the overwhelming majority even, based on this list. Perhaps it should be the default.


P.S. how about the auto-naming syntax from the PyPI’s sentinel package? Something like

MySentinel = sentinel.create()
print(MySentinel)  # prints `MySentinel`
7 Likes