0

I am having a problem importing a script in another directory to the main script. FYI, this is a python Flask app. I have the empty __init__.py in the module_directory, so importing the module in the upper __init__.py should not be a problem, but it happens. I don't know why.

myfolder
    - __init__.py
    - module_directory
        - script_to_import.py
        - __init__.py
    - static
    - templates

__init__.py is the main server script where the app is defined with routes like @app.route("/home", methods=["GET","POST"]) something like that. Below is what I do in the upper __init__.py to import the module.

from module_directory.script_to_import import *

It gives me error saying that No module_directory.

putting . in front of the module name fixed the problem.

from .module_directory.script_to_import import *
minjunkim7767
  • 213
  • 1
  • 3
  • 13
  • What executes the upper `__init__.py`? – martineau Jun 10 '20 at 14:41
  • @martineau it is the Flask app setting up url routes and running the actual app. – minjunkim7767 Jun 10 '20 at 14:51
  • Does this answer your question? https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time – IMB Jun 10 '20 at 14:55
  • 1
    Does this answer your question? [Relative imports for the billionth time](https://stackoverflow.com/questions/14132789/relative-imports-for-the-billionth-time) – IMB Jun 10 '20 at 14:56

1 Answers1

3

I tried replicating it on my end

.
├── __init__.py
└── module_directory
    ├── __init__.py
    └── script_to_import.py

The __init__.py in module_directory is empty and script_to_import.py has:

def return_15():
    return 15

In the __init__.py of the . folder (which is nothing but myfolder), I have:

from module_directory.script_to_import import return_15

print(return_15())

When I run this file in the terminal, it gets executed and I get the following output

enter image description here

some_programmer
  • 3,268
  • 4
  • 24
  • 59