我有一些类似这样的代码:
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...
将元素添加到stored_blocks
中运作良好,但我无法增加嵌套函数中的num_converted
。我得到一个异常,说UnboundLocalError: local variable 'num_converted' referenced before assignment
。
我知道在3.x中,我可以尝试使用nonlocal num_converted
,但我怎样才能解决2.x中的这个问题呢?我不想为此使用全局变量。
def
不是唯一定义命名空间的关键字:还有class
。 - Jochen Ritzel