omarish
omarish

Reputation: 605

evaluating a complex conditional python

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

I have 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?

Upvotes: 2

Views: 657

Answers (3)

Greg Hewgill
Greg Hewgill

Reputation: 994817

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.

Upvotes: 5

parent5446
parent5446

Reputation: 898

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

Upvotes: 0

AlexJF
AlexJF

Reputation: 886

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).

Upvotes: 0

Related Questions