python – returning a default value

You need to use a sentinel to detect that a default value was not set:

sentinel = object()

def func(someparam, default=sentinel):
    if default is not sentinel:
        print("You passed in something else!")

This works because an instance of object() will always have it’s own memory id and thus is will only return True if the exact value was left in place. Any other value will not register as the same object, including None.

You’ll see different variants of the above trick in various different python projects. Any of the following sentinels would also work:

sentinel = []
sentinel = {}

Leave a Comment