-1

For some reason, the Python-2.7 timeit function crashes in the following example:

a,b = 0,0
timeit a=b                  # ok: 10000000 loops, best of 3: 50.9 ns per loop
timeit if a==a+b: pass      # ok:  1000000 loops, best of 3: 129 ns per loop
timeit a=a+b                # crashes!

Traceback (most recent call last):
UnboundLocalError: local variable 'a' referenced before assignment

Apparently, I can assign to a (first example), I can compare a to a+b (2nd example), so why can't I run the 3rd example ?!?! Of course, the statement being timed is, by itself, perfectly sound ...

Fabian
  • 4,160
  • 20
  • 32
Rolf Bartstra
  • 1,643
  • 1
  • 16
  • 19

1 Answers1

3

timeit is actually a function but some python interpreters can allow you to use it with a statement's syntax, like IPython, But it is actually a function.

So in a==a+b it actually considers a and b as global variable and therefore no Error, as it can fetch the global a and b.

But in a=a+b it considers a as local variable and b is still global so there it raises the Error, because as soon as python sees assignment inside a function it considers it as a local variable.

it is equivalent to:

In [7]: def func1():
    a==a+b
   ...:     

In [8]: def func():
    a=a+b
   ...:     

In [9]: dis.dis(func1)
  2           0 LOAD_GLOBAL              0 (a)
              3 LOAD_GLOBAL              0 (a)
              6 LOAD_GLOBAL              1 (b)
              9 BINARY_ADD          
             10 COMPARE_OP               2 (==)
             13 POP_TOP             
             14 LOAD_CONST               0 (None)
             17 RETURN_VALUE        

In [10]: dis.dis(func)
  2           0 LOAD_FAST                0 (a)   # but there's nothing to load, so Error
              3 LOAD_GLOBAL              0 (b)
              6 BINARY_ADD          
              7 STORE_FAST               0 (a)
             10 LOAD_CONST               0 (None)
             13 RETURN_VALUE        


In [11]: func()     #same error as yours
---------------------------------------------------------------------------
UnboundLocalError                         Traceback (most recent call last)

UnboundLocalError: local variable 'a' referenced before assignment
Ashwini Chaudhary
  • 244,495
  • 58
  • 464
  • 504
  • Thanks Ashwini, you just taught me some fundamental understanding of functions, statements, and local/global variables ... – Rolf Bartstra Dec 20 '12 at 15:57