Material

Sentinel Objects

One thing I find myself needing sometimes in Python is a very light-weight sentinel value. It's not very common, but when I do need it it has unique requirements. Maybe I want to signal an special condition via a return rather than exception, or I want to return a guaranteed unique key for the caller to pass back later. These often need to be hashable for speed, lightweight in memory overhead, and ideally not compare equally to any other object in the system - so integers, floats, and strings are out. I could write my own class that does nothing, but that fails the "lightweight" requirement.

Luckily, Python provides exactly what I want in the object base type used by all "new"-style classes:

a, b = object(), object()
a == b        # => True
a == b        # => False
a.foo = 1     # => AttributeError, base objects do not waste
              #    memory on instance dictionaries
{ a: 3 }      # {<object object at 0xb7ce3498>: 3}

a is guaranteed to forever be unique in the land of Python variables, and if it's initially created as a local variable, there's no way (short of poking around in the gc) for anything to get an implicit or indirect handle or equal object to it.