Newbie question

Thomas Heller theller at python.net
Tue Apr 16 13:13:36 EDT 2002


"Ante" <abagaric at rest-art.hr> wrote in message news:a9hhbs$1ksn$1 at as201.hinet.hr...
> from file 'dummy.py'
> ----------------------------
> num = 0
>
> def dummy():
>     num += 1
>
> dummy()
> ----------------------------
>
> now, in the interpreter:
>
> >>> import dummy
> Traceback (most recent call last):
>   File "<string>", line 1, in ?
>   File "C:\downloads\python2.2.1\dummy.py", line 6, in ?
>     dummy()
>   File "C:\downloads\python2.2.1\dummy.py", line 4, in dummy
>     num += 1
> UnboundLocalError: local variable 'num' referenced before assignment
>
>
> Why does this happen?
> If I replace num += 1 with print num, it prints 0 without an error.
> I guess it scans the whole function and check if there's an assignment to a
> name,
> and if there is, assumes it's a local variable. But += isn't supposed to
> move the
> reference but instead change the same variable. Or what did I get wrong?
>
> Ante.
>

Take a look:

C:\>python -OO
Python 2.2.1 (#34, Apr  9 2002, 19:34:33) [MSC 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> num = 1
>>> def f():
...   num += 100
...
>>> f()
Traceback (most recent call last):
  File "<stdin>", line 1, in ?
  File "<stdin>", line 2, in f
UnboundLocalError: local variable 'num' referenced before assignment
>>> import dis
>>> dis.dis(f)
          0 LOAD_FAST                0 (num)
          3 LOAD_CONST               1 (100)
          6 INPLACE_ADD
          7 STORE_FAST               0 (num)
         10 LOAD_CONST               0 (None)
         13 RETURN_VALUE
>>>

Behind the scenes, the value bound to 'num' is retrieved,
100 is added 'inplace', and the result will be stored back.
It wouldn't work otherwise - integers are immutable in Python.

Thomas





More information about the Python-list mailing list