[Python-ideas] A "local" pseudo-function

Tim Peters tim.peters at gmail.com
Mon Apr 30 14:58:17 EDT 2018


[Tim, still trying to define `iseven` in one statement]

>     even = (lambda n: n == 0 or odd(n-1))
>     odd = (lambda n: False if n == 0 else even(n-1))
>     iseven = lambda n: even(n)
...

> [and the last attempt failed because a LOAD_GLOBAL was generated
>    instead of a more-general runtime lookup]

So if I want LOAD_FAST instead, that has to be forced, leading to a
one-statement definition that's wonderfully clear:

    iseven = lambda n: (
        lambda
            n=n,
            even = (lambda n, e, o: n == 0 or o(n-1, e, o)),
            odd = (lambda n, e, o: False if n == 0 else e(n-1, e, o)):
                   even(n, even, odd)
        )()

Meaning "wonderfully clear" to the compiler, not necessarily to you ;-)

Amusingly enough, that's a lot like the tricks we sometimes did in
Python's early days, before nested scopes were added, to get recursive
- or mutually referring - non-global functions to work at all.  That
is, since their names weren't in any scope they could access, their
names had to be passed as arguments (or, sure, stuffed in globals -
but that would have been ugly ;-) ).


More information about the Python-ideas mailing list