Confessions of a Python fanboy
kyrie at uh.cu
Wed Aug 26 23:00:11 CEST 2009
On Friday 31 July 2009 04:08:33 am Masklinn wrote:
> On 30 Jul 2009, at 23:57 , Luis Zarrabeitia wrote:
> > I'd like to ask, what "container.each" is, exactly? It looks like a
> > function
> > call (as I've learned a few posts ago), but, what are its arguments?
> > How the
> > looping "works"? Does it receive a "code" object that it has to
> > execute?
> > Is .each some kind of magic keyword? (This has little to do with
> > python or
> > the current thread, so feel free to reply off-list if you want to...)
> #each is simply a method that takes a function (called blocks in
> ruby). One could call it a higher-order method I guess.
> It's an implementation of the concept of internal iteration: instead
> of collections yielding iterator objects, and programmers using those
> through specially-built iteration constructs (e.g. `for…in`),
> collections control iteration over themselves (the iteration is
> performed "inside" the collection, thus the "internal" part) and the
> programmer provides the operations to perform at each iterative step
> through (usually) a function.
Interesting. I know what internal iteration is, and I suspected it was along
these lines when I saw the syntax and that .each was a function and not a
keyword. But if it is internal iteration and the .each method is receiving an
anonymous function, I wonder what is the scope of the variables in that
function. In pseudo-python terms (using your example),
x = 5
x = do_something_else(item)
(or something like that). In python, the inner function would be invalid
(the 'x' is local). For that construct to be equivalent to a for loop, the
anonymous function shouldn't create a new scope. Is that what is happening?
(If it is, this would be a big difference between anonymous and non-anonymous
Anyway, this is OT. Thank you for your reply.
(ah, sorry for taking so long... I was out of town)
Luis Zarrabeitia (aka Kyrie)
Fac. de Matemática y Computación, UH.
More information about the Python-list