Beginnger Question

Terry Reedy tejarex at yahoo.com
Wed Apr 10 10:03:19 EDT 2002


"Sibylle Koczian" <Sibylle.Koczian at Bibliothek.Uni-Augsburg.de> wrote
in message news:a914t4$g70$1 at rzmux02.rz.uni-augsburg.de...
> >I'm a newbie myself, so this is probably wrong, but wouldn't this
be *even*
> >better?
> >
> >x = 2
> >def wrong(num):
> >    x = x+1
> >    print x

No, this should be

def incx():
  global x
  x = x+1

x = 2
incx()
print x
# prints 3

> Traceback (most recent call last):
>   File "<interactive input>", line 1, in ?
>   File "<interactive input>", line 2, in wrong
> UnboundLocalError: local variable 'x' referenced before assignment
>
> I think the exception is new (result of nested scopes?), but it's
quite
> probable you meant to write

No, message means just what it says: without global declaration, name
bound to new value is taken to be local, but its value is requested
before being set.

> for the reason already stated: call by value, which works on a copy
of the
> parameter inside the function and doesn't change the parameter
itself.
> (Would be the same in C, by the way.)

Python namespaces associate names and objects via object references.
Function calls are call by reference: a *new* name (the parameter name
in the function definition) is bound to each reference within the
function's local namespace.  The reference is copied (and the the
reference count bumped up), not the value.  This 'call-binding' is
undone by any subsequent assignment to the parameter name within the
function.

>>> x = 0
>>> def test(y):
...   print y is x
...   y = y+1
...   print y is x
...
>>> test(x)
1
0

Terry J. Reedy







More information about the Python-list mailing list