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 …
timeitis actually a function but some python interpreters can allow you to use it with a statement‘s syntax, likeIPython, But it is actually a function.So in
a==a+bit actually considersaandbas global variable and therefore no Error, as it can fetch the globalaandb.But in
a=a+bit considersaas local variable andbis 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: