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.

Author rhettinger
Recipients bzip2, docs@python, rhettinger
Date 2019-01-05.04:20:45
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1546662045.53.0.334033020611.issue35625@roundup.psfhosted.org>
In-reply-to
Content
We should remove the "equivalent to for-loops" wording for list comprehensions.  That is a hold-over from 2.7 where it used to be true.  That said, the list comprehension section is too early in the tutorial to go into scopes and generators, so a full explanation will need to be deferred.

> As an aside, I agree with the developers who consider 
> this scope "limitation" a bug and not (paraphrasing) 
> "just how the language works", since the exact same two
> lines of code, which depend on no other variables or 
> functions, work in a function or module but not in a class.

If you view classes as just another nested scope, I can see why you might think the behavior is buggy, limited, or undesirable.  That however is not how the language is designed.  Think about why methods have to reference class variables using "self.classvar" rather than just "classvar".  When the methods run, they have access to their own locals() and to the module level globals().  To access the locals() for the class, they need use "self.classvar" or "classname.classvar".  This is central to how python works .  There are two separate lookup chains, one for variables (locals -> nested scopes -> globals -> __builtins__ -> NameError) and another for attributes (inst_dict -> class_dict -> parent_class_dict -> AttributeError).

Guido intentionally shifted list comprehensions to work like generator expressions.  In a class scope, they behave like methods in that they have access to the outer globals but no direct access to the locals() in the class.
History
Date User Action Args
2019-01-05 04:20:47rhettingersetrecipients: + rhettinger, docs@python, bzip2
2019-01-05 04:20:45rhettingersetmessageid: <1546662045.53.0.334033020611.issue35625@roundup.psfhosted.org>
2019-01-05 04:20:45rhettingerlinkissue35625 messages
2019-01-05 04:20:45rhettingercreate