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.

Author steven.daprano
Recipients eric.smith, jennydaman, steven.daprano
Date 2021-03-03.08:55:51
SpamBayes Score -1.0
Marked as misclassified Yes
Message-id <1614761752.62.0.570140244342.issue43380@roundup.psfhosted.org>
In-reply-to
Content
Here's an example that shows what is going on:


def demo():
    a = 1
    class B:
        x = a
    print(B.x)  # Okay.
    
    class C:
        x = a  # Fails.
        if False:
            a = None
    print(C.x)


If you run that, B.x is printed (1) but assigning to C.x fails:

>>> demo()
1
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<stdin>", line 7, in demo
  File "<stdin>", line 8, in C
NameError: name 'a' is not defined


The reason is that inside a function, assignment to a name makes it a local. This interacts oddly with class scope.

By the way, I get the same results with this all the way back to Python 2.4. (I don't have older versions to test.) So this has existed for a very long time.
History
Date User Action Args
2021-03-03 08:55:52steven.dapranosetrecipients: + steven.daprano, eric.smith, jennydaman
2021-03-03 08:55:52steven.dapranosetmessageid: <1614761752.62.0.570140244342.issue43380@roundup.psfhosted.org>
2021-03-03 08:55:52steven.dapranolinkissue43380 messages
2021-03-03 08:55:51steven.dapranocreate