13

Let's say I have the following structure:

 dir_1
 ├── functions.py
 └── dir_2
     └── code.ipynb

In, code.ipynb, I simply want to access a function inside functions.py and tried this:

from ..functions import some_function

I get the error:

attempted relative import with no known parent package

I have checked a bunch of similar posts but not yet figured this out... I am running jupyter notebook from a conda env and my python version is 3.7.6.

CHRD
  • 1,917
  • 1
  • 15
  • 38

4 Answers4

9

In your notebook do:

import os, sys
dir2 = os.path.abspath('')
dir1 = os.path.dirname(dir2)
if not dir1 in sys.path: sys.path.append(dir1)
from functions import some_function
Mr_and_Mrs_D
  • 32,208
  • 39
  • 178
  • 361
5

The jupyter notebook starts with the current working directory in sys.path. see sys.path

... the directory containing the script that was used to invoke the Python interpreter.

If your utility functions are in the parent directory, you could do:

import os, sys
parent_dir = os.path.abspath('..')
# the parent_dir could already be there if the kernel was not restarted,
# and we run this cell again
if parent_dir not in sys.path:
    sys.path.append(parent_dir)
from functions import some_function
gman3g
  • 91
  • 1
  • 5
2

Given a structure like this:

 dir_1
 ├── functions
 │   └──__init__.py  # contains some_function
 └── dir_2
     └── code.ipynb

We are simply inserting a relative path into sys.path:

import sys

if ".." not in sys.path:
    sys.path.insert(0, "..")
from functions import some_function
Stefan_EOX
  • 1,279
  • 1
  • 16
  • 35
1

You can use sys.path.append('/path/to/application/app/folder') and then try to import

Mayank Porwal
  • 33,470
  • 8
  • 37
  • 58
  • Thanks! I really would like to avoid stating explicit paths though. Is there no way around this? Why am I getting the mentioned error? – CHRD Apr 06 '20 at 12:13
  • Take a look at https://stackoverflow.com/questions/16981921/relative-imports-in-python-3 –  Apr 06 '20 at 12:23
  • I believe the problem is due to your relative import. You might want to try something like python3 -m dir_2/code.py –  Apr 06 '20 at 12:25
  • Not sure I understand. I am running a jupyter notebook, and the whole point is that I want to use the relative path and avoid explicit paths. – CHRD Apr 06 '20 at 12:26
  • 1
    To be able to use relative paths, you should be working in packages. 'In other words, the algorithm to resolve the module is based on the values of __name__ and __package__ variables.' In your case, you don't have a package so __package__ is none. You need to have __init__.py to make your directory a package. Two different solutions are here in a detailed manner: https://napuzba.com/a/import-error-relative-no-parent/p2 –  Apr 06 '20 at 12:59
  • Also, it is generally advised not to use relative paths as modules tend to move around a lot. So please also consider that –  Apr 06 '20 at 12:59