New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Assigning function parameter to class attribute by the same name #87546
Comments
# Example Consider these three examples, which are theoretically identical
## Expected Output
## Actual Output
|
Was supposed to be: ? Not that that changes your problem. I just want to understand the exact issue. |
# Example Consider these three examples, which are theoretically identical
## Expected Output
## Actual Output
|
Yes sorry that was a typo |
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. |
Looking at the disassembly of the demo() function also shows differences between the B and C classes. I seem to recall discussion about this on, maybe, the Python-Dev list. I think resolving this will probably have to wait on a re-design of the exact scoping rules with respect to classes inside functions. |
Note: these values reflect the state of the issue at the time it was migrated and might not reflect the current state.
Show more details
GitHub fields:
bugs.python.org fields:
The text was updated successfully, but these errors were encountered: