python closure with assigning outer variable inside inner function

后端 未结 4 1242
星月不相逢
星月不相逢 2021-01-17 09:18

I\'ve got this piece of code:

#!/usr/bin/env python

def get_match():
  cache=[]
  def match(v):
    if cache:
      return cache
    cache=[v]
    return ca         


        
4条回答
  •  半阙折子戏
    2021-01-17 10:05

    Replace

    cache=[]
    def match(v):
    

    with

    def match(v,cache=[])
    

    Explanation: Your code declares cache as a variable of get_match, which the returned match(v) knows nothing about (due to the following assignment). You do however want cache to be part of match's namespace.

    I know this way a "malevolent" user could redefine cache, but that's their own mistake. Should this be an issue though, the alternative is:

    def match(v):
         try:
             if cache:
                 return cache
         except NameError:
             cache = []
         ...
    

    (See here)

提交回复
热议问题