16 Apr 2007 (updated 19 Jun 2007 at 21:07 UTC)
»
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.
From http://www.norvig.com/python-iaq.html
"""
def __init__(self, prompt='h[%d] >>> '):
self.prompt = prompt
def __str__(self):
try:
if _ not in h: h.append(_)
except NameError:
pass
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
.pythonrc.py. 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).
export PTHONSTARTUP="$HOME/.pythonrc.py"
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!
Syndicated 2007-04-16 02:36:05 (Updated 2007-05-07 19:28:34) from Alexandre Vassalotti