在Python 2中,如何在父范围中写入变量? [英] In Python 2, how do I write to variable in the parent scope?

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

问题描述

我在函数中包含以下代码:

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.

所以我很好奇如何在父函数的作用域中写入变量。
非本地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屋!

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