importing python utility functions into jupyter notebook
Asked Answered
S

2

6

I have been using Jupyter notebook for my python applications. There are several utility functions that I use on regular basis. Today, my solution is to copy all these functions into new python notebook and execute my new applications. I wanted to write a python file (say utility.py) and write all routine functions in that file. However, I am not sure how to call or import utility.py into Jupyter notebook.

utility.py
def f1(): do_something
def f2: do_something2
def f3: do_somthing3

In .ipynb file

import utility.py
utility.f1()
utility.f2()
Sweeper answered 18/5, 2018 at 17:42 Comment(0)
P
3

assuming that utility.py's absolute path is /home/anhata/utils/utility.py:

import sys
sys.path.append('/home/anhata/utils')
import utility

utility.f1()

be careful though, utility is a very common word for a potential duplicate.

It is a strong possibility that there might be a module named utility inside python package library. In that case, your program might confuse your utility.py with that file. I can suggest you to rename it to something specific, such as anhata_utils.py.

Polysyllabic answered 18/5, 2018 at 17:50 Comment(1)
I get the following error when calling a anhata_utilities.print_test() function #...module 'anhata_utilities' has no attribute 'print_test'...#Sweeper
S
1

My favorite way to handle this is to paste the same chunk of code at the top of every notebook, and this code is smart enough to figure out where it lives and whether it needs to be added to the path.

import sys, os
if os.path.abspath("..") not in sys.path:
    sys.path.insert(0, os.path.abspath(".."))

Then I can build out my project with a notebooks/ subdirectory containing my notebooks, a data/ subdirectory containing any necessary data, and a util/ directory containing __init__.py and any extra code I want to use. Supposing I wrote my_function in util/utility.py, I would use it as follows:

from util.utility import my_function

y = my_function(x)

Because I placed the full path of ".." first in line of my sys.path, I can just import from there. Just be careful of name collisions. For example, naming your subdirectory numpy, then trying to import the public numpy library would cause your own version of numpy to be found first, and you would never get access to the public version. These problems can be infuriating to debug.

Sall answered 31/3, 2021 at 2:41 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.