2014-09-23 64 views
3

IPython的timeit有時會斷裂:爲什麼IPython的timeit不能使用set literals?使用組文字時

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,不能在兩個蟒2.x和python3。

回答

4

這是一個bug in IPython,它是由在ipython magics中擴展{var}引用的語法引起的,它與python devs爲set字面值選擇的語法相沖突。

如果你碰到這個問題,一個可能的解決方法是逃避集文字與雙大括號:

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 
相關問題