Callable as the default argument to dict.get without it being called if the key exists

Another option, assuming you don’t intend to store falsy values in your dictionary:

test.get('store') or run()

In python, the or operator does not evaluate arguments that are not needed (it short-circuits)


If you do need to support falsy values, then you can use get_or_run(test, 'store', run) where:

def get_or_run(d, k, f):
    sentinel = object()  # guaranteed not to be in d
    v = d.get(k, sentinel)
    return f() if v is sentinel else v

Leave a Comment