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: Error in list comprehension conditionals when used in class attributes
Type: behavior Stage: resolved
Components: Interpreter Core Versions: Python 3.10, Python 3.9, Python 3.8, Python 3.7
process
Status: closed Resolution: not a bug
Dependencies: Superseder:
Assigned To: Nosy List: Dennis Sweeney, din14970
Priority: normal Keywords:

Created on 2022-01-27 13:18 by din14970, last changed 2022-04-11 14:59 by admin. This issue is now closed.

Messages (3)
msg411869 - (view) Author: (din14970) Date: 2022-01-27 13:18
I discovered this one by accident. When using a conditional inside a list comprehension in class attributes one can get some unexpected behavior. The following does not work:

```
class TestClass:
    list_1 = [1, 2, 3, 4, 5]
    exclude = [2, 4]
    list_2 = [i for i in list_1 if i not in exclude]
```

It throws a `NameError` saying exclude isn't defined. The following snippets do work:

```
exclude = [2, 4]

class TestClass:
    list_1 = [1, 2, 3, 4, 5]    
    list_2 = [i for i in list_1 if i not in exclude]
```

```
class TestClass:
    list_1 = [1, 2, 3, 4, 5]
    exclude = [2, 4]
    list_2 = []
    for i in list_1:
         if i not in exclude:
               list_2.append(i)    
```

```
class TestClass:
    list_1 = [1, 2, 3, 4, 5]
    exclude = [2, 4]
    list_2 = [i for i in list_1]
```


So it seems that only when a class attribute is used in the conditional part of another class attribute a `NameError` is raised.
msg411873 - (view) Author: Dennis Sweeney (Dennis Sweeney) * (Python committer) Date: 2022-01-27 13:51
I believe this is a duplicate of bpo-45899
msg411875 - (view) Author: Dennis Sweeney (Dennis Sweeney) * (Python committer) Date: 2022-01-27 13:54
See also https://stackoverflow.com/questions/13905741/accessing-class-variables-from-a-list-comprehension-in-the-class-definition
History
Date User Action Args
2022-04-11 14:59:55adminsetgithub: 90707
2022-01-27 13:54:25Dennis Sweeneysetstatus: open -> closed
resolution: not a bug
messages: + msg411875

stage: resolved
2022-01-27 13:51:29Dennis Sweeneysetnosy: + Dennis Sweeney
messages: + msg411873
2022-01-27 13:18:58din14970create