Python闭包:在父作用域中写入变量 [英] Python closure: Write to variable in parent scope

查看:136
本文介绍了Python闭包:在父作用域中写入变量的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在函数中有以下代码:

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中没有一个声音方式来访问只有一个范围界限。只有全局关键字可以将变量引用移出当前范围,它会直接到达顶部。

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 变成单元素数组。

num_converted = [0]
def convert_variables(m):
    name = m.group(1)
    num_converted[0] += 1
    return '<%%= %s %%>' % name

这篇关于Python闭包:在父作用域中写入变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆