我有一个函数内部下面的代码:Python的封:写入变量父范围
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)
将元素添加到stored_blocks
工作正常,但在第二子功能我不能增加num_converted
:
UnboundLocalError: local variable 'num_converted' referenced before assignment
我可以使用global
但全局变量是丑陋的,我真的不需要该变量是全球性的。
所以我很好奇我如何写入父函数范围内的变量。 nonlocal num_converted
可能会完成这项工作,但我需要一个适用于Python 2.x的解决方案。
与某些流行的观点相反(通过这类问题来判断)`def`并不是唯一定义名称空间的关键字:也有'class`。 – 2011-01-31 14:22:41