Express What, not How.

Alex Martelli aleax at aleax.it
Wed Oct 15 03:13:03 EDT 2003


Rainer Deyke wrote:
   ...
> (x == 0).if_true(anonymous_code_block)
> 
> Sure, Python already has an 'if' statement.  That does not mean that there
> are no other control structures worth implementing as HOFs.

True: if we had good code block literals, they'd help.  However, the
issue of having to name the code block (with a def) is perhaps not as
crucial as it appears -- as important (and not implicit in the code
block being a literal) is in what scope the code block gets and sets
variables.  If an anonymous code block, like a lambda, is totally
equivalent to a named function (sets variable locally, gets them in
lexical scope), then being able to write the above rather than

def guarded(): anonymous_code_block
(x == 0).if_true(guarded)

is a somewhat minor.  The problem is, what could I possibly write in the
code block in order to obtain the same effect as with:
    if x == 0:
        x = 23
        y += 1
and that's an issue of scope, not one of naming or not naming the block.
(Mertz's proposal for a 'block' keyword addresses this, but by wanting
the block's scope to be that of the caller rather than that of the
definer, it of course solves none of the problems Smalltalks block solve).


> However, I think I can make an even stronger case for anonymous functions
> from my own code, which is littered with lambda expressions such as
> 'lambda:
> 1', 'lambda: 0', and 'lambda: None'.  Giving those mini functions
> individual names would be an atrocity, and even a factory function that
> returns these mini functions would only hurt readability.

I disagree: I find nullary(1), nullary(0) and the like very readable.
"lambda: x" is IMHO much more of a problem -- again because of scope.


Alex





More information about the Python-list mailing list