Most idiomatic way to provide default value in python?

Many SO discussions and search queries have not been able to definitively answer the question of the best / safest / most Pythonic way of providing a default value if the Python function receives Nonein a parameter. This is especially true for a parameter datetimeif it matters, but ideally we standardize our approach for all types of parameters.

Here are two approaches that both fit as the β€œright” way to do this:

  • myval if myval else defaultval
  • myval or defaultval

Are they functionally equivalent or are there subtle differences between them? I very much prefer the brevity and clarity of the second option, but the proponents of the first say that it is not always safe. Any guidance from someone who has more python experience than me (like almost anyone) would be greatly appreciated.

+4
source share
3 answers

1 is by far the preferred conditional assignment method (Explicit is better than implicit)

and it’s 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

Main problem -

x = x or y

x of 0 or an empty array or any other fake value can never be assigned

+2
source

They are exactly equivalent, however I suggest

defaultval if myval is None else myval

(This behaves correctly during transmission, i.e. myval = []).

+2

, , , :

Disclaimer: x or y; Result: if x is false, then y, else xand Note: This is a short circuit operator, so it evaluates only the second argument, if the first False.

+1
source

Source: https://habr.com/ru/post/1538103/


All Articles