Created
December 7, 2010 04:16
-
-
Save kevinclark/731446 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
>>> b = 0 | |
>>> def incB(): | |
... b += 1 | |
... | |
>>> c = [] | |
>>> def addC(): | |
... c.append(1) | |
... | |
>>> b | |
0 | |
>>> c | |
[] | |
>>> incB() | |
Traceback (most recent call last): | |
File "<stdin>", line 1, in <module> | |
File "<stdin>", line 2, in incB | |
UnboundLocalError: local variable 'b' referenced before assignment | |
>>> addC() | |
>>> c | |
[1] |
Yep, the reason it happens makes sense. But it's the old 'const ptr vs ptr to const' issue. Seems like we should be able to avoid that by now in high level languages. I'd actually prefer if 'global' was required to access the external scope.
Heh I wouldn't mind that either since I absolutely hate globals in code that are not constants declared in ALL_CAPS. I really doubt that'd fly if suggested on python-ideas@ though. ;)
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
http://docs.python.org/library/exceptions.html#exceptions.UnboundLocalError
http://docs.python.org/reference/simple_stmts.html#the-global-statement
b += 1 is really doing b = b + 1. within the function, python determined that you have a local called b when parsing the code during the function definition but as you haven't assigned to it yet during the b + 1 RHS it is an "unbound local".
If you want to assign a value to a global from a function or method you need to use the 'global foo' statement within the function. Its a good thing as it makes code that is modifying a global much more obvious when reading it. It is only needed when the assignment is ambiguious as it woudl be in this case. does "b = b + 1" mean you want a new local called b to have the value of the global b + 1? or did you want to reassign the global b? python doesn't allow you to both reference a global in a function and reassign a value to a local of the same name.