在 Python 2 中,如何写入父作用域中的变量? [英] In Python 2, how do I write to variable in the parent scope?
问题描述
我在一个函数中有以下代码:
I have the following code inside a function:
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
:
Adding elements to stored_blocks
works fine, but I cannot increase num_converted
in the second subfunction:
UnboundLocalError: 赋值前引用了局部变量 'num_converted'
UnboundLocalError: local variable 'num_converted' referenced before assignment
我可以使用 global
但全局变量很难看,我真的不需要那个变量是全局的.
I could use global
but global variables are ugly and I really don't need that variable to be global at all.
所以我很好奇如何写入父函数作用域中的变量.nonlocal num_converted
可能会完成这项工作,但我需要一个适用于 Python 2.x 的解决方案.
So I'm curious how I can write to a variable in the parent function's scope.
nonlocal num_converted
would probably do the job, but I need a solution that works with Python 2.x.
推荐答案
问题: 这是因为 Python 的范围规则已经过时了.+=
赋值运算符的存在将目标 num_converted
标记为封闭函数范围的局部,并且在 Python 2.x 中没有健全的方法来访问一个范围水平从那里.只有 global
关键字可以将变量引用提升到当前作用域之外,它会将您直接带到顶部.
Problem: This is because Python's scoping rules are demented. The presence of the +=
assignment operator marks the target, num_converted
, as local to the enclosing function's scope, and there is no sound way in Python 2.x to access just one scoping level out from there. Only the global
keyword can lift variable references out of the current scope, and it takes you straight to the top.
修正:将 num_converted
变成单元素数组.
Fix: Turn num_converted
into a single-element array.
num_converted = [0]
def convert_variables(m):
name = m.group(1)
num_converted[0] += 1
return '<%%= %s %%>' % name
这篇关于在 Python 2 中,如何写入父作用域中的变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!