6 ms·
> a non-existing problem Many times I've found myself wanting to write a function that I only need to use once. APIs for example, when they require a function
by rambojazz 6y ago
> a non-existing problem
Many times I've found myself wanting to write a function that I only need to use once. APIs for example, when they require a function argument. Or even just when making a "list comprehension", maybe I need more than a 1-liner lambda. I really miss this in Python.
Having said that, I won't use the implementation given in this post because it just looks overly complex.
- travisjungroth 6y ago> Many times I've found myself wanting to write a function that I only need to use once. Then write a function that you use once. Give it a short name, or just call it f. You could even give it a leading underscore, and that will signal that the function is private to that module and it won’t get imported on * imports.
- dTal 6y agoAnd if I have many single-use functions in a module? I call them _f1(), _f2(), _f3() etc? Naming things is a burden, one of the two hardest computer science problems. Mandating that all functions be named is like mandating that all values be named - no "x * 2" for you! You have to do "doubling_constant = 2: x * doubling_constant". It's true that beyond a certain level of complexity, a name can help convey intent - but that's a decision best left to the programmer, not enforced by some stupid arbitrary parsing rule.
- travisjungroth 6y agoCall them all _f. If you have a linter it may need tweaking.
- powersnail 6y agoYou don't have to define them in a module. Just define them on the spot, like a lambda. So all of them can be named `f` without a problem.