Search code examples
pythonpackagerelative-import

Importing local python module from directory with __init__.py


I have been working on a project that requires editing and using an opensource project, lets call it osproj. I renamed the folder containing the edited scripts to osprojmine.

Here is an example directory structure:

root/  
    mycode.py  
    osprojmine/  
        __init__.py  
        foo.py  
        bar.py  

In mycode.py I have the import statement

import osprojmine as osproj

I have been able to use osproj.module() and osproj.class() within mycode.py with no issues and everything runs smoothly on my end.

The issue arises when I send the files over to my colleague. He is getting a
ModuleNotFoundError: No module named 'osprojmine'

I am using python 3.8.5. He was on 3.9.6 and has tried downgrading.

It seems his python interpreter just isn't recognizing osprojmine as a python package but on my end it does? Very confused. I am relatively new to this field so any and all advice welcome!


Solution

  • The colleague (and you for that matter) should run the code as:

    $ cd root
    $ python -m mycode
    

    This way the absolute import will be resolved