Python from Wise Guy's Viewpoint

Paul Rubin http
Sun Oct 19 14:04:20 EDT 2003


Frode Vatvedt Fjeld <frodef at cs.uit.no> writes:
> > [..] Functions are internally delt with using dictionaies.  The
> > bytecode compiler gives it a ID and the look up is done using a
> > dictionary.  Removing the function from the dictionary removes the
> > function.  (pythonese for hash-table)
> 
> So to get from the ID to the bytecode, you go through a dictionary?
> And the mapping from name to ID happens perhaps when the caller is
> bytecode-compiled?

Hah, you wish.  If the function name is global, there is a dictionary
lookup, at runtime, on every call.

   def square(x):
      return x*x

   def sum_of_squares(n):
      sum = 0
      for i in range(n):
         sum += square(x)
      return sum

   print sum_of_squares(100)

looks up "square" in the dictionary 100 times.  An optimization:

   def sum_of_squares(n):
      sum = 0
      sq = square
      for i in range(n):
        sum += sq(x)
      return sum

Here, "sq" is a local copy of "square".  It lives in a stack slot in
the function frame, so the dictionary lookup is avoided.




More information about the Python-list mailing list