Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

Just curious, but from a pragmatic view, what is the advantage of using anonymous functions instead of named functions for any mildly complex code?



Readability and scoping are two big advantages. Anonymous functions are often short and sweet, but also highly specific to a single section of the code. It's not meant to be reused. Having to name that one-off use case and hoist it into a function elsewhere makes it harder to maintain and understand. With proper anonymous functions, you can just read through it in one go.


But you don't need to name it big or maintain it somewhere else? Just use a throwaway name and write it where you use it. I mean python even allows overriding functions with the same name in the same scope. You could literally go with using just the same name everywhere.


True, but you're missing the point.


Then what is the point?


Readability. If you're using the same name everywhere, then your code is really hard to understand for other devs:

    val = my_list.reduce(foobar)

What is even going on here?


one option is to define your function inline, directly above the line where you would have liked to write the complex anonymous function. I guess if you are worried about namespace pollution you can 'del' the symbol afterward.


It's pretty common to define "higher-order" functions in functional programming. These will sometimes be applied to code blocks.

For example, Python's with statement could have been entirely programmed as a library function if lambas supported code blocks:

    with(open("file.txt"), lambda f:
        content = f.read()
        return sum(int(c) for c in content.split(" "))
    )

Functional languages usually have a pretty limited "core" and implement most of their features through their standard library, usually using higher-order functions, overloaded operators ...


But I can do all that with python already? Your example would work this way too:

    def _(f):
        content = f.read()
        return sum(int(c) for c in content.split(" "))
    with(open("file.txt"), _)


I don't think they were saying you can't do it in Python, just offering what is arguably a nicer syntax, but of course that is subjective. The anonymous function version lets you write things in the order they happen and also "binds" the operations together, ie, someone can't accidentally add a completely unrelated line between the `def` and the `with`. It ultimately doesn't matter, people just get used to the conventions of their preferred languages and we all trudge on.




Consider applying for YC's Fall 2025 batch! Applications are open till Aug 4

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: