import function from a file in the same folder

PythonPython 3.xFlask

Python Problem Overview


I'm building a Flask app with Python 3.5 following a tutorial, based on different import rules. By looking for similar questions, I managed to solve an ImportError based on importing from a nested folder by adding the folder to the path, but I keep failing at importing a function from a script in the same folder (already in the path). The folder structure is this:

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 a function from config.py by using this code:

import config as Config

but I get this error:

ImportError: No module named 'config'

I don't understand what's the problem, being the two files in the same folder. Thanks in advance

Python Solutions


Solution 1 - Python

Have you tried

import app.config as Config

It did the trick for me.

Solution 2 - Python

To import from the same folder you can do:

from .config import function_or_class_in_config_file

or to import the full config with the alias as you asked:

from ..app import config as Config

Solution 3 - Python

# imports all functions    
import config
# you invoke it this way
config.my_function()

or

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

If the app.py is invoked not from the same folder you can do this:

# 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

Solution 4 - Python

Another, shorter way would be:

import .config as Config

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionZemianView Question on Stackoverflow
Solution 1 - PythonmacdraiView Answer on Stackoverflow
Solution 2 - PythonJujuView Answer on Stackoverflow
Solution 3 - Pythonstefan.sttView Answer on Stackoverflow
Solution 4 - PythonTimLangerView Answer on Stackoverflow