Binding frustration

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


So it just occurred to me that probably, in this case, the Python way 
is the Scheme way:

def getGenres(title):

     def inGenre(g):
         return <boolean test using g and title and the dictionary>

     return filter(inGenre, ['Comedy','Suspense', ...])

:)

But still, wrt my original complaint, doesn't it seem wrong that I 
couldn't write that program?

Rob

On Thursday, September 18, 2003, at 05:31 PM, Rob Hunter wrote:

> 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
>
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>






More information about the Python-list mailing list