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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值