python if else 必须同时出现吗,Python:Inline if语句else什么也不做

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.

解决方案

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.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值