Most pythonic way to refactor multiple equality checks

132 views Asked by At

Given an if statement like:

if response.status == SUCCESS or \
   response.status == FAILURE or \
   response.status == CLEAR or \
   response.status == READY:

Is it better to refactor like (1):

if any(response.status == status for status in (SUCCESS, FAILURE, CLEAR, READY):

Or (2):

if response.status in {SUCCESS, FAILURE, CLEAR, READY}:

My hunch is that 1 is better as it is more transparent (if not also more readable), but 2 is more concise and avoids having to iterate through each item in the tuple.

1

There are 1 answers

3
drt On

You could use tuple or list like this, no need to iterate. (Python3.7)

>>>'SUCCESS' in ('SUCCESS', 'FAILURE', 'CLEAR', 'READY')
True

your case

if response.status in (SUCCESS, FAILURE, CLEAR, READY):