classification
Title: Set comprehension + eval doesn't work inside function definition
Type: Stage: resolved
Components: Versions: Python 2.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Ariel Bruner, ned.deily
Priority: normal Keywords:

Created on 2015-03-19 21:31 by Ariel Bruner, last changed 2015-03-19 21:52 by ned.deily. This issue is now closed.

Messages (2)
msg238561 - (view) Author: Ariel Bruner (Ariel Bruner) Date: 2015-03-19 21:31
The following code gives a NameError:

>>> def foo(bar):
	print {eval(x) for x in ['bar']}


>>> foo(2)

Traceback (most recent call last):
  File "<pyshell#52>", line 1, in <module>
    foo(2)
  File "<pyshell#51>", line 2, in foo
    print {eval(x) for x in ['bar']}
  File "<pyshell#51>", line 2, in <setcomp>
    print {eval(x) for x in ['bar']}
  File "<string>", line 1, in <module>
NameError: name 'bar' is not defined

I've seen this kind of bug reported for Python 3.X (e.g. Issue5242), and the behavior seems to be identical (e.g. can be fixed with {eval(x) for x in ['bar'] if True or bar}), but the previously reported bug reports mention comprehension is implemented differently on 2.X and that it should not happen there, so I thought that might be of interest.
msg238563 - (view) Author: Ned Deily (ned.deily) * (Python committer) Date: 2015-03-19 21:52
Thanks for the report.  Your example is of a set comprehension.  Set and dictionary comprehensions were Python 3.1 features backported to Python 2.7 for compatibility and thus had no existing Python 2 compatibility concerns.  If you try a similar example using list comprehensions, which have been around in Python 2 for a long time, you'll see there is a difference in behavior between Python 2 and 3, which is what under discussion in Issue5242.

https://docs.python.org/2/whatsnew/2.7.html#python-3-1-features
History
Date User Action Args
2015-03-19 21:52:08ned.deilysetmessages: - msg238562
2015-03-19 21:52:00ned.deilysetmessages: + msg238563
2015-03-19 21:49:25ned.deilysetstatus: open -> closed

components: - Windows
title: Comprehension + eval doesn't work inside function definition -> Set comprehension + eval doesn't work inside function definition
nosy: + ned.deily, - tim.golden, zach.ware, steve.dower

messages: + msg238562
resolution: not a bug
stage: resolved
2015-03-19 21:31:47Ariel Brunercreate