Binding frustration

Rob Hunter rob at cs.brown.edu
Thu Sep 18 18:58:51 EDT 2003


On Thursday, September 18, 2003, at 06:21 PM, Terry Reedy wrote:

>
> "Rob Hunter" <rob at cs.brown.edu> wrote in message
> news:mailman.1063920805.24865.python-list at python.org...
>>      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).

So it seems that if Python made a syntactic distinction between 
introducing a new binding, and assigning to an old one, then this 
problem would go away.  That's what is happening with result.append(g), 
right?  Because of the syntax in this statement (ie, there's no "=" in 
it), Python knows that _result_ must exist, so it goes and looks for 
it.  But, IMO, I *should* be allowed to use the + (append) operator.  
Because there is no syntax for a new binding (like LET, for example), 
Python awkwardly forces the programmer to choose either the local scope 
or the global one when it comes to assignment.  And so, in my case, it 
forces me to use another (but semantically, quite similar) language 
construct.

Does anyone know why they didn't have an explicitly new binding syntax? 
  Perhaps to minimize the initial part of the learning curve.  This 
makes sense, but I would have much preferred it the other way.

Rob

>
> Terry J. Reedy
>
>
> -- 
> http://mail.python.org/mailman/listinfo/python-list
>






More information about the Python-list mailing list