为什么IPython的timeit不能与set原义一起使用?

使用设置文字时,IPython timeit有时会中断:

In [1]: timeit 'potato' in {'spam', 'eggs', 'potato'}
10000000 loops, best of 3: 27.6 ns per loop

In [2]: timeit 'potato' in {'potato'}
---------------------------------------------------------------------------
NameError                                 Traceback (most recent call last)
<ipython-input-2-9f61653b85de> in <module>()
----> 1 get_ipython().magic(u"timeit 'potato' in {'potato'}")

/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in magic(self, arg_s)
   2203         magic_name, _, magic_arg_s = arg_s.partition(' ')
   2204         magic_name = magic_name.lstrip(prefilter.ESC_MAGIC)
-> 2205         return self.run_line_magic(magic_name, magic_arg_s)
   2206 
   2207     #-------------------------------------------------------------------------

/usr/local/lib/python2.7/dist-packages/IPython/core/interactiveshell.pyc in run_line_magic(self, magic_name, line)
   2124                 kwargs['local_ns'] = sys._getframe(stack_depth).f_locals
   2125             with self.builtin_trap:
-> 2126                 result = fn(*args,**kwargs)
   2127             return result
   2128 

/usr/local/lib/python2.7/dist-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell)

/usr/local/lib/python2.7/dist-packages/IPython/core/magic.pyc in <lambda>(f, *a, **k)
    191     # but it's overkill for just that one bit of state.
    192     def magic_deco(arg):
--> 193         call = lambda f, *a, **k: f(*a, **k)
    194 
    195         if callable(arg):

/usr/local/lib/python2.7/dist-packages/IPython/core/magics/execution.pyc in timeit(self, line, cell)
   1011             number = 1
   1012             for _ in range(1, 10):
-> 1013                 if timer.timeit(number) >= 0.2:
   1014                     break
   1015                 number *= 10

/usr/lib/python2.7/timeit.pyc in timeit(self, number)
    193         gc.disable()
    194         try:
--> 195             timing = self.inner(it, self.timer)
    196         finally:
    197             if gcold:

<magic-timeit> in inner(_it, _timer)

NameError: global name 'potato' is not defined

IPython v2.2.0,在python 2.x和python3上均失败.

解决方法:

这是一个bug in IPython,是由于在ipython magic中扩展{var}引用的语法与python开发人员为集合文字选择的相同语法引起的.

如果遇到此问题,可能的解决方法是使用双花括号将设置文字转义:

In [1]: timeit 0 in {0}
# TypeError: argument of type 'int' is not iterable

In [2]: timeit 0 in {{0}}
10000000 loops, best of 3: 60.1 ns per loop
上一篇:Python:有没有办法使用timeit.timeit()导入变量?


下一篇:在Windows 10 使用 Anaconda安装 TensorFlow gpu 2.0 的步骤