scopes? (is: I don't get it ...)

Terry Reedy tjreedy at udel.edu
Thu May 29 15:23:58 EDT 2003


"Axel Bock" <news-and-lists at the-me.de> wrote in message
news:pan.2003.05.29.18.28.57.897132 at the-me.de...
> Am Thu, 29 May 2003 10:21:00 -0700 schrieb djw:
>
> > In order to assign to a global in a funtion, you must use the
global
> > statement, otherwise Python will assume you are assigning to a
local.
> > That's the way I understand it, anyway.
> >
> > test.py:
> > t1 = []
> > t2 = 0
> > def testme():
> >         global t2
> >         print t1
> >         print t2
> >         t2+=1

> whew, yes, thanks all of you! this helps ... ! :-)

Here are two more examples to consider...

>>> x=1
>>> def f():
...   x=2
...   global x
...
<stdin>:1: SyntaxWarning: name 'x' is assigned to before global
declaration
>>> f()
>>> x
2

# So put global statements at the top, even if not yet required.

>>> def g():
...   print x
...   x=3
...
>>> g()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in g
UnboundLocalError: local variable 'x' referenced before assignment

Some newbies expect printing of 2 instead of the error.  But the
interpreter reads the whole function text to classify variables as
local or not before starting again from the top to compile.

Terry J. Reedy






More information about the Python-list mailing list