Search code examples
pythonpython-importpython-module

import module in different contexts


I have a file structure like this:

work/
├─ analysis.ipynb
├─ app/
│  ├─ __init__.py
│  ├─ class_a.py
│  ├─ script.py
│  ├─ utils.py

File class_a.py contains a class MyClass and also an import from utils like this:

from utils import useful_function

class MyClass():
    ...

Then I try to import MyClass in analysis.ipynb like this:

from app.class_a import MyClass

and get an error:

ModuleNotFoundError                       Traceback (most recent call last)
<ipython-input-4-8eeb8559d767> in <module>
      2 import os
      3 from datetime import datetime
----> 4 from app.class_a import MyClass
      5 from app.utils import useful_function
      6 ...

~/Documents/work/app/class_a.py in <module>
      1 import pandas as pd
----> 2 from utils import useful_function
      3 
      4 class MyClass():
      5     '''indeed very necessary class for me

ModuleNotFoundError: No module named 'utils'

I have figured out that if I change all imports in app folder to something like this:

from app.utils import useful_function

Then I can import all I need from analysis.ipynb

However app should work as something I run with python script.py and that does not work unless imports are written in the original way.

I do not understand modules and packaging and so can not even ask a question precisely, but how do I align import "styles" in order to both be able to run python scripts.py from the app directory and import MyClass from analys.ipynb?


Solution

  • import statements search through the list of paths in sys.path, so I've added these lines to my analysis.ipynb:

    import sys
    sys.path.append('/path/to/work/app/')
    

    In case someone would have the same question and struggle as me.