[Python-ideas] Tweaking closures and lexical scoping to include the function being defined

Paul Moore p.f.moore at gmail.com
Wed Sep 28 12:26:00 CEST 2011

On 28 September 2011 08:10, Paul Moore <p.f.moore at gmail.com> wrote:
> That either validates the default-argument hack as a valid response to
> a specific requirement, or suggests some syntax added to the function
> definition line. Or of course, just go with a normal (nested function)
> closure.

Taking a step back from all this, using an explicit closure to
implement the counter example being used throughout this thread looks
something like this:

>>> # I thought apply still existed in some module. Never mind, can't find it so I'll reimplement a quick version here...
>>> def apply(f): return f()
>>> @apply
... def counter():
...     n = 1
...     def inner():
...         nonlocal n
...         print(n)
...         n += 1
...     return inner
>>> counter()
>>> counter()
>>> counter()

To be honest, that doesn't actually look that bad. Explicit is better
than implicit and all that, and the boilerplate doesn't really bother
me that much.

The real annoying boilerplate here is the "def dummy_name()...return
dummy_name" bit. But fixing that leads us directly back to the
perennial discussion on anonymous multiline functions...


More information about the Python-ideas mailing list