Dynamic default arguments in python functions

No, that's pretty much it. Usually you test for is None so you can safely pass in falsey values like 0 or "" etc.

def foo(bar, baz=None):
    baz = baz if baz is not None else blar()

The old fashioned way is the two liner. Some people may prefer this

def foo(bar, baz=None):
    if baz is None:
        baz = blar()

You can replace

baz = baz if baz else blar()

with

baz = baz or blar()

if you're still happy with just testing for falsy values instead of None.

Tags:

Python