function-class frustration

Gabriel Genellina gagsl-py2 at yahoo.com.ar
Sat Mar 22 15:51:05 EDT 2008


En Sat, 22 Mar 2008 07:07:18 -0300, John Machin <sjmachin at lexicon.net>  
escribi�:

> On Mar 22, 7:19 pm, castiro... at gmail.com 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 sitecustomize.py module:

<code>
# sitecustomize.py

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()
         else:
             __ = builtin.__
         __.append(value)

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:
             return
         if value in self:
             self.remove(value)
         if len(self) > self.maxlen - 1:
             del self[:-self.maxlen - 1]
         list.append(self, value)
</code>

py> 24*60*60*365
31536000
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
10512000
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
py>

-- 
Gabriel Genellina




More information about the Python-list mailing list