Issue
Surprising ipython magic %timeit
error:
In[1]: a = 2
In[2]: %timeit a = 2 * a
Traceback (most recent call last):
File "...\site-packages\IPython\core\interactiveshell.py", line 3326, in run_code
exec(code_obj, self.user_global_ns, self.user_ns)
File "<ipython-input-97-6f70919654d1>", line 1, in <module>
get_ipython().run_line_magic('timeit', 'a = 2 * a')
File "...\site-packages\IPython\core\interactiveshell.py", line 2314, in run_line_magic
result = fn(*args, **kwargs)
File "<...\site-packages\decorator.py:decorator-gen-61>", line 2, in timeit
File "...\site-packages\IPython\core\magic.py", line 187, in <lambda>
call = lambda f, *a, **k: f(*a, **k)
File "...\site-packages\IPython\core\magics\execution.py", line 1158, in timeit
time_number = timer.timeit(number)
File "...\site-packages\IPython\core\magics\execution.py", line 169, in timeit
timing = self.inner(it, self.timer)
File "<magic-timeit>", line 1, in inner
UnboundLocalError: local variable 'a' referenced before assignment
So %timeit
doesn't like self re-assignment. Why? Anyway to overcome this?
Solution
As with the underlying timeit
module, the timed statement is integrated into a generated function that performs the timing. The assignment to a
causes the function to have an a
local variable, hiding the global. It's the same issue as if you had done
a = 2
def f():
a = 2 * a
f()
although the generated function has more code than that.
Answered By - user2357112 supports Monica
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.