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

后端 未结 6 568
小蘑菇
小蘑菇 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:55

    (see below for the edited answer)

    You can use something like:

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

    This way, num_converted works as a C-like "static" variable of the convert_variable method


    (edited)

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

    This way, you don't need to initialize the counter in the main procedure.

提交回复
热议问题