2
category.is_parent = True if self.request.get('parentKey') is not None else category.is_parent = False 

Above is the code in which I am trying to write a if else in a single line and it is giving me this syntax error

SyntaxError: can't assign to conditional expression" 

But if I write it in following way it works fine

if self.request.get('parentKey') is not None: category.is_parent = True else: category.is_parent = False 
3
  • You don't need an id/else here. Just do category.is_parent = self.request.get('parentKey') != None Commented Nov 25, 2016 at 17:44
  • 1
    If you put it on one line, it's a slightly different syntax. x = a if condition else b, and you can chain multiple ones up too, like x = a if condition else b if condition2 else c Commented Nov 25, 2016 at 17:44
  • The structure you tried is '<assignment> if condition else <assignment>'; the structure that's allowed is 'variable = <expression>' where expression is of the form '<value1> if <condition> else <value2>'. Commented Nov 25, 2016 at 17:46

3 Answers 3

3

Try this:

category.is_parent = True if self.request.get('parentKey') else False 

To check only against None:

category.is_parent = True if self.request.get('parentKey') is not None else False 
Sign up to request clarification or add additional context in comments.

4 Comments

This isn't exactly the same with what the OP wants. Doesn't handle the case where self.request.get('parentKey') is falsy and not None
@SaimAbdullahCh You can accept it as the answer of your question :)
@MosesKoledoye How do you know that?
Because '', 0, [] etc. will all return False, but it should be True in this case.
1

You can write:

category.is_parent = True if self.request.get('parentKey') is not None else False

Or even simpler in this case:

category.is_parent = self.request.get('parentKey') is not None

Comments

0

You can write this with a one liner but using the [][] python conditional syntax. Like so:

category.is_parent = [False,True][self.request.get('parentKey') is not None 

The first element in the first array is the result for the else part of the condition and the second element is the result when the condition in the second array evaluates to True.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.