Raymond Hettinger <raymond.hettin...@gmail.com> added the comment:

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.

----------
nosy: +rhettinger

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue35625>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to