[New-bugs-announce] [issue46549] Error in list comprehension conditionals when used in class attributes
din14970
report at bugs.python.org
Thu Jan 27 08:18:58 EST 2022
New submission from din14970 <nielscautaerts at hotmail.com>:
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.
----------
components: Interpreter Core
messages: 411869
nosy: din14970
priority: normal
severity: normal
status: open
title: Error in list comprehension conditionals when used in class attributes
type: behavior
versions: Python 3.10, Python 3.7, Python 3.8, Python 3.9
_______________________________________
Python tracker <report at bugs.python.org>
<https://bugs.python.org/issue46549>
_______________________________________
More information about the New-bugs-announce
mailing list