I'd like to know if its possible to use the * operator in a oneline if to achieve the following functionality:
if node['args'] != None:
return_val = funct(*node['args'])
else:
return_val = funct()
I thought I could just say
return_val = funct(*node['args'] if node['args'] != None else None)
but it turns out this is the same as saying
if node['args'] != None:
return_val = funct(*node['args'])
else:
return_val = funct(*None)
which doesn't make any sense for *None
.
I tired enclosing the first option in parenthesis but this just throws SyntaxError: can't use starred expression here
return_val = funct((*node['args']) if node['args'] != None else None)
One Line If-Else Statements in Python Writing a one-line if-else statement in Python is possible by using the ternary operator, also known as the conditional expression. This works just fine. But you can get the job done by writing the if-else statement as a neat one-liner expression.
Arithmetic Operators + (Addition) – This operator is used to add two operands. – (Subtraction) – Subtract two operands. * (Multiplication) – Multiply two operands. / (Division) – Divide two operands and gives the quotient as the answer.
A single-line if statement just means you're deleting the new line and indentation. You're still writing the same code, with the only twist being that it takes one line instead of two. Note: One-line if statement is only possible if there's a single line of code following the condition.
Answer: Yes, we can use if-else in one line. In Python, we can convert if-else into one conditional statement.
Yes, you need to provide an empty sequence, not None
:
>>> def f(*args):
... for arg in args:
... print(arg)
...
>>> x = None
>>> y = ('a','b')
>>> f(*(y if x is not None else ()))
>>> x = object()
>>> f(*(y if x is not None else ()))
a
b
But I think your if -else
statement approach is much preferable. I only have to look at it once and I know immediately what is going on. With the conditional expression, I have to think about it.
Also, this is a conditional expression, not a "one-line if statement".
A more concise solution, albeit one with slightly different semantics:
return_val = funct(*node['args'] or ())
If bool(node['args'])
evaluates to False
, the empty tuple ()
will be unpacked (into nothing) and passed; otherwise, node['args']
will be unpacked and passed.
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