function-class frustration

Gabriel Genellina gagsl-py2 at
Sat Mar 22 20:51:05 CET 2008

En Sat, 22 Mar 2008 07:07:18 -0300, John Machin <sjmachin at>  

> On Mar 22, 7:19 pm, castiro... at wrote:
>> On the other hand, are you willing to make changes to the console?
>> How big and what?  I was thinking of __ to keep the second-to-last
>> most recent command.
> Access to and editing of previous input lines is already provided by
> the cooked mode of the console (e.g. on Windows, lean on the up-arrow
> key) or can be obtained by installing the readline package. Perhaps by
> analogy with _, you mean the *result* of the penultimate *expression*.
> This functionality would be provided by the Python interactive
> interpreter but it's not ... do have a look at IPython (http://

There is no need to change the interpreter, one can use sys.displayhook to  
achieve that.
Create or add the following to your module:


import sys
import __builtin__ as builtin

def displayhook(value):
     if value is not None:
         sys.stdout.write('%s\n' % value)
         builtin._ = value
         if not hasattr(builtin, '__'):
             __ = builtin.__ = displaylist()
             __ = builtin.__

sys.displayhook = displayhook

class displaylist(list):
     """List of expressions kept by displayhook.
     It has a maximum size and a custom display, enumerating lines.
     Lines are trimmed at the middle to fit the maximum width"""

     maxlen = 20
     maxwidth = 80-1-4

     def __str__(self):
         def genlines(self):
             for i, value in enumerate(self):
                 s = str(value)
                 if len(s) > self.maxwidth:
                     p = (self.maxwidth - 3) // 2
                     s = s[:p] + '...' + s[-(self.maxwidth - p - 3):]
                 yield '%2d: %s' % (i, s)
         return '\n'.join(genlines(self))

     def append(self, value):
         # don't keep duplicates
         # obey the maximum size
         if value is self:
         if value in self:
         if len(self) > self.maxlen - 1:
             del self[:-self.maxlen - 1]
         list.append(self, value)

py> 24*60*60*365
py> "hello world".split()
['hello', 'world']
py> help
Type help() for interactive help, or help(object) for help about object.
py> quit
Use quit() or Ctrl-Z plus Return to exit
py> __
  0: 31536000
  1: ['hello', 'world']
  2: Type help() for interactiv...ct) for help about object.
  3: Use quit() or Ctrl-Z plus Return to exit
py> __[1]
['hello', 'world']
py> __[0] // 3
py> __
  0: 31536000
  1: Type help() for interactiv...ct) for help about object.
  2: Use quit() or Ctrl-Z plus Return to exit
  3: ['hello', 'world']
  4: 10512000

Gabriel Genellina

More information about the Python-list mailing list