New submission from din14970 <nielscautae...@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 <rep...@bugs.python.org>
<https://bugs.python.org/issue46549>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to