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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With