Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper use of the * operator in a oneline if statement python

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)
like image 452
Indigo Avatar asked Oct 11 '17 18:10

Indigo


People also ask

How do you do an if statement on one line Python?

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.

What can the * operator be used for?

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.

How do you use one line on an if statement?

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.

Can we write if else into one line in Python * If else not used in Python Yes No Depends on the usage?

Answer: Yes, we can use if-else in one line. In Python, we can convert if-else into one conditional statement.


2 Answers

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".

like image 59
juanpa.arrivillaga Avatar answered Oct 21 '22 03:10

juanpa.arrivillaga


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.

like image 24
ash Avatar answered Oct 21 '22 02:10

ash