Many discussions and SO searches have been unable to conclusively answer the question of the best/safest/most Pythonic way of providing a default value if a Python function receives None
in a parameter. This specifically came up in regards to a datetime
parameter, in case that matters, but ideally we standardize our approach for all parameter types.
Here are the two approaches that both keep coming up as the "correct" way to do this:
myval if myval else defaultval
myval or defaultval
Are they both functionally equivalent, or are there subtle differences between the two? I vastly prefer the brevity and clarity of the second option, but adherents to the first one say it's not always safe. Any guidance from someone with more python experience than me (e.g. nearly anyone) would be greatly appreciated.
To specify default values for parameters, you use the following syntax: def function_name(param1, param2=value2, param3=value3, ...): Code language: Python (python) In this syntax, you specify default values ( value2 , value3 , …) for each parameter using the assignment operator ( =) .
The default value of reference_point is 0.
Python's default arguments are evaluated once when the function is defined, not each time the function is called (like it is in say, Ruby). This means that if you use a mutable default argument and mutate it, you will and have mutated that object for all future calls to the function as well.
A list would grow bigger than expected when a function was called multiple times, which would cause strange errors.
1 is by far the preffered method of conditional assignment (Explicit is better than implicit)
and even better to be explicit
myval = myval if myval is not None else defaultval
or even better
def some_function(arg1,arg2="defaultValue"):
myval = arg2
the main problem is
x = x or y
can never be assigned an x of 0 or an empty array or any other falsy value
They are exactly equivalent, however I suggest
defaultval if myval is None else myval
(This behaves properly when passed ie myval = []
).
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