Interpretation vs dynamic dispatch penalty in Python

Let’s take a look at this python function: def py_fun(i,N,step): res=0.0 while i<N: res+=i i+=step return res and use ipython-magic to time it: In [11]: %timeit py_fun(0.0,1.0e5,1.0) 10 loops, best of 3: 25.4 ms per loop The interpreter will be running through the resulting bytecode and interpret it. However, we could cut out the interpreter … Read more

Is there a way to store a function in a list or dictionary so that when the index (or key) is called it fires off the stored function?

Functions are first class objects in Python and so you can dispatch using a dictionary. For example, if foo and bar are functions, and dispatcher is a dictionary like so. dispatcher = {‘foo’: foo, ‘bar’: bar} Note that the values are foo and bar which are the function objects, and NOT foo() and bar(). To … Read more