Blog Post #4

bksahu
Published: 07/22/2019

Hi, welcome to my 4th blog post !

Last time we saw how reformulations of `min` and `max` works. This time we will drive in how reformulation of `zip` (only in Py27) works. If I were to implement `zip` using Python 2 it were to look something like this:

def _zip(*iterables):
     # zip('ABCD', 'xy') --> Ax By
     # import ipdb; ipdb.set_trace()
     sentinel = object()
     iterators = [iter(it) for it in iterables]
     zipped = []
     for _ in xrange(len(iterators)):
         result = []
         for it in iterators:
             elem = next(it, sentinel)
             if elem is not sentinel:
                 result.append(elem)
         if len(result) == len(iterators):    
             zipped.append(tuple(result))
     return zipped

But on reformulation, some things need to be changed. We also have to take define new temp variables inside the scope and release it when we are done. One more major optimizations that we have to do is to use one loop instead to two loops as seen above. So, finally our reformulation pseudo-code will look something like this:

def _zip(a, b, c, ... ):
   # First assign, to preserve order of execution,
   # the arguments might be complex expressions.
   tmp_arg1 = a
   tmp_arg2 = b
   tmp_arg3 = c
   ...

   tmp_iter_1 = iter(tmp_arg1)
   tmp_iter_2 = iter(tmp_arg2)
   tmp_iter_3 = iter(tmp_arg3)
   ...

   # could be more
   tmp_result = []
   try:
       while 1:
           tmp_result.append(
               (
                    next(tmp_iter_1),
                    next(tmp_iter_2),
                    next(tmp_iter_3),
                    ...
               )
            )
      except StopIteration:
          pass

   return tmp_result

In this way we can optimize the zip nodes in Nuitka.

Thank you for reading :) 

DJDT

Versions

Time

Settings from gsoc.settings

Headers

Request

SQL queries from 1 connection

Static files (2312 found, 3 used)

Templates (11 rendered)

Cache calls from 1 backend

Signals

Log messages