Naming higher order functions

Kragen Sitaker kragen at
Sun Feb 3 01:20:37 EST 2002

"Alex Martelli" <aleax at> writes:
> To make it almost-work in older Pythons, the old trick was:
> def makeGetNth(n):
>   def g(x, n=n): return x[n]
>   return g
> ...  The "almost" is because one might then, by
> mistake, call the returned g with two arguments, and the
> second one would take n's place; you have more control now.

You could still write

class makeGetNth:
    def __init__(self, n): self.n = n
    def __call__(self, x): return x[self.n]

which works the same way but avoids the "almost".  Nested scopes are
nicer, of course.

More information about the Python-list mailing list