python闭包变量作用域_Python闭包:在父作用域中写入变量

1586010002-jmsa.png

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)

Adding elements to stored_blocks works fine, but I cannot increase num_converted in the second subfunction:

UnboundLocalError: local variable 'num_converted' referenced before assignment

I could use global but global variables are ugly and I really don't need that variable to be global at all.

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.

解决方案

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.

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闭包变量作用域_Python学...

一、全局变量与局部变量一个模块中,最高级别的变量有全局作用域。全局变量一个特征就是:除非...

继续阅读

python变量及其作用域,闭包

http://blog.csdn.net/pipisorry/article/details/42525939建议参考[Python核心编程2ed.pdf:11...

继续阅读

python闭包变量_Python变量作用...

1、引言最近在刷leetcode题的时候,遇到一个求最长回文子串的题目,于是,我写了如下的代码:c...

继续阅读

python函数作用域与闭包_理解 Py...

未经作者允许,请勿转载,违者必追究责任。1.作用域Python的作用域可以分为四种:L(Local)局部...

继续阅读

python变量作用域图解_Python学...

1.作用域Python的作用域可以分为四种:L(Local)局部作用域E(Enclosing)闭包函数外的函数中...

继续阅读

python什么是闭包的作用域_Pytho...

什么是闭包在维基中,闭包的解释是这样的:在计算机科学中,闭包(Closure)是词法闭包(LexicalC...

继续阅读

python变量作用域_Python变量作...

变量作用域一个程序的所有的变量并不是在哪个位置都可以访问的。访问权限决定于这个变量是在哪...

继续阅读

python变量作用域_Python变量作...

各位小伙伴,新年快乐!今天是2018年的第一个工作日,不知道经过三天的休整和庆祝,各位的身心...

继续阅读

python 中函数对象、闭包、作用...

函数对象函数名是存放了函数的内存地址,存放了内存地址的变量都是对象,即函数名就是函数对象...

继续阅读

python 变量作用域_Python 3 学...

1.变量作用域Python中,程序的变量并不是在哪个位置都可以访问的,访问权限决定于这个变量是在...

继续阅读