0

I stumbled into a weird problem. I narrowed it down to the lines below just to focus on exactly what's happening so, please, don't mind the purposes of this code.

Code is:

dictionary = {
        'key': 'value'
}

class Test:

    a = {**dictionary}

    b = dictionary['key']

    c = {i: dictionary[i] for i in dictionary}

Runs without any problems.

If I change it to:

class Test:

    dictionary = {
        'key': 'value'
    }

    a = {**dictionary}

    b = dictionary['key']

    c = {i: dictionary[i] for i in dictionary}

I'll get this:

Traceback (most recent call last):

File "/home/PythonTest.py", line 2, in class Test:

File "/home/PythonTest.py", line 12, in Test c = {i: dictionary[i] for i in dictionary}

File "/home/PythonTest.py", line 12, in c = {i: dictionary[i] for i in dictionary}

NameError: name 'dictionary' is not defined

Why would the NameError be thrown only on the third assignment? When debugging, I see that assignments to variables a and b work just fine.

0 Answers0