Import from file in same folder

I am building a Flask application with Python 3.5 after the tutorial based on different import rules. If I look for similar questions, I managed to solve ImportError based on import from a subfolder, adding a folder to the path, but I continue to refuse when importing a function from a script in the same folder (already on the way), The folder structure is as follows:

DoubleDibz  
β”œβ”€β”€ app
β”‚   β”œβ”€β”€ __init__.py
β”‚   β”œβ”€β”€ api 
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── helloworld.py
β”‚   β”œβ”€β”€ app.py
β”‚   β”œβ”€β”€ common
β”‚   β”‚   β”œβ”€β”€ __init__.py
β”‚   β”‚   └── constants.py
β”‚   β”œβ”€β”€ config.py
β”‚   β”œβ”€β”€ extensions.py
β”‚   β”œβ”€β”€ static
β”‚   └── templates
└── run.py

In app.py, I import the function from config.py with this code:

import config as Config

but I get this error:

ImportError: No module named 'config'

I do not understand what the problem is, being two files in the same folder. thanks in advance

+6
source share
3 answers

You tried

import app.config as Config

He helped.

+7
source

To import from the same folder, you can:

from .config import function_or_class_in_config_file

:

from ..app import config as Config
+3
# imports all functions    
import config
# you invoke it this way
config.my_function()

# import specific function
from config import my_function
# you invoke it this way
my_function()

app.py , :

# csfp - current_script_folder_path
csfp = os.path.abspath(os.path.dirname(__file__))
if csfp not in sys.path:
    sys.path.insert(0, csfp)
# import it and invoke it by one of the ways described above
+1

Source: https://habr.com/ru/post/1017099/


All Articles