Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Inline if statement else do nothing

Assigning a Django Model's field to a value if it matches a condition.

g = Car.objects.get(pk=1234)
g.data_version = my_dict['dataVersion'] if my_dict else expression_false # Do nothing??

How do I do nothing in that case? We can't do if conditional else pass.

I know I can do:

if my_dict:
    g.data_version = my_dict['dataVersion']

but I was wondering if there was a way to do inline expression_true if conditional else do nothing.

like image 200
user1757703 Avatar asked Aug 14 '14 23:08

user1757703


People also ask

How do you say do nothing in an if statement in Python?

pass is a special statement in Python that does nothing. It only works as a dummy statement. We can use pass in empty while statement also. We can use pass in empty if else statements.

How do you inline an if statement in Python?

Use an inline if-else expressionUse the syntax statement1 if condition else statement2 to execute statement1 if condition is True otherwise execute statement2 if condition evaluates to False .

Can we write if statement without else in Python?

An if statement looks at any and every thing in the parentheses and if true, executes block of code that follows. If you require code to run only when the statement returns true (and do nothing else if false) then an else statement is not needed.

Can we write if-else into one line in Python?

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


1 Answers

No, you can't do exactly what you are describing, as it wouldn't make sense. You are assigning to the variable g.data_version... so you must assign something. What you describe would be like writing:

g.data_version =  # There is nothing else here

Which is obviously invalid syntax. And really, there's no reason to do it. You should either do:

if my_dict:
    g.data_version = my_dict['dataVersion']

or

g.data_version = my_dict['dataVersion'] if my_dict else None # or 0 or '' depending on what data_version should be.

Technically, you could also do:

g.data_version = my_dict['dataVersion'] if my_dict else g.data_version

if you only want to update g.data_version if your dict exists, but this is less readable and elegant than just using a normal if statement.

like image 118
Johndt Avatar answered Oct 13 '22 05:10

Johndt