On Mon, Jul 8, 2013 at 8:26 AM, Tim Hanson <tjhan...@yahoo.com> wrote:
> In the first Lutz book, I am learning about nested functions. > > Here's the book's example demonstrating global scope: > >>> def f1(): > x=88 > def f2(): > print(x) > f2() > > > >>> f1() > 88 > > No problem so far. I made a change and ran it again: > > >>> def f1(): > x=88 > def f2(): > print(x) > x=99 > print(x) > f2() > > > >>> f1() > Traceback (most recent call last): > File "<pyshell#11>", line 1, in <module> > f1() > File "<pyshell#10>", line 7, in f1 > f2() > File "<pyshell#10>", line 4, in f2 > print(x) > UnboundLocalError: local variable 'x' referenced before assignment > > This doesn't work. To my mind,in f2() I first print(x) then assign a > variable > with the same name in the local scope, then print the changed x. Why > doesn't > this work? > This doesn't work because, if you assign a local variable anywhere in a function, python assumes that all variables with that name in the entire function refer to the one in local scope. In other words, you can't have two variables with the same name from different scopes exist in one function. The reasons behind this are partly technical, and partly philosophical. Technically, the frame that contains all of a function's local names is created when you enter that function, which means that even when the local 'x' has not yet been assigned it exists in the frame, masking the global variable. Philosophically, using two identical names from different scopes leads to difficult to understand code that is very easy to introduce subtle bugs into. You may either use a 'global x' statement to indicate to python that you're using the name from the global scope, or pass the value of the global in through a function argument and use the local name. HTH, Hugo
_______________________________________________ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor