Python: built-in if statement does nothing

Assigning a Django model field to a value if it matches the condition.

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

How am I doing nothing in this case? We can not do if conditional else pass.

I know that I can:

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

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

+4
source share
1 answer

No, you cannot do what you describe, as that does not make sense. You assign a variable g.data_version... so you have to assign something. What you described will look like a record:

g.data_version =  # There is nothing else here

This is clearly invalid syntax. And indeed, there is no reason for this. You must 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.

:

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

g.data_version, dict , , if.

+8

All Articles