Replacement for lambda - 'def' as an expression?

Simo Melenius firstname.lastname at iki.fi-spam
Wed Sep 7 02:50:30 EDT 2005


Paul Rubin <http://phr.cx@NOSPAM.invalid> writes:

> Sybren Stuvel <sybrenUSE at YOURthirdtower.com.imagination> writes:
> > An example:
> > 
> > def generate_randomizer(n, m):
> >     randomizer = def(x):
> >         return x ** n % m
> > 
> >     return randomizer
> 
> You're a little bit confused; "name" doesn't necessarily mean "persistent
> name".  You could write the above as:
>
>   def generate_randomizer (n, m):
>      def randomizer(x):
>         return pow(x, n, m)
>      return randomizer

But if you could do anonymous blocks, you could just write something
like:

def generate_randomizer (n, m):
    return def (x):
        return pow (x, n, m)

Personally, I don't mind naming local functions in practice (and
Python syntax doesn't lend itself very well to anonymous blocks) but
rather, the nuisance is that I feel there's just plain something wrong
with it. It's less beautiful than it could be.

Luckily, the last time I followed the discussion on this topic in
c.l.p, some bright mind whose name escapes me now pointed out the
craziness of _having to_ name functions by comparing it to the
situation where you'd have to bind any literal objects to symbols
before you could use them. Like:

def return_fixed_number ():
        res = 42
        return res

or:

arg1 = "foo"
arg2 = 42
arg3 = baz ()
myfunction (arg1, arg2, arg3.xyzzy ())

Sure, you don't lose any expressiveness in that: if you had to name
any object before using it, you could write all the same programs that
you can in the current Python. But it's the expressiveness of your
mind that gets harpooned: you'll have to keep part of your focus on
these extraneous local variables instead of thinking only in terms
of values where only values matter.


-- 
firstname.lastname at iki.fi -- Today is the car of the cdr of your life.



More information about the Python-list mailing list