/ Jupyter notebook

Reusing Code in Jupyter Notebooks

Magic commands in Jupyter notebooks are a great addition to my workflow. One really useful magic command comes with the ipyext package.

"Writeandexecute" allows you to quickly save classes or functions in a Jupyter notebook as separate *.py files. No need to copy and paste code, just two lines of magic commands and the file is saved and can be reused via import.

For this magic command to work you will need to install the ipyext package first.

  1. Install ipyext:
    • Conda:
      conda install -c https://conda.anaconda.org/janschulz ipyext
    • Pip:
      pip install ipyext
  2. Load extension in Jupyter
    %load_ext ipyext.writeandexecute
  3. Save module to file
    Put the following code on top of the cell with your function or class you want to export.
    %%writeandexecute -i identifier filename.py
    For example:
    %%writeandexecute -i user_accounts user.py
  4. Run the cell to write the file.
  5. Now you are ready to use the module
    import filename

Follow the link to find the full documentation of the ipyext package.

Reusing Code in Jupyter Notebooks
Share this

Subscribe to All things Data Science