For whatever reason I often find myself writing code like this:
def returns_a_func(this_var_gets_used):
def _inner_func(*args, **kwargs):
"""Do some stuff in here"""
return _inner_func
Or like this:
def some_useful_func(*args, **kwargs):
"""Does useful and interesting things, I promise"""
this_one_takes_a_func_arg(
"foo",
42,
some_useful_func,
)
Maybe I’m mistaken but these kinds of patterns seem to arise a lot in functional-style code. The problem is that it feels needlessly verbose and repetitive. It’s not very economical from a purely syntactic standpoint.
I realize that functions are first-order objects in Python. I think my hangup is that they are semantically first-order objects but the Python syntax doesn’t reflect that fact. And of course I realize there is lambda
but its usefulness is quite limited and its syntax is frankly a bit cumbersome.
So here’s my question: why not real anonymous functions a la JavaScript or Rust? Has this been proposed before? I did a quick search of PEPs and was not able to find anything.
As the language adopts more functional constructs it seems like this would be quite useful.
I’m not sure how difficult it would be to implement in the parser, but it seems like it would be relatively unambiguous to implement syntax like this:
def returns_a_func(this_var_gets_used):
return (*args, **kwargs) => ( # are the parens actually useful/necessary here?
"""Do some stuff in here"""
)
Similarly, like this:
this_one_takes_a_func_arg(
"foo",
42,
(*args, **kwargs) => (
"""Does useful and interesting things, I promise"""
),
)
I supposed the biggest problem is knowing how to delimit the anonymous function. Languages with brackets don’t have this problem but it’s slightly more difficult with only whitespace, although it still seems unambiguous to me in most circumstances. Perhaps I’m also missing some trickiness around the scope of the parameters, although it seems like lambda
would have the same problem.
Anyway, this is mostly just some idle questioning, but it has bothered me enough over the years to bring it up here. If it’s actually interesting and unobjectionable I’d be willing to consider drafting a PEP.