Import Local Module in Jupyter Notebook

Import local function from a module housed in another directory with relative imports in Jupyter Notebook using Python 3

I had almost the same example as you in this notebook where I wanted to illustrate the usage of an adjacent module's function in a DRY manner.

My solution was to tell Python of that additional module import path by adding a snippet like this one to the notebook:

import os
import sys
module_path = os.path.abspath(os.path.join('..'))
if module_path not in sys.path:
sys.path.append(module_path)

This allows you to import the desired function from the module hierarchy:

from project1.lib.module import function
# use the function normally
function(...)

Note that it is necessary to add empty __init__.py files to project1/ and lib/ folders if you don't have them already.

How do I import local modules stored in my Google Drive to Google Collab?

Just specify where your file is starting from drive.MyDrive.

For example, if I had a file test_function.py in the root of my Google Drive with the function square in it, I can import it by

from drive.MyDrive.test_function import square

Example image of execution and printing of paths:

Colab notebook example

And yes, you are able to run your Jupyter Notebooks from anywhere in your Google Drive. Just find the file, click on it, and click on "Open with Google Colaboratory" at the top when Google says there is "No preview available".

Jupyter Notebook: Importing function from local module and external modules not defined

Please add

import numpy as np

to numpytest.py.

How to import a module into another module in databricks notebook?

There are several aspects here.

  • If these files are notebooks, then you need to use %run ./config to include notebook from the current directory (doc)
  • if you're using Databricks Repos and arbitrary files support is enabled, then your code needs to be a Python file, not notebook, and have correct directory layout with __init__.py, etc. In this case, you can use Python imports. Your repository directory will be automatically added into a sys.path and you don't need to modify it.

P.S. I have an example of repository with both notebooks & Python files approaches.

Jupyter can't find python imports in same directory

the reason why your sys.path.append statements have no effect is that you start the paths with a trailing "/", which indicates that they are absolute paths, even though they should not be.

You could either add the full paths to the modules you would like to import or, if you want to use relative paths, do something like this:

import os
sys.path.append(os.path.join(os.path.abspath(os.getcwd()), "networks"))

Here, os.path.abspath(os.getcwd()) computes the absolute path of the current working directory and os.path.join joins it with your relative path afterwards.

Best,
Homan



Related Topics



Leave a reply



Submit