3

I have this code:

if self.date: # check date is not NoneType
    if self.live and self.date <= now and self.date >= now:
         return True
return False

My IDE says: This looks like it should be simplified i.e. Python chained comparison.

What is a chained comparison and how can it be simplified?

Prometheus
  • 32,405
  • 54
  • 166
  • 302

4 Answers4

6

An example of a chained comparison is shown below.

age = 25

if 18 < age <= 25:
    print('Chained comparison!')

Note that beneath the covers this is exactly the same as shown below, it just looks nicer.

age = 25

if 18 < age and age <= 25:
    print('Chained comparison!')
Ffisegydd
  • 51,807
  • 15
  • 147
  • 125
4
self.age <= now and self.age >= now

Can be simplified to:

now <= self.age <= now

But since it is True only when self.age is equal to now we can simplify the whole algorithm to:

if self.date and self.live and self.age==now:
   return True
return False

If you want to check if age is in some range then use chained comparison:

if lower<=self.age<=Upper:
     ...

Or:

if self.age in range(Lower, Upper+1):
     ...
Piotr Dabkowski
  • 5,661
  • 5
  • 38
  • 47
1

Your code can and should be reduced to:

return self.date and self.live and self.date == now

this is because:

  1. now <= self.date <= now is mathematically equal to self.date == now
  2. if you return a boolean depending on whether a condition is true, it's the same as just returning the result of evaluating the condition expression itself.

As to reducing a <= b and b<= c: it's the same as a <= b <= c; and this actually works with any other operator.

Erik Kaplun
  • 37,128
  • 15
  • 99
  • 111
0

To check if x is superior to 5 and inferior to 20, you can use a simplified chain comparison, i.e.:

x = 10
if 5 < x < 20:
   # yes, x is superior to 5 and x is inferior to 20
   # it's the same as: if x > 5 and x < 20:

The above is a simple example but I guess it will help new users to get started with simplified chain comparison in python

Pedro Lobito
  • 94,083
  • 31
  • 258
  • 268