I'll try to add something to the good answers Oscar and Martijn already gave.
When you read a function in python, any function, you have to read it twice. Always.
In the first pass, you should do this: for each global
and nonlocal
declaration statement, move them (conceptually) to the beginning of the function.
For each statement of the following forms
* x = expr (or "x += expr", "x *= expr", etc.)
* for x in expr:
* with expr as x:
* def x(...):
* class x:
* import x (or "import foo as x")
* from some_module import x (or "from some_module import foo as x")
Take the name x, and see: if it is declared in a global
or nonlocal
statement, leave it there. Otherwise, add it to a local
declaration, right after the global
and nonlocal
. (There's no local
keyword in python. It's all conceptually). Function parameters are always local. The names in these statements should be mutually exclusive, just like the scopes they refer to.
This was the first pass. Now you can sit and read the code. Any time you see a variable name, you look it up on these three statement - global
, nonlocal
and our imaginary local
. If the name is there - you know where it belongs. Otherwise, look it up in the same way on any enclosing function, then in the global namespace. If it's not there, it should be a built in - or an error.
Having done that for update()
, you'd get:
def update():
local testing # not real python code
print "UPDATED"
testing = 2
Well, that's not what you meant, right?
Another example, before:
x=3
def print5():
for i in range(5):
print(x)
x += 1
After:
x=3
def print5():
local i, x
for i in range(5):
print(x) # oops. x is local but was not assigned!
x += 1
Note that the algorithm I described is not full. I left out exceptions, which hide names for the except
clause only; eval
and exec
; and from some_module import *
.
For complete information, see the docs: http://docs.python.org/2/reference/executionmodel.html#naming-and-binding