r/IPython • u/ta-da-scientist • Oct 14 '14
IPython notebook good practices
What good practices did you come up with? How do you decide how to split your code into cells? Do you define as many functions as you would in a standard python file? When using version control, do you commit the cell contents only or the output as well?
13
Upvotes
11
u/Noctambulist Oct 14 '14
I use IPython mostly for data analysis, so my best practices are based around that.
I do my best to keep cells split up thematically, with markdown text in between such that it is basically literate programming. This helps me figure out what I was doing later, plus it makes the code more understandable for others.
Typically, I will split up all data analysis and plotting code. So, in one cell, I do all the calculations and put the results into a data structure, usually a Pandas DataFrame. Then in the next cell, I write all the matplotlib plotting code. This makes it so that if I want to change something in the figure, I don't have to rerun the analysis.
I define functions whenever I need to perform the same computation multiple times, such as when I'm using map(), pandas DataFrame.apply(), or comprehensions. As such, I don't define as many functions as I would in a normal file. A lot of the operations are only done once and can be refactored easily just by editing the code in that one cell. But, with normal code, I prefer to modularize since it isn't structured top to bottom like in a Notebook.
I've been committing the entire file recently. One nice reason to do this is that you can use nbviewer.ipython.org to view any IPython Notebook file hosted online. So, I've been committing the entire file to GitHub, then linking to the nbviewer rendered Notebook.