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()

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

1 Comment

I get the following error when calling a anhata_utilities.print_test() function #...module 'anhata_utilities' has no attribute 'print_test'...#
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.