I have some code like:
def example():
# other logic omitted
stored_blocks = {}
def replace_blocks(m):
block = m.group(0)
block_hash = sha1(block)
stored_blocks[block_hash] = block
return '{{{%s}}}' % block_hash
num_converted = 0
def convert_variables(m):
name = m.group(1)
num_converted += 1
return '<%%= %s %%>' % name
fixed = MATCH_DECLARE_NEW.sub('', template)
fixed = MATCH_PYTHON_BLOCK.sub(replace_blocks, fixed)
fixed = MATCH_FORMAT.sub(convert_variables, fixed)
# more logic...
Adding elements to stored_blocks
works fine, but I cannot increase num_converted
in the second nested function. I get an exception that says UnboundLocalError: local variable 'num_converted' referenced before assignment
.
I know that in 3.x, I could try nonlocal num_converted
, but how can I solve the problem in 2.x? I don't want to use a global variable for this.