Chaining comparison operators in Python
Python Clean Code Tip:
Use chained comparison when you need to check whether some variable is between MIN and MAX values.
👇
from dataclasses import dataclass @dataclass class SurfBoard: width: float length: float MINIMAL_LENGTH = 201.3 MAXIMAL_LENGTH = 278.5 # without chained comparison def board_is_pwa_compliant(surf_board: SurfBoard): return surf_board.length > MINIMAL_LENGTH and surf_board.length < MAXIMAL_LENGTH surf_board = SurfBoard(width=75.3, length=202.7) print(board_is_pwa_compliant(surf_board)) # True # with chained comparison def board_is_pwa_compliant(surf_board: SurfBoard): return MINIMAL_LENGTH < surf_board.length < MAXIMAL_LENGTH print(board_is_pwa_compliant(surf_board)) # True # don't abuse it like this: a <= b < c > d