Reply to post: Re: Reinventing a more limited wheel

Python creator Guido van Rossum sys.exit()s as language overlord

The Indomitable Gall

Re: Reinventing a more limited wheel

" There is absolutely no way to ensure that f(x) is idempotent. If you don't understand that, then step away from the keyboard. "

And this is another reason to favour the PEP -- taking the same example

results = [(x, f(x), x/f(x)) for x in input_data if f(x) > 0]

if the function f is not idempotent, then we now have the possibility of throwing a divide-by-zero exception, which would cause the whole comprehension to be binned. (E.g. first call to f(x) returns 1, but in x/f(x), f(x) returns zero.)

In the case of the assignment expression version...

results = [(x, y, x/y) for x in input_data if (y := f(x)) > 0]

... as f(x) is only evaluated once, x/y will never result in a divide-by-zero exception.

POST COMMENT House rules

Not a member of The Register? Create a new account here.

  • Enter your comment

  • Add an icon

Anonymous cowards cannot choose their icon

Biting the hand that feeds IT © 1998–2019