What is the most Pythonic way to provide a fall-back value in an assignment?

Since 2.5:

If you want to fall back only on None:

a = x if x is not None else y 

If you want to fall back also on empty string, false, 0 etc.:

a = x if x else y 

or

a = x or y 

As for undefined (as never defined, a.k.a. not bound):

try:
  a = x 
except NameError:
  a = y

or a bit more hackish (I’d not really recommend that, but it’s short):

a = vars().get('x',y)

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)