简体   繁体   中英

Most pythonic way to refactor multiple equality checks

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM