Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dynamic default arguments in python functions

Tags:

python

I have a need for functions with default arguments that have to be set at function runtime (such as empty lists, values derived from other arguments or data taken from the database) and I am currently using the following pattern to deal with this:

def foo(bar, baz=None):
    baz = baz if baz else blar()
    # Stuff

Where blar() gives the proper default value of baz which might change during execution. However, the baz = baz if baz else ... line strikes me as inelegant. Does anyone else have a better method of avoiding the one-time binding of default function arguments? Small, cross-platform libraries installable by pip are acceptable replacements.

like image 753
Drakekin Avatar asked Jun 06 '13 11:06

Drakekin


2 Answers

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()
like image 68
John La Rooy Avatar answered Nov 15 '22 17:11

John La Rooy


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.

like image 21
Alex Hall Avatar answered Nov 15 '22 18:11

Alex Hall