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 bzip2
Recipients bzip2, docs@python
Date 2018-12-31.10:48:00
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1546253280.49.0.920078772343.issue35625@roundup.psfhosted.org>
In-reply-to
Content
The sections on list, set and dict comprehensions in the tutorial on data structures (ref. 1) state repeatedly that they are equivalent to for loops, but do not mention that this is not true in classes. In fact, the example used for nested list comprehensions (section 5.1.4) will work in a function, but not in a class. Similarly, there seems to be no mention of this scope "limitation" in the tutorial on classes (ref. 2), despite a section on scopes and namespaces (section 9.2) and another that mentions list comprehensions (section 9.10). The scope "limitation" is mentioned at the end of a section on resolution of names on a page about the execution model in the reference guide (ref. 3), and of course in various forums, where people may perhaps eventually find them after wasting time trying to figure out what they've done wrong.

If comprehensions are "equivalent" to for loops only under certain conditions (in a class, but only in a class, only one variable from outside the comprehension is accessible in the comprehension, and it must be the outermost iterable), they are not equivalent and should not be described as such. This "limitation" should be mentioned prominently wherever comprehensions are described, since both classes and comprehensions are presumably common constructs. When people read "is equivalent to" without a qualifier, they assume "is always equivalent to".

Returning to section 9.10 in ref. 2, the unique_words example is misleading because it strongly implies that nested for loops in a comprehension should work in a class. Since that's only true in some cases, the example should be qualified. More broadly, because that tutorial is about classes, the relevance of the last three sections should be revisited.

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.

1. https://docs.python.org/3/tutorial/datastructures.html
2. https://docs.python.org/3/tutorial/classes.html
3. https://docs.python.org/3/reference/executionmodel.html
History
Date User Action Args
2018-12-31 10:48:02bzip2setrecipients: + bzip2, docs@python
2018-12-31 10:48:00bzip2setmessageid: <1546253280.49.0.920078772343.issue35625@roundup.psfhosted.org>
2018-12-31 10:48:00bzip2linkissue35625 messages
2018-12-31 10:48:00bzip2create