Weird local variables behaviors

Dan Bishop danb_83 at yahoo.com
Sat Jun 21 05:48:47 CEST 2008


On Jun 20, 7:32 pm, Matt Nordhoff <mnordh... at mattnordhoff.com> wrote:
> Sebastjan Trepca wrote:
> > Hey,
>
> > can someone please explain this behavior:
>
> > The code:
>
> > def test1(value=1):
> >     def inner():
> >         print value
> >     inner()
>
> > def test2(value=2):
> >     def inner():
> >         value = value
> >     inner()
>
> > test1()
> > test2()
>
> > [trepca at sauron ~/dev/tests]$ python locals.py
> > 1
> > Traceback (most recent call last):
> >   File "locals.py", line 13, in <module>
> >     test2()
> >   File "locals.py", line 10, in test2
> >     inner()
> >   File "locals.py", line 9, in inner
> >     value = value
> > UnboundLocalError: local variable 'value' referenced before assignment
>
> > Why can't he find the variable in the second case?
>
> > Thanks, Sebastjan
>
> Python doesn't like when you read a variable that exists in an outer
> scope, then try to assign to it in this scope.
>
> (When you do "a = b", "b" is processed first. In this case, Python
> doesn't find a "value" variable in this scope, so it checks the outer
> scope, and does find it. But then when it gets to the "a = " part...
> well, I don't know, but it doesn't like it.)

In a language like C++, the scope of a variable is determined by the
declaration.

int x; // A
class Example
{
   int x; // B
   void f()
   {
      int x; // C
      x = 42; // Which x?
   }
};

The "x" referred to in the statement "x = 42;" refers to local
variable of Example::f.  If line C were removed, then it would refer
to the member variable of class Example.  And if line B were removed,
then it would refer to the global variable.

In Python, however, there are no declarations.  Therefore, it requires
another approach.  What it chose was:

(1) Explicit "self" for object attributes.
(2) A function's local variables are defined as those appearing on the
left side of an assignment.  Whether the name happens to refer to a
global is NOT considered.



More information about the Python-list mailing list