I have the following folder structure.
application/app/folder/file.py
and I want to import some functions from file.py in another Python file which resides in
application/app2/some_folder/some_file.py
I've tried
from application.app.folder.file import func_name
and some other various attempts but so far I couldn't manage to import properly. How can I do this?
Nothing wrong with:
Just make sure folder also contains an __init__.py, this allows it to be included as a package. Not sure why the other answers talk about PYTHONPATH.
The answers here are lacking in clarity, this is tested on Python 3.6
With this folder structure:
Where
myfile.py
has the content:The import statement in
main.py
is:and this will print hello.
Considering
application
as the root directory for your python project, create an empty__init__.py
file inapplication
,app
andfolder
folders. Then in yoursome_file.py
make changes as follows to get the definition of func_name:Try Python's relative imports:
Every leading dot is another higher level in the hierarchy beginning with the current directory.
Problems? If this isn't working for you then you probably are getting bit by the many gotcha's relative imports has. Read answers and comments for more details: How to fix "Attempted relative import in non-package" even with __init__.py
Hint: have
__init__.py
at every directory level. You might needpython -m application.app2.some_folder.some_file
(leaving off .py) which you run from the top level directory or have that top level directory in your PYTHONPATH. Phew!Using sys.path.append with an absolute path is not ideal when moving the application to other environments. Using a relative path won't always work because the current working directory depends on how the script was invoked.
Since the application folder structure is fixed, we can use os.path to get the full path of the module we wish to import. For example, if this is the structure:
And let's say that you want to import the "mango" module. You could do the following in vanilla.py:
Of course, you don't need the mango_dir variable.
To understand how this works look at this interactive session example:
And check the os.path documentation.