I tend to use this a lot, but it's ugly:
a = (lambda x: x if x else y)(get_something())
So I wrote this function:
def either(val, alt):
if val:
return val
else:
return alt
So you can do:
a = either(get_something(), y)
Is there a built-in function for this (similar to ISNULL in T-SQL)?
No. Assignment in Python is a statement, not an expression.
The statement can be a single line or a block of code. #If the condition is true, the statement will be executed. num = 5 if num > 0: print(num, "is a positive number.") print("This statement is true.") #When we run the program, the output will be: 5 is a positive number. This statement is true.
There is new syntax := that assigns values to variables as part of a larger expression. It is affectionately known as “the walrus operator” due to its resemblance to the eyes and tusks of a walrus.
We use those statements while we want to execute a block of code when the given condition is true or false. Type of condition statement in Python: If statement. If Else statement.
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
.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With