[issue43380] Assigning function parameter to class attribute by the same name

Steven D'Aprano report at bugs.python.org
Wed Mar 3 03:55:52 EST 2021


Steven D'Aprano <steve+python at 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 <report at bugs.python.org>
<https://bugs.python.org/issue43380>
_______________________________________


More information about the Python-bugs-list mailing list