python closure with assigning outer variable inside inner function

后端 未结 4 1237
星月不相逢
星月不相逢 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:21

    Since Python sees cache=[v] - assignment to cache, it treats it as local variable. So the error is pretty reasonable - no local variable cache was defined prior to its usage in if statement.

    You probably want to write it as:

    def get_match():
      cache=[]
      def match(v):
        if cache:
          return cache
        cache.append(v)
        return cache
      return match
    m = get_match()
    m(1)
    

    Highly recommended readings: Execution Model - Naming and binding and PEP 227 - Statically Nested Scopes

提交回复
热议问题