42piratas
42piratas

Reputation: 595

Relative imports from within a notebook that is not at the 'main.py' level

I have a structure like the following one:

/src
    __init__.py
    module1.py
    module2.py
/tests
    __init__.py
    test_module1.py
    test_module2.py
/notebooks
    __init__.py   
    exploring.ipynb
main.py

I'd like to use the notebook 'exploring' to do some data exploration, and to do so I'd need to perform relative imports of module1 and module2. But if I try to run from ..src.module1 import funct1, I receive an ImportError: attempted relative import with no known parent package, which I understand is expected because I'm running the notebook as if it was a script and not as a module.

So as a workaround I have been mainly pulling the notebook outside its folder to the main.py level every time I need to use it, and then from src.module1 import funct1 works.

I know there are tons of threads already on relative imports, but I couldn't find a simpler solution so far of making this work without having to move the notebook every time. Is there any way to perform this relative import, given that the notebook when called is running "as a script"?

Upvotes: 1

Views: 282

Answers (1)

Yelyzaveta Velizhanina
Yelyzaveta Velizhanina

Reputation: 187

Scripts cannot do relative imports. Have you considered something like:

if __name__ == "__main__":
    sys.path.insert(0,
        os.path.abspath(os.path.join(os.getcwd(), '..')))
    from src.module1 import funct1
else:
    from ..src.module1 import funct1

Or using exceptions:

try:
    from ..src.module1 import funct1
except ImportError:
    sys.path.insert(0,
        os.path.abspath(os.path.join(os.getcwd(), '..')))
    from src.module1 import funct1

?

Upvotes: 2

Related Questions