From The Compiler, 5 Years ago, written in Python.
Embed
  1.     # These functions get called only once, as they will override
  2.     # themselves with dynamically created functions in the Struct
  3.     # object
  4.  
  5.     def to_binary(self, *varargs, **keys):
  6.  
  7.         """data = s.to_binary(...)
  8.  
  9.        Convert Python values into the binary representation.  The
  10.        arguments will be all value fields with names, in the order
  11.        given when the Struct object was instantiated.  With one
  12.        exception: fields with default arguments will be last.
  13.  
  14.        Returns the binary representation as the string DATA.
  15.  
  16.        """
  17.  
  18.         # [...]
  19.  
  20.         # Add function header
  21.         code = 'def to_binary(self, %s):\n' % string.join(args, ', ') + code
  22.  
  23.         # self._pack_code = code
  24.  
  25.         # print
  26.         # print code
  27.         # print
  28.  
  29.         # Finally, compile function by evaluating it.  This will store
  30.         # the function in the local variable to_binary, thanks to the
  31.         # def: line.  Convert it into a instance metod bound to self,
  32.         # and store it in self.
  33.  
  34.         # Unfortunately, this creates a circular reference.  However,
  35.         # Structs are not really created dynamically so the potential
  36.         # memory leak isn't that serious.  Besides, Python 2.0 has
  37.         # real garbage collect.
  38.  
  39.         exec(code)
  40.         self.to_binary = new.instancemethod(to_binary, self, self.__class__)
  41.  
  42.         # Finally call it manually
  43.         return self.to_binary(*varargs, **keys)