Some cool IPython tips

The IPython shell is a fast way to evaluate small bits of code. It also functions as a mighty fine calculator. You can install it with pip, pip install ipython, and launch it with the ipython command. Besides the normal Python REPL stuff, here are a few cool things about the IPython shell.


Let’s say you’re reading a blog post on how to do something amazing in Python and you want to follow along in the shell. If you copy a code snippet to your clipboard, you can type %paste in the shell and it will execute each line one at a time. Go ahead and try it:

one_string = "this "
two_string = "is "
red_string = "pretty "
blue_string = "sweet"
>>> print(one_string + two_string + red_string + blue_string)
this is pretty sweet

Although Zed Shaw might disagree with me, I think this is way better than typing each line by hand.


IPython keeps track of history across sessions. So if I remember writing a killer list comprehension last week called hello in IPython, I can get it back by typing:

>>> hello =

And then hitting the up arrow until I find it. If you’re an emacs user, you can also scroll through your history with C-p to go up and C-n to go down. This is based on reverse-i-search in bash, but IPython’s version always seems to work better for me.

View docstrings and source

If you add two question marks ?? before a function, class or method, you can see the docstring (if there is one) and the source.

>>> import requests
>>> ??requests.get
Signature: requests.get(url, params=None, **kwargs)
def get(url, params=None, **kwargs):
   """Sends a GET request.

   :param url: URL for the new :class:`Request` object.
   :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`.
   :param \*\*kwargs: Optional arguments that ``request`` takes.
   :return: :class:`Response <Response>` object
   :rtype: requests.Response

   kwargs.setdefault('allow_redirects', True)
   return request('get', url, params=params, **kwargs)
File:      /opt/conda/lib/python3.5/site-packages/requests/
Type:      function

This is very handy for figuring out what arguments you need to pass in.


comments powered by Disqus