Let’s say we want to create a function with an optional parameter that distinguishes between None
as a value and the genuine absence of a value. A solution is to create a unique object with object()
and check the identity of the argument with the is
operator.
Since the object()
function returns a new featureless object every time it is called, we can use it to create unique dummy values – or sentinel values.
Example:
MISSING = object()
def func(arg=MISSING):
if arg is MISSING:
print("No argument provided")
else:
print(f"Argument provided: {arg}")
With this pattern, we can pass None
as an argument and the function will correctly identify it as a value.