Boosted Python Startup

Yesterday, I was reading Peter Norvig’s excellent article about spell checking. Then, I started to look to some of his older stuff. So, I found his Python IAQ (Infrequently Answered Questions), and discovered a pretty neat trick:

h = [None]  # history

class Prompt:
    """A prompt a history mechanism.
    def __init__(self, prompt='h[%d] >>> '):
        self.prompt = prompt

    def __str__(self):
            if _ not in h: h.append(_)
        except NameError:
        return self.prompt % len(h)

    def __radd__(self, other):
        return str(other) + str(self)

sys.ps1 = Prompt()
sys.ps2 = '     ... '

This improve the interactive prompt of Python with a shell-like history mechanism. With this prompt, you can reuse any previous value returned by Python. For example:

h[1] >>> lambda x: x * 2
<function <lambda> at 0xb7dab41c>
h[2] >>> [1, 2, 3, 4, 5]
[1, 2, 3, 4, 5]
h[3] >>> map(h[1], h[2])
[2, 4, 6, 8, 10]

You can make it your default prompt, by adding the above in your You will need to specify its location to Python with the environment variable PYTHONSTARTUP. Just add something like the following to your shell configuration (e.g., .bashrc or .zshrc).


I am sure there is a ton of other useful modifications, which can be done with the startup file of Python. If you’re interested, here my brand new startup file. And if you know any other cool tricks for Python, please tell me!

· RSS feed for comments on this post


  1. Bill Mill said,

    May 3, 2007 @ 8:39 pm

    Trick #1: use IPython, which already has this and much, much, more.

  2. Alexandre said,

    May 3, 2007 @ 8:54 pm

    Yes! You’re right, Bill.

    In fact, this morning I woke up thinking why I was using this trick, at all, since IPython offered more. I have to admit, though, that dreaming about programming is a bit creepy. I guess that happens when you’re totally dedicated to something. Anyway, thanks for making me remember this!

  3. Bill Mill said,

    May 3, 2007 @ 9:55 pm

    I think your comment box stripped the href from my link?

    Anyway, no problem, I can’t even function with the normal python interpreter anymore.