Why not real anonymous functions?

I don’t want to sound too dismissive here, but often when I hear people say this I tend to think it’s because they are trying to import idioms from other languages into Python when Python just has an alternative way of doing whatever they’re trying to do.

I’m most familiar with this in the case of trying to write JavaScript in Python. For instance, some JS programmers are used to a method-chaining style with a lot of filters and maps. But in Python a lot of those can be done using list/generator comprehensions instead. Similarly JS has a .forEach method that takes a function, and yeah, it’s more convenient in JavaScript to use an inline function, but in Python you don’t need that because the regular for loop is fine, and if you want more fancy behavior, you have the whole iterator protocol to play with. And one of things people like about JS “fat arrow” functions is that they solve some problems with an awkward this context, but Python doesn’t have those problems in the first place.

Even within JS, I feel that some of the reasons people use inline functions are basically workarounds for annoying behavior of JS (e.g., this and rather complex and confusing behavior of the basic for construct). In Python, where those workarounds are no longer necessary, there is even less reason to write code that way.

That style of functional programming isn’t inherently bad or anything, but Python just has alternative ways of achieving many similar things. I’ve seen people express points similar to yours in the past, but in each case my reaction is mostly the same: wanting to write code in a style similar to how you would write it in JavaScript (or Rust or whatever) is not in itself a compelling justification for adding features to Python. The question is whether adding the feature to Python improves our ability to write good code in Python. If there are already fine ways to do something in Python, we don’t need to add another way just because some other language does things that way. (And we definitely don’t need to take the JavaScript approach of constantly adding a bunch of revamped or alternative versions of old functionality, littering the language with the detritus of the past.)

What’s wrong with that line of reasoning is that it doesn’t make sense to add features just because another language has them. The features you mention were not added just because another language had them. They were added because another language provided some inspiration for a feature to add to Python that might be helpful when writing code in Python. It’s totally great to have interchange of ideas between different languages, but each language will choose the features that mesh well with its existing constructs. Just because a certain Indian restaurant makes a great chicken curry doesn’t mean the Mexican restaurant down the street should add chicken curry to their menu too. :slight_smile:

11 Likes