4 ms·
What is the problem using def for your multiline closures?
by quietbritishjim 5y ago
What is the problem using def for your multiline closures?
- valenterry 5y agoIt's boilerplate and makes you have to jump around in the code to follow what's happening. If a function is used 2 times, 3 times, ... sure, go for it. If it's just a one-time use, please don't make a separate function.
- quietbritishjim 5y agoIt doesn't have to be a separate function, it can be nested (in fact it has to be if it's a closure). That's no different from what you would have got if you were allowed multiline lambdas in the first place. Or did you just mean it has to be one line earlier than the line of code that uses it? That doesn't seem like a big imposition to me. def precise_multiples_first(max_val, divisor): print(f"Using {max_val=}") def sort_key(val): if val % divisor == 0: return 0, val else: return 1, val return sorted(range(max_val), key=sort_key) vs def precise_multiples_first(range_max, divisor): print(f"Using {max_val=}") return sorted(range(max_val), key=lambda val: ( if val % divisor == 0: return 0, val else: return 1, val )) (Yes I know I could've squeezed that function onto one line e.g. using ternary operator, but it was just a quick example.)
- valenterry 5y agoThat only works if you are not already within a lambda expression - which happens quite often if you embrace a FP style