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: Can't do dict comp from previously defined dict in the outermost scope of class defintion
Type: behavior Stage: resolved
Components: IDLE, Interpreter Core, Windows Versions: Python 3.6
process
Status: closed Resolution: not a bug
Dependencies: Superseder: Comprehensions in a class definition mostly cannot access class variable
View: 11796
Assigned To: Nosy List: Assume_Away, paul.moore, steve.dower, tim.golden, xiang.zhang, zach.ware
Priority: normal Keywords:

Created on 2016-12-19 03:17 by Assume_Away, last changed 2022-04-11 14:58 by admin. This issue is now closed.

Messages (3)
msg283575 - (view) Author: Dan Snider (Assume_Away) * Date: 2016-12-19 03:17
class MyClass:
    a_dict = {'key':'value'}
    r_dict = {a_dict[k]:k for k in a_dict}
    
throws the error: 

Traceback (most recent call last):
  File "C:/Users/D/AppData/Local/Programs/Python/Python35-32/deleteme.py", line 1, in <module>
    class MyClass:
  File "C:/Users/D/AppData/Local/Programs/Python/Python35-32/deleteme.py", line 3, in MyClass
    r_dict = {a_dict[k]:k for k in a_dict}
  File "C:/Users/D/AppData/Local/Programs/Python/Python35-32/deleteme.py", line 3, in <dictcomp>
    r_dict = {a_dict[k]:k for k in a_dict}
NameError: name 'a_dict' is not defined
msg283576 - (view) Author: Xiang Zhang (xiang.zhang) * (Python committer) Date: 2016-12-19 03:39
This is by design in 3.x. You can refer #11796 for explanation.
msg283577 - (view) Author: Xiang Zhang (xiang.zhang) * (Python committer) Date: 2016-12-19 04:10
Also http://stackoverflow.com/a/4199355/2189957.
History
Date User Action Args
2022-04-11 14:58:40adminsetgithub: 73194
2016-12-19 04:30:27terry.reedysetassignee: terry.reedy ->

nosy: - terry.reedy
2016-12-19 04:10:12xiang.zhangsetmessages: + msg283577
2016-12-19 03:39:53xiang.zhangsetstatus: open -> closed

superseder: Comprehensions in a class definition mostly cannot access class variable

nosy: + xiang.zhang
messages: + msg283576
resolution: not a bug
stage: resolved
2016-12-19 03:17:19Assume_Awaycreate