开发者

evaluating a complex conditional python

show_prev_btn = (len(sessions) > 0 and (sessions[0].pk == \
    Session.objects.filter(user=request.user).first().pk))

I h开发者_高级运维ave this boolean that I'm calculating. Sessions is a list and if it has 0 elements, sessions[0] will raise an exception. Fortunately, I think that I can catch it before it's evaluated by checking len(sessions) > 0.

This works on my local development machine, but is this okay practice or should I nest these conditionals?


In Python, the and operator is defined to use short-circuit evaluation. So if you have an expression like

a() and b()

then first a() will be called. Only if that returns True, will b() be called. If a() returns False, then b() will not be called, so you can do things in b() that might crash if a() is False.

This is certainly accepted practice and is widely used.


The advantage of nesting the conditions is that, in this specific case, it might improve readability a bit (by reducing line length).

Although in my opinion both are equally good solutions it's a matter of taste and code style more than anything else (doubt the performance differences, if any, would have a great impact).


To copy from an older question, try this. The syntax is more intuitive, though the difference is arbitrary.

sessions[0].pk == Session.objects.filter(user=request.user).first().pk) if len(sessions) else False
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜