Binding frustration

Rob Hunter rob at cs.brown.edu
Thu Sep 18 17:31:17 EDT 2003


So I thought I had come to peace with binding in Python, but then this 
happened to me:

I was trying to do things the Python way (as opposed to the Scheme way) 
as was suggested to me, and so here's a shortened version of my program:

def getGenres(title):  #it takes a movie title and returns a list of 
genres that the movie falls into

     result = [] # my accumulator

     def inGenre(g): # g is a genre
         if <here I test if "title" is of genre g (using a simple Python 
dictionary I have collected from a mini web crawl)>:
               result = result + [g] # if title is of genre g, then add 
it to the accumulator

      # and then I do a number of inGenre tests:
      inGenre('Comedy')
      inGenre('Sci-fi')
      inGenre('Suspense')
      ...
      return result

So what's wrong with this program?  Well, Python tells me:

UnboundLocalError: local variable 'result' referenced before assignment

It seems my only choice is to move result to the global environment, 
but if that's not a kludge, I don't know what is.  So why doesn't this 
work?  Python lambdas are able to use "free" variables in this way.  
Why not a def?  And more importantly, how should I get around this?

Thanks all,

Rob






More information about the Python-list mailing list