Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Most idiomatic way to provide default value in python?

Tags:

python

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:

  1. myval if myval else defaultval
  2. 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.

like image 724
Joel P. Avatar asked Apr 25 '14 16:04

Joel P.


People also ask

How do you define a default value in Python?

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 ( =) .

What is the default value of reference point in Python?

The default value of reference_point is 0.

What is a mutable default argument in Python?

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.

Why shouldn't you use a list as a default argument?

A list would grow bigger than expected when a function was called multiple times, which would cause strange errors.


2 Answers

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

like image 132
Joran Beasley Avatar answered Oct 18 '22 16:10

Joran Beasley


They are exactly equivalent, however I suggest

defaultval if myval is None else myval

(This behaves properly when passed ie myval = []).

like image 33
Hugh Bothwell Avatar answered Oct 18 '22 15:10

Hugh Bothwell