Importing files from different folder using __init__.py doesn't work in runtime

Question:

This is my first time trying to import from different folder. the structure is as follow:

application
  │
  ├── __init__.py
  │
  ├── folder
  │     ├── file.py
        │
        └── __init__.py
  │ 
  └── folder2
      ├── some_file.py  
      │
      └── __init__.py

I want to import some_file to file.py
I tried to do from application.folder2 import some_file, and it doesn’t work:
ModuleNotFoundError: No module named ‘application’.

Note : Visual code is recognizing the folders as modules, therefore I get the error only in run time.

I followed this answer link, which was the most suitable to me.

What is wrong here?

Asked By: Mr.O

||

Answers:

TLDR: Run your program as part of its package:

$ python3 -m application.folder.file

The search path for modules is derived from the main script, among other things. Running

$ python3 application/folder/file.py

means the search path is inside application/folder – where there is not application module.

Since application appears to be intended as a package anyways, use the -m switch to run your file as part of the package structure:

$ python3 -m application.folder.file

This will look for the application package (including the current directory) and recursively traverse to .folder and .file. This guarantees that the import paths match the package layout.

In order to use this from another folder than the one containing application, either install the package or set PYTHONPATH to point to the parent folder of application.

$ export PYTHONPATH=$(PYTHONPATH):/path/to/parent_of_application
$ python3 -m application.folder.file
Answered By: MisterMiyagi

Create a .env file under the application folder and set the python path to it.

## Set python path
PYTHONPATH=.

Answered By: SAB6