This issue tracker has been migrated to GitHub, and is currently read-only.
For more information, see the GitHub FAQs in the Python's Developer Guide.

classification
Title: Separate Scope for List Comprehensions
Type: enhancement Stage:
Components: None Versions:
process
Status: closed Resolution: rejected
Dependencies: Superseder:
Assigned To: Nosy List: nobody, rhettinger
Priority: normal Keywords:

Created on 2002-01-29 22:13 by rhettinger, last changed 2022-04-10 16:04 by admin. This issue is now closed.

Messages (5)
msg53455 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2002-01-29 22:13
The variables in a list comprehension should not be in 
the enclosing scope.

i=10
temp = [str(i) for i in range(5)]
print i

Should print 10 instead of 4.

Implement the above as:

i=10
def _listcomp():
    for i in range(5):
        yield str(i)
temp = list(_listcomp())
print i

Note, I timed the difference between the existing and 
proposals implementations and found only a 4% decrease 
in speed.

In case someone is already relying on the list 
comprehension variables being in the local scope, a 
deprecation warning or from __future__ in warranted.

Also note, this implementation leaves open the 
possibility of creating generator comprehensions so 
that temp=[yield str(i) for i in range(5)] creates the 
same code as above except that the final 'list' 
coercion is eliminated:  temp=_listcomp

msg53456 - (view) Author: Nobody/Anonymous (nobody) Date: 2002-01-30 15:52
Logged In: NO 

This is Guido; I can't log in here on the road.

I believe this has been fixed in Python 2.2, and possibly 
in 2.1.2.  Can you check that?
msg53457 - (view) Author: Raymond Hettinger (rhettinger) * (Python committer) Date: 2002-01-30 16:20
Logged In: YES 
user_id=80475

I verified that this has NOT been fixed in Python 2.2:


Python 2.2 (#28, Dec 21 2001, 12:21:22) [MSC 32 bit 
(Intel)] on win32
Type "copyright", "credits" or "license" for more 
information.
IDLE 0.8 -- press F1 for help
>>> i=10
>>> temp = [str(i) for i in range(5)]
>>> print i
4
msg53458 - (view) Author: Nobody/Anonymous (nobody) Date: 2002-01-30 19:33
Logged In: NO 

Oops, I misread your complaint. The bug that was fixed was 
that sometimes the variables end up in the *global* scope.

This was discussed when it was designed and it was decided 
to do it this way.  It's similar to what a regular for loop 
does:

  for i in range(10): pass
  print i

prints 10.

I'll reject this when I can log in to SF again.

--Guido (again)
msg53459 - (view) Author: Nobody/Anonymous (nobody) Date: 2002-01-30 19:34
Logged In: NO 

Sorry, the bug that was fixed was about global scope.

This was discussed when list comprehensions were designed, 
and it was a conscious decision that won't be changed.  
It's the same as for regular for loops.

--Guido (still can't log in)
History
Date User Action Args
2022-04-10 16:04:56adminsetgithub: 35996
2002-01-29 22:13:09rhettingercreate