%timeit和变量的重新分配 [英] %timeit and re-assignment of variable
本文介绍了%timeit和变量的重新分配的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
令人惊讶的ipython magic %timeit
错误:
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
因此,%timeit
不喜欢自我重新分配.为什么?无论如何要克服这个问题?
So %timeit
doesn't like self re-assignment. Why? Anyway to overcome this?
推荐答案
与基础的timeit
模块一样,定时语句被集成到执行定时的生成函数中.分配给a
会使函数具有a
局部变量,从而隐藏全局变量.就像你做完一样的问题
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.
这篇关于%timeit和变量的重新分配的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文