为什么IPython的timeit不能使用set literals?

时间:2014-09-23 10:14:37

标签: python set ipython timeit

使用set literals时,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上都失败了。

1 个答案:

答案 0 :(得分:4)

它是bug in IPython,由ipython magics中扩展{var}引用的语法引起,与python devs为set literals选择的语法相冲突。

如果碰到这个问题,可能的解决方法是使用双花括号转义集文字:

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
相关问题