That's what nonlocal is for: https://docs.python.org/3/reference/simple_stmts.html#the-no... Just stick "nonlocal counter" in your function and it works.
Also nonlocal implies that other variables are local, which is not true. E.g., the following works without "nonlocal" keyword:
counter = [0]
def add(n):
counter[0] += n
add(1)
add(2)
(This used to be my workaround.)Your example works because you are mutating an existing object, not reassigning a new one.
It's a disingenuous comparison IMO.
What's messy about it?
>>> (lambda f: lambda x: f(x) * 2)(lambda x: x + 1)(100)
202clos = 42
def foo(x): return x + clos
def bar(y): return y * clos
higher_order(foo, bar)
What's so hard about that?
You could do this with a lambda construct in Python; but this only works if the function has a single expression-statement; it doesn't work e.g. when you have a bunch of assignments inside the function you are inlining.
Sure, it's ugly but I think it's a silly challenge. Complex functions defined in the function call are un-maintainable anyway IMO.
Also, I think scoping rules in Python are terrible. I always end up with a namespace that is a mess. And you can't do something like this in a clean way: