Steven D'Aprano <steve+pyt...@pearwood.info> added the comment:

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.

----------
nosy: +steven.daprano

_______________________________________
Python tracker <rep...@bugs.python.org>
<https://bugs.python.org/issue43380>
_______________________________________
_______________________________________________
Python-bugs-list mailing list
Unsubscribe: 
https://mail.python.org/mailman/options/python-bugs-list/archive%40mail-archive.com

Reply via email to