Binding frustration

R

Rob Hunter

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
 
J

JCM

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

Here you're attempting to rebind a variable which lives in an
enclosing scope. This isn't possible in Python (except for globals).
Use result.append(g) instead and it should work.
 
T

Terry Reedy

Rob Hunter said:
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

UnboundLocalError: local variable 'result' referenced before
assignment

When, within a function, you assign to a variable that has not been
declared global, then you implicitly declare that variable to be local
to the function -- in this case, inGenre(). But local var 'result'
has not previously been assigned a value within inGenre. Hence the
error message. As JCM said, try result.append(g).

Terry J. Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,768
Messages
2,569,575
Members
45,053
Latest member
billing-software

Latest Threads

Top