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 mjs0
Recipients mjs0
Date 2011-04-07.12:55:20
SpamBayes Score 7.5201234e-11
Marked as misclassified No
Message-id <1302180921.17.0.22284518515.issue11796@psf.upfronthosting.co.za>
In-reply-to
Content
A list comprehension or generator expression in a class definition fails with NameError if it has a condition that refers to another class variable. This doesn't occur if the class variable is used the "in" part of the expression.

The following works:

class Foo:
    x = range(3)
    y = [z for z in x]

but this doesn't:

class Foo:
    x = 3
    y = [z for z in range(5) if z < x]

The error reported is: NameError: global name 'x' is not defined

Both of these examples work in Python 2.

Issue3692 suggests that class variables can't be referred to inside list comprehensions and gen expressions inside class definitions and that this won't be fixed, but these examples show that it is possible to refer to an outside class variable depending on usage. This is inconsistent and confusing.

The Python 2 behaviour makes much more sense. I understand that we don't want list comprehensions to leak internal variables but they should still be able to pull names from outside scopes in a consistent way.
History
Date User Action Args
2011-04-07 12:55:21mjs0setrecipients: + mjs0
2011-04-07 12:55:21mjs0setmessageid: <1302180921.17.0.22284518515.issue11796@psf.upfronthosting.co.za>
2011-04-07 12:55:20mjs0linkissue11796 messages
2011-04-07 12:55:20mjs0create