Why doesn't IPython timeit work with literal set?

IPython timeit

sometimes breaks when using a set of 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 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, does not work on both python 2.x and python3.

+3


source to share


1 answer


This is a bug in IPython caused by the syntax for expanding {var} references in ipython magic, contrary to the same syntax chosen by the python developers for the literal set.

If you run into this problem, perhaps a workaround is to exit the set of literals with double curly braces:



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

      

+4


source







All Articles