0

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?

Mr.O
  • 342
  • 2
  • 19
  • How do you *run* this application? Do you run it as ``python3 -m application.folder.file``, or as ``python3 application/folder/file.py``, or is your entry point even elsewhere? – MisterMiyagi Oct 22 '20 at 07:28
  • I run it like `python3 application/folder/file.py` – Mr.O Oct 22 '20 at 07:29

1 Answers1

1

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
MisterMiyagi
  • 44,374
  • 10
  • 104
  • 119
  • 1
    seems to work. but it's very annoying. This way, I can't run directly from visual code or debug (is there something to do with this?). It only works using terminal command , and only from the home directory of application (not inside application directory for example). By the way you said to use `-m`, but didn't wrote it the command, it work by using: `$ python3 -m application.folder.file` – Mr.O Oct 22 '20 at 08:36
  • 1
    I cannot help you with Visual Code, but I am certain it supports this as well (my IDE defaults to this mode). Note that invoking python like this is not restricted to the terminal. As for doing this without being in the containing directory, I have expanded the answer to describe that. – MisterMiyagi Oct 22 '20 at 08:59
  • 1
    @Mr.O Thanks for spotting the typo (missing ``-m``), fixed it. – MisterMiyagi Oct 22 '20 at 09:06
  • I will look at my IDE options. Thank you – Mr.O Oct 22 '20 at 09:08