-1

Can anyone please explain what this code is for?

shift, range = order < self.order and (1, (to, orig-1)) or (-1, (orig+1, to))

I know it will set shift and range depending on the result of order < self.order

What I don't know is why there is an and and or statement there

Miguel Ike
  • 484
  • 1
  • 6
  • 19

2 Answers2

3

From the documentation of boolean expressions in Python -

The expression x and y first evaluates x ; if x is false, its value is returned; otherwise, y is evaluated and the resulting value is returned.

The expression x or y first evaluates x; if x is true, its value is returned; otherwise, y is evaluated and the resulting value is returned.

So and / or expressions in Python don't necessarily return True or False, instead -

  1. For and it return the last evaluated False value, or if all values are True , they return the last evaluated value.

  2. For or it returns the last evaluated True value, or if all values are False, it returns the last evaluated value.

So , in your case if the condition is true , it returns the value of (1, (to, orig-1)) , otherwise it returns the value of (-1, (orig+1, to)) .

Very simple examples to show this -

>>> 1 < 5 and 2 or 4
2
>>> 6 < 5 and 2 or 4
4

Also, though not directly applicable to the condition , but in a general case, for a condition like -

cond and a or b

if cond is a True-like value and a has a False-like value (like 0 or empty string/list/tuple, etc), it would return b . Example -

>>> 1 < 5 and 0 or 2
2

So, it would be better to use the equivalent if..else ternary expression, Example -

a if cond else b
Community
  • 1
  • 1
Anand S Kumar
  • 88,551
  • 18
  • 188
  • 176
1

There is a logical error in this code - when order < self.order evaluates to True, an exception will be raised.

I believe this is what is intended:

shift, range = (1, (to, orig - 1)) if order < self.order else (-1, (orig + 1, to))

This will assign 1 to shift and (to, orig - 1) to range when order < self.order is True and -1 to shift and (orig + 1, to) to range when order >= self.order

chucksmash
  • 5,777
  • 1
  • 32
  • 41