Best way to do conditional assignment in python

The or operator does what you want:

get_something() or y

In fact, it's chainable, like COALESCE (and unlike ISNULL). The following expression evaluates to the left-most argument that converts to True.

A or B or C

You may use:

a = get_something() or y

If get_something is True in boolean context, its value will be assigned to a. Otherwise - y will be assigned to a.


You can use a simple or, like so:

>>> a = None
>>> b = 1
>>> c = (a or b) # parentheses are optional
>>> c
1

Easy!

For more conditional code:

a = b if b else val

For your code:

a = get_something() if get_something() else val

With that you can do complex conditions like this:

a = get_something() if get_something()/2!=0 else val

I have provided an answer to this question to another user. Check it out here:

Answer to similar question

To respond quickly here, do:

x = true_value if condition else false_value