Explorative programming with IPython

IPython is a must-have and must-use for Python programmers, it really makes things easier, especially since Python lacks a good IDE.

IPython is an enhanced Python shell which offers following features:

  • improved introspection
  • additional shell syntax
  • code highlighting
  • tab completion
  • and other things

It's really great to explore code or just test ideas out. I normally have an IPython open where I try stuff out.

In conjunction to this, it's possible to create your own shell with your own namespace. This is great if you want to have an easy to use admin interface.

The following code will try to open an IPython shell, if that fails it opens a standard Python shell:

import my_application

def answer_to_life():
    return 42

namespace = locals().copy()

doc = """\
[Interactive Shell]
Available objects:
    my_application      your application
    answer_to_life      answers the question we are all wondering about
"""

try:
    import IPython
    IPython.Shell.IPShell(user_ns=namespace).mainloop(sys_exit=1, banner=doc)
except:
    import code
    code.interact(doc, None, namespace)
Python · Stuff · Tips 26. Aug 2008
© Amir Salihefendic. Powered by Skeletonz.