New submission from Menno Smits <me...@freshfoo.com>:

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.

----------
components: Interpreter Core
messages: 133213
nosy: mjs0
priority: normal
severity: normal
status: open
title: list and generator expressions in a class definition fail if expression 
condition refers to a class variable
type: behavior
versions: Python 3.2

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

Reply via email to