[Python-ideas] For-loop variable scope: simultaneous possession and ingestion of cake
Jan Kanis
jan.kanis at phil.uu.nl
Wed Oct 8 15:08:25 CEST 2008
On 06/10/2008, Arnaud Delobelle <arnodel at googlemail.com> wrote:
>
> How do you want this to behave?
>
> lst = []
> a = [0]
>
> for i in range(10):
>
> a[0] = i
> lst.append(lambda: a[0])
> for f in lst:
> print(f())
>
> How about this?
>
> for a[0] in range(10):
> lst.append(lambda: a[0])
> for f in lst:
> print(f())
In my previous post I argued not to distinguish between the loop index
variable and other 'loop-scope' variables, so both pieces of code
should show the same behaviour. In what that behaviour is, there are
two possibilities:
1) Treat arbitrary location specifications like a[0] the same as
normal local/global variables. That would imply that both examples
print 0, 1, ... 9. It would also imply that lists and other arbitrary
python data structures need to be able to hold cells (over which the
python interpreter transparently indirects, so they would not be
directly visible to python code). So at the end of the second loop,
the python memory layout looks like this:
+---+
a ---> |[0]| -----------\
+---+ |
lst |
| |
v |
+---+ v
|[9]| ---> lambda ---> cell ---> 9
|[ ]|
|[8]| ---> lambda ---> cell ---> 8
|[ ]|
|[7]| ---> lambda ---> cell ---> 7
|[ ]|
...
(Note in case ascii art breaks: a[0] is pointing to the cell that
holds the 9, the same one lst[9]'s lambda is pointing at.)
But I think this would be a better solution:
2) Treat location specifiers other than local and global variables
(variables you can write down without using dots or square brackets)
the same as they are treated today. In that case, both loops would
print ten times 9. I would want to argue this is the better approach,
because when you write down a[0] you are specifically thinking of a
and a[0] in terms of objects, while when you use a local variable you
just need some place to store a temporary result, and not be bothered
with it any more than absolutely necessary.
However, I don't think anyone in their right mind would write loops
using a[0] as the index variable. Have you ever had the need to do
this?
> ATM, I think this proposal will only make things more complicated from
> every point of view.
Partly true, more (variants of) proposals makes decisions harder. But
you should read my proposal as merely extending Gregs original
proposal of using cells in loop indexes to all variables that are used
in loops, obviating the need for a separate scope/let construct. So I
think it has a place in this discussion.
Jan
More information about the Python-ideas
mailing list