[Python] Module not found during import in Jupyter Notebook

Discussão em 'Python' iniciado por Stack, Maio 15, 2025.

  1. Stack

    Stack Membro Participativo

    I have the following package (and working directory):

    WorkingDirectory--
    |--MyPackage--
    | |--__init__.py
    | |--module1.py
    | |--module2.py
    |
    |--notebook.ipynb



    In __init__.py, I have:

    import module1
    import module2


    If I try to import MyPackage into my notebook:

    import MyPackage as mp


    I will get


    ModuleNotFoundError: No module named 'module1'
    ​

    But import works fine if I execute the script outside a notebook: if I create test.py in the same directory and do the same as in the notebook the import would work properly. It will work inside the notebook if I use fully qualified name in __init__.py (import MyPackage.module1).

    What's the reason for different import behavior?

    I have confirmed the working directory of the notebook is WorkingDirectory.

    The exact error is:

    C:\Users\Me\Documents\Working Directory\MyPackage\__init__.py in <module>()
    ---> 17 import module1

    ModuleNotFoundError: No module named 'module1'


    My problem differs from the possible duplicate:


    1. The notebook was able to find the package, but only unable to load the module. This was inferred from substituting module1 with MyPackage.module1 worked well and suggests it may not be a problem related with PATH.


    2. I cd'ed into WorkingDirectory and started the server there. The working directory should be the folder containing my package.

    Continue reading...

Compartilhe esta Página