[New-bugs-announce] [issue11796] list and generator expressions in a class definition fail if expression condition refers to a class variable

Menno Smits report at bugs.python.org
Thu Apr 7 14:55:21 CEST 2011


New submission from Menno Smits <menno at 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 <report at bugs.python.org>
<http://bugs.python.org/issue11796>
_______________________________________


More information about the New-bugs-announce mailing list