Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

A better way to write: a = b if a is None else a

Tags:

python

There is a very common sentence that I use over and over in Python that feels "too long", and I am hoping there is a more Pythonic way to write it:

a = b if a is None else a

Is there a better way to write this?

like image 369
gnychis Avatar asked Dec 03 '22 15:12

gnychis


2 Answers

The typical shortcut for this is

a = a or b

Though, this will only test if a evaluates to False, so 0, False, None, '', etc. will all cause a to be set to b

like image 72
Brendan Abel Avatar answered Dec 05 '22 05:12

Brendan Abel


You could do...

if a is None: 
     a = b

It seems a bit cleaner to me and you don't have to assign a variable to itself.

like image 26
Steve Byrne Avatar answered Dec 05 '22 05:12

Steve Byrne