Thursday, October 18, 2018

Jupyter Notebooks: Interacting with Python Files

You can make functions defined inside a python file [myFunctions.py] visible in a Jupyter Notebook by simply importing it as a module.

For example suppose myFunctions.py contains:

$ cat myFunctions.py

def func1():

def func2():

etc.

You can use the functions by importing the python file as a module.

from myFunctions import *

This makes func1() and func2() visible inside the Jupyter notebook.

This feature can be helpful in reducing clutter by moving large walls of code out of the notebook, which can then retain a simpler look and feel.

There are two potential issues:

  • when you make changes to python file, they are not immediately reflected in the notebook
  • if your python file has any "script"-like commands outside the function definitions, they are executed when the file is imported as a module

The first issue can be taken care of by the magic command %autoreload.

In [1]: %load_ext autoreload

In [2]: %autoreload 2

In [3]: from myFunctions import func1

In [4]: func1()
Out[4]: 42

In [5]: # open myFunctions.py in an editor and change func1() to return 43

In [6]: func1()
Out[6]: 43

The second issue can be resolved by decorating the "script" commands with an appropriate if statement, which ensures that those commands are not executed unless the file is executed directly.

$ cat myFunctions.py

def func1():

def func(2):

#  
# Main Driver
# This part is not run when imported as a module
#
if __name__ == '__main__':
    some script commands
    print('something')

No comments: