0

I have some trouble with imports in python. I don't exactly understand why there is an error.

I am using jupyter notebook from directory notebooks. I need to import function prepare_data which is situated in source/prepare_data.py

For importing i have tried to use from ..source.prepare_data import prepare_data

As here https://docs.python.org/3/reference/import.html (Paragraph 5.7) and python shows me an error "attempted relative import beyond top-level package".

packages

Emma
  • 27,428
  • 11
  • 44
  • 69
artikot
  • 16
  • 5

2 Answers2

1

You cannot import from the parent of your current working directory. Easy way to solve this is working from the root path.

In this answer you can find more info.

albeksdurf
  • 124
  • 8
1

You can add the path of the script to your system path:

sys.path.append('../source/')
from prepare_data import prepare_data

Note that this is a pretty quick-and-dirty hack. The linked answer from @albeksdurf has some better options if you are thinking of packaging up your code.

Andrew Guy
  • 9,310
  • 3
  • 28
  • 40