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.

classification
Title: NameError on if clause of class-level list comprehension
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.10
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: ThiefMaster, jhpfjyne, mark.dickinson, mrabarnett
Priority: normal Keywords:

Created on 2021-11-25 15:16 by jhpfjyne, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg407002 - (view) Author: (jhpfjyne) Date: 2021-11-25 15:16
Accessing an attribute defined at class-level in the if clause of a list comprehension at class-level throws a NameError.

>>> class Foo:
...     a = ['a', 'b']
...     b = ['b', 'c']
...     c = [x for x in a if x not in b]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in Foo
  File "<stdin>", line 4, in <listcomp>
NameError: name 'b' is not defined
msg407003 - (view) Author: Mark Dickinson (mark.dickinson) * (Python committer) Date: 2021-11-25 15:42
This is expected behaviour. See the docs here: https://docs.python.org/3.9/reference/executionmodel.html#resolution-of-names

> The scope of names defined in a class block is limited to the class block; it does not extend to the code blocks of methods – this includes comprehensions and generator expressions since they are implemented using a function scope.
msg407004 - (view) Author: Matthew Barnett (mrabarnett) * (Python triager) Date: 2021-11-25 15:50
It's not just in the 'if' clause:

>>> class Foo:
...     a = ['a', 'b']
...     b = ['b', 'c']
...     c = [b for x in a]
...
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 4, in Foo
  File "<stdin>", line 4, in <listcomp>
NameError: name 'b' is not defined
History
Date User Action Args
2022-04-11 14:59:52adminsetgithub: 90057
2021-11-25 15:50:09mrabarnettsetnosy: + mrabarnett
messages: + msg407004
2021-11-25 15:42:54mark.dickinsonsetstatus: open -> closed

nosy: + mark.dickinson
messages: + msg407003

resolution: not a bug
stage: resolved
2021-11-25 15:24:08ThiefMastersetnosy: + ThiefMaster
2021-11-25 15:16:34jhpfjynecreate