Non-obvious name bindings

Jeff Shannon jeff at ccvcorp.com
Thu Nov 15 02:38:17 CET 2001


Fernando Pérez wrote:

> On Wed, 14 Nov 2001, Jeff Shannon wrote:
>
> > If I'm reading the bug report right, then it *is* expected behavior that list
> > comp variables are function-local variables, not true "temporary" variables.
>
> You are right. The problem is that the list comp. index was propagating
> *outside* of a function magically. After using a list comprehension your
> global namespace would grow variables all by itself. Very disconcerting.

Yes, and definately a bug.  However, as I understand it, the issue being discussed in
this thread, is taking place entirely within the local namespace.  (I could be in
error, as the first few posts in this thread never made it to my news server, but
none of the examples quoted in the messages that I've seen have shown anything other
than interactive sessions.)  It seems to me that the O.P. had expected list comp
variables to never exist outside of the list comp.  The existence of the bug that you
pointed out, does not change the fact that that expectation was in error.  :)


> >
> > C++ (IIRC) treats loop indices as being limited to the scope of the loop only,
> > and invalid once the loop ends.  Python, however, has a much simpler scoping
> > scheme, and doesn't use a separate scope for loops (and list comps are just
> > syntax sugar for a for-loop).
> >
>
> C++ treats variables as *block* local:
>
> for(int i=0;i<n;i++) {...
> // i exists here
> }
> // i doesn't exist anymore (declared in above block header)

Yes, this is what I was trying to say--though perhaps not as effectively as you said
it. :)  My understanding was that this was the behavior that the O.P. expected.  But
Python doesn't use this concept of block-local scope.


> The bug appears if you do the above in a file, not at the interpreter. Don't
> know why the difference.

I'd presume that the difference is that there is no practical difference between
global and local namespace at the interactive prompt (until you define a function, at
which point function-local namespace has meaning, thus my use of a function in my
example).

Of course, it's also entirely possible that I missed something critical in those
first few posts, that renders my interpretation meaningless.  :)

Jeff Shannon
Technician/Programmer
Credit International





More information about the Python-list mailing list