Python nested function scopes
- by Thomas O
I have code like this:
def write_postcodes(self):
"""Write postcodes database. Write data to file pointer. Data
is ordered. Initially index pages are written, grouping postcodes by
the first three characters, allowing for faster searching."""
status("POSTCODE", "Preparing to sort...", 0, 1)
# This function returns the key of x whilst updating the displayed
# status of the sort.
ctr = 0
def keyfunc(x):
ctr += 1
status("POSTCODE", "Sorting postcodes", ctr, len(self.postcodes))
return x
sort_res = self.postcodes[:]
sort_res.sort(key=keyfunc)
But ctr responds with a NameError:
Traceback (most recent call last):
File "PostcodeWriter.py", line 53, in <module>
w.write_postcodes()
File "PostcodeWriter.py", line 47, in write_postcodes
sort_res.sort(key=keyfunc)
File "PostcodeWriter.py", line 43, in keyfunc
ctr += 1
UnboundLocalError: local variable 'ctr' referenced before assignment
How can I fix this? I thought nester scopes would have allowed me to do this. I've tried with 'global', but it still doesn't work.