Skip to content

Instantly share code, notes, and snippets.

@awesomebytes
Last active April 1, 2021 02:26
Show Gist options
  • Select an option

  • Save awesomebytes/bb364ff00e99bf74472c6bc7c0c7a52e to your computer and use it in GitHub Desktop.

Select an option

Save awesomebytes/bb364ff00e99bf74472c6bc7c0c7a52e to your computer and use it in GitHub Desktop.
Compilation of ipython features or tricks I use to help developing/exploring

Ipython tricks

Here I'll describe some ipython tricks to make developing or exploring bugs easier.

First: What is ipython? It's an interactive Python terminal with colours, autocompletion and some additional magic.

Install it with: sudo pip install --upgrade ipython

Autocompletion

Just press TAB to autocomplete almost anything, imports, functions, methods... autocompletion on import

This is very useful to interactively understand the state of some object. Note that you can also use dir(my_object) to find out all the methods/fields it has.

Check docs

Just add ? to any function/method and you'll get the help. docs

Get the result of the last line executed

It's always in the _ variable, just write _ or print(_).

Time a function/method

Just use the magic method %timeit like, %timeit my_method().

timeit

Move into directories, get autocompletion on file choosing

You can use some commands as if you were in the shell normally, like cd, ls... use as shell

Save the output of a shell command into a variable (SUPER EASY AND USEFUL)

Just write your command with an exclamation mark ! in front (and save it), like output = ! ps aux | grep ipython. save command output

This is superuseful for one-off tasks that are easy to solve in python partially and easy to solve partially in bash.

Check your history of commands and save it

Access the history by doing %history and save it (as explained here) with %save:

In [15]: %save -r mysession 1-99999
The following commands were written to file `mysession.ipy`:

Use an ipython shell as a debugging breakpoint

You can add to your script the line: import ipdb; ipdb.set_trace()

And you will be dropped into an ipython shell with all the autocompletion capabilities to explore the state of your program.

Note that you may need to install:

sudo apt-get install libncurses5-dev
sudo pip install --upgrade ipdb ipython readline

Others

Docs are here: https://ipython.readthedocs.io/en/stable/interactive/magics.html

I haven't used them much but there are interesting ones like %run that runs a program in the ipython shell, and then you get all the variables to explore interactively.

You can also define alias for commands.

You can also use matplotlib inside of ipython: https://matplotlib.org/stable/users/interactive.html

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment