Search code examples
pythonpython-3.ximportpython-importimporterror

How importing actually works in python?


In my working directory, I have python3 files like this

/Path/to/cwd/main.py
/Path/to/cwd/Folder/one.py
/Path/to/cwd/Folder/two.py

So I had a main.py file like this

import Folder.one as one
#Do something

In one.py I had code like this

import two
#Some functions defined locally utilizing functions written in two.py
if __name__ == '__main__':
    #Code for testing Functions

When I run one.py, it runs fine. But when I run main.py, it throws an error

ModuleNotFoundError: No module named 'two'

Ideally, I would not be expecting such an error at all.

It worked when I changed the import statement from import two to import Folder.two, which works. But I would like to do this in some other way without affecting such import statements much. How to achieve this?


Solution

  • In order for the python interpreter to know what directories contain code to be loaded, you need to include a __init__.py file.

    Have a look at this answer to learn more about how to import packages.

    In the case of your second import, to access that method you would need to use this syntax.

    from .two import *