In Python 2, how do I write to variable in the parent scope?

后端 未结 6 550
小蘑菇
小蘑菇 2020-12-07 16:31

I have the following code inside a function:

stored_blocks = {}
def replace_blocks(m):
    block = m.group(0)
    block_hash = sha1(block)
    stored_blocks[         


        
6条回答
  •  隐瞒了意图╮
    2020-12-07 16:46

    Using the global keyword is fine. If you write:

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

    ... num_converted doesn't become a "global variable" (i.e. it doesn't become visible in any other unexpected places), it just means it can be modified inside convert_variables. That seems to be exactly what you want.

    To put it another way, num_converted is already a global variable. All the global num_converted syntax does is tell Python "inside this function, don't create a local num_converted variable, instead, use the existing global one.

提交回复
热议问题