54

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.

starball
  • 20,030
  • 7
  • 43
  • 238
Zemian
  • 571
  • 1
  • 5
  • 8

4 Answers4

41

Have you tried

import app.config as Config

It did the trick for me.

macdrai
  • 586
  • 5
  • 6
23

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
Juju
  • 231
  • 2
  • 3
  • 1
    This will not work if launched as a script. You would get the error `ModuleNotFoundError: No module named '__main__.config'; ' __main__' is not a package `. So @macdrai 's answer is more appropriate. – Dr_Zaszuś Jul 29 '19 at 16:14
  • @Dr_Zaszuś, I wasn't able to import when I tried macdrai's answer and with this solution, I got the same error – Abhishek Saxena Dec 23 '19 at 10:11
  • Great solution if there is no need to have "app" in the first case. – Sany Dec 22 '21 at 09:33
6
# 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
stefan.stt
  • 2,357
  • 5
  • 24
  • 47
1

Another, shorter way would be:

import .config as Config
asti205
  • 154
  • 7