[Tutor] "local variable 'l1' referenced before assignment"

Dick Moores rdm at rcblue.com
Sat Jun 28 11:03:32 CEST 2008


At 01:05 AM 6/28/2008, Alan Gauld wrote:

>"Dick Moores" <rdm at rcblue.com> wrote
>
>
>>I'm puzzled by the below error msg. If I change the line in a2() from
>>
>>l1 = [1,2,3]*100
>
>This is not in a2() this is in the global namespace outside of a2.
>a2() consists of a single assignment statement. And assignment
>inside a function creates a local variable which in this case
>masks the global variable. But the local variable assignment
>uses the same variable which is not allowed so you get the
>error message.
>
>>Why? And why isn't that line a problem for a1()?
>
>In a1 you don't assign so you never create a local variable
>you use the global variable
>
>
>>=========================================
>>def a1():
>>        return l1.extend(l2)
>
>No assignment, it returns the global value
>
>>if __name__=='__main__':
>>        l1 = [1,2,3]*100
>>        t = Timer("a1()", "from __main__ import a1")
>
>
>>def a2():
>>        l1 += l2
>
>new local variable "created" but erroneously. Change to
>
>def a2():
>     global I1
>     I1 += I2
>     return I1
>
>See my tutor topic on namespaces for more on this theme.

Thanks very much Alan. I think I've got it now, but I will study that 
section in your tutorial.

And my thanks also to Douglas Drumond.

 >>> import this
[snip]
Namespaces are one honking great idea -- let's do more of those!
 >>>

Dick 



More information about the Tutor mailing list