Sentinels Library

1.1.1 · active · verified Thu Apr 09

The `sentinels` module is a small utility providing a `Sentinel` class, along with useful instances for creating unique singleton objects. These objects serve as special markers, often used as default values for function arguments or to denote the absence of a value, especially when `None` is a valid input. The current version is 1.1.1, and it appears to be actively maintained with a recent release in August 2025.

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to use the pre-defined `NOTHING` sentinel for dictionary operations where `None` is a valid value, and how to create a custom sentinel using the `Sentinel` class. It highlights the use of `is` for comparison, a key characteristic of sentinel objects.

from sentinels import NOTHING, Sentinel

class MyDict(dict):
    def get_default_or_raise(self, key, default=NOTHING):
        returned = self.get(key, default)
        if returned is NOTHING:
            raise KeyError(key)
        return returned

# Example usage:
d = MyDict({"valid_none": None, "valid_zero": 0})

# Key exists with a valid None value
print(f"'valid_none' value: {d.get_default_or_raise('valid_none', default=None)}")

# Key exists with a valid zero value
print(f"'valid_zero' value: {d.get_default_or_raise('valid_zero')}")

# Key does not exist, uses NOTHING as default, raises KeyError
try:
    d.get_default_or_raise("non_existent_key")
except KeyError as e:
    print(f"Caught expected error: {e}")

# Create a custom sentinel
MISSING_VALUE = Sentinel('MISSING_VALUE')
def my_function(arg=MISSING_VALUE):
    if arg is MISSING_VALUE:
        print("Argument was not provided.")
    else:
        print(f"Argument provided: {arg}")

my_function()
my_function("hello")

view raw JSON →