Nicholas
Nicholas

Reputation: 2668

In Jupyter notebook, how do I arrange subroutines in order to write a project efficiently?

I'd like to write a program using Python in Jupiter. To make things easy, it'd be better off writing a few subroutines (functions) and probably some user-defined classes first before writing the main script. How do I arrange them in Jupiter? Just each sub function/class for a new line and write sequentially and then write main script below to call subroutines? I just wonder if this is the right way to use Jupyter.

I am new to Jupyter and Python, but in Matlab, for instance, I would create a folder which contains all sub functions to be used. And I will also write a script inside the same folder to call these functions to accomplish the task. However, how do I achieve this in Python using Jupyter?

Upvotes: 3

Views: 4342

Answers (2)

Vasco
Vasco

Reputation: 1197

I use notebooks mainly for data analysis. My workflow is as follows: During development, I declare all my routines in notebook cells. When I need the same functions for the next dataset, I quite often copy-paste them to the new notebook. Quite often, I have to adapt the functions slightly for the new dataset. When it turned out that I use functions often in may notebooks, I create a separate module (yust a python file with the functions copy-pasted in it) and put this my "global" python directory (~/python) on my system. This function is in my $pythonpath, and hence, in the next notebook I can simply say

from read_data_functions import square_measurement, long_run

Upvotes: 2

Pyrce
Pyrce

Reputation: 8571

The best thing to do for repeated code you want all your notebook to access is to add it to the profile directory. The notebook will load all scripts from that directory in order, so it's recommended you name files 01-<projname>.py if you want them to load in a certain order. All files in that directory will be loaded via exec which executes the file as though it were in your context, it's not a module load so globals will squash each other and all of the model context will be in your local namespace afterwards (similar to an import * effect).

To find your profile directory the docs recommend you use ipython locate profile <my_profile_name>. This will tell you where you can place the script.

Upvotes: -1

Related Questions