Why doesn't this simple Curry-like implemention work?

Martin von Loewis loewis at informatik.hu-berlin.de
Sun Oct 28 05:12:28 EST 2001


"Michael R. Head" <burner at core.binghamton.edu> writes:

> # for some reason this function doesn't work in python 1.5.2.
> def curry(f, p):
> 	return lambda x: apply(f, p, x)
> 
> I've looked up on the list better class-based implementations, and am
> using one of them, but I'm curious why this doesn't work (when the
> curried function is called, f becomes unknown).

In Python 1.5.2, function scopes don't nest. Given

x=1
def foo():
  x=2
  def bar():
    return x
  return bar()

calling foo() will return 1. Python only has three nested name spaces:
locals, globals, and builtins. Since the lambda expression produces a
nested function, and since f is neither local to the lambda
expression, nor global, it will not find the name f.

The common work-around was to write

 def curry(f, p):
 	return lambda x,f=f,p=p: apply(f, p, x)

Starting with Python 2.1, function scopes optionally do nest (if you
import nested_scopes from __future__). In Python 2.2, they nest by
always.

Regards,
Martin



More information about the Python-list mailing list