Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

import function from a file in the same folder

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

like image 227
Zemian Avatar asked May 09 '17 08:05

Zemian


People also ask

How do you import a function from another file in the same directory in python?

Remember the file that contains the function definitions and the file calling the functions must be in the same directory. To use the functions written in one file inside another file include the import line, from filename import function_name . Note that although the file name must contain a . py extension, .

How do I import a function from another Ipynb file?

You'll need to install it: pip install ipynb . Create a Notebook named my_functions. ipynb . Add a simple function to it.

Can function be imported from python file?

file.py contains a function named function . How do I import it? You should probably go through the modules section in the Python tutorial. Also if you want to import the function from the file.py , make sure there is no package in your directory with the name file .


3 Answers

Have you tried

import app.config as Config

It did the trick for me.

like image 78
macdrai Avatar answered Oct 22 '22 07:10

macdrai


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
like image 39
Juju Avatar answered Oct 22 '22 06:10

Juju


# 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
like image 5
stefan.stt Avatar answered Oct 22 '22 05:10

stefan.stt