I am using Sourcery tool to suggest me some code simplifications and readability improvements. Today I got a suggestion to use next() with a generator expression instead of a for loop:
Before:
def get_first_even_number(numbers):
for number in numbers:
if number % 2 == 0:
return number
return None
After
def get_first_even_number(numbers):
return next((number for number in numbers if number % 2 == 0), None)
My code was a little bit more complicated than this example and I needed time to understand the refactored code.
I really do not understand how does the refactored form “make our code and our intent clearer”. I think I will disable this refactoring as useless in my configuration. What are your opinions?
Then only advantage I see is that the code was converted to a single return statement with a single expression but the considerable cost is the high complexity of the expression and the less common second argument of next().