[Python-Dev] Lexical scoping in Python 3k

Andrew Koenig ark at acm.org
Mon Jul 3 17:08:18 CEST 2006


> I don't think "trivial" is the right word to use here,
> since it implies something that's of so little importance
> that it can be ignored. But the simple cases are precisely
> the ones where this wart hurts the most, so we can't
> ignore them.

I'd like to inject an example that might help make this discussion more
concrete.

Consider the following function:

	def for_each(seq, f):
		for i in seq:
			f(i)

I'm sure I've seen more than one instance of someone on comp.lang.python
trying to do the equivalent of using a function such as this one to compute
the sum of the elements of a sequence as follows:

	def sum(seq):
		result = 0
		def accum(i):
			result += i
		for_each(seq, accum)
		return result

and wonder why it doesn't work.  Still odder, why it doesn't work and the
following does:

	def sum(seq):
		result = [0]
		def accum(i):
			result[0] += i
		for_each(seq, accum)
		return result[0]

Transforming the first definition of sum above into the second may be
trivial, but only if you've encountered the technique before.  Moreover, the
first version of sum uses a technique that is more than 45 years old (!), as
it was available to Algol 60 programmers.




More information about the Python-Dev mailing list