Importing from parent and grandParent folders - AndrewMZ6/python_cheat_sheet GitHub Wiki

to understand what's going on let's come up with some terminology

parent folder - a folder that contains a folder where the calling file is located
parent file - a file that is in the parent folder and has the same level of hyerarcy as the folder that contains the calling file

image

In the figure above main.py is the calling file. It is the file from where we want to import other files
Folder parent_main is a parent folder for main.py since it contains folder main which contains main.py file
File parent_file.py is parent file for main.py since it located in the parent folder

The question is how do we import parent_file.py from main.py? And the anser is sys.path.
Here's the code for main.py

import sys
sys.path.append('../../parent_main')
import parent_file
parent_file.parent_func()

# response:
# hi, this is parent file function!

Now what we did is we added parent_main folder to sys.path variable which is used to look for imported modules!
Another option:

import sys
sys.path.append('..')
import parent_file
parent_file.parent_func()

neighbour folder is a folder that has the same parent folder as the folder that contains the caller file
neighbour file is a file that is located in neighbour folder

image

In the figure above folder neighbour is neighbour to the caller file main.py and file neighbour_file.py is a neighbour file for the main.py

import sys
sys.path.append('../..')
import parent_main.parent_file
import parent_main.neighbour.neighbour_file

parent_main.parent_file.parent_func()
parent_main.neighbour.neighbour_file.neighbours_func()


# response:
# hi, this is parent file function!
# Yo, this is neighbour file!

Why stop here?

image

import sys
sys.path.append('../../../grand_parent_main')
import parent_main.parent_file
import parent_main.neighbour.neighbour_file
import grand_parent_file

parent_main.parent_file.parent_func()
parent_main.neighbour.neighbour_file.neighbours_func()
grand_parent_file.grand_parent_func()

# response:
# hi, this is parent file function!
# Yo, this is neighbour file!
# hi, this is grand parent file function!

When we use .. notation we go one folder upper in the folder hyerarcy.
So at the beginning we are in the main.py file and inside main folder and only files that are in the main folder are in the scope of import "vision". After using .. we moved to parent_main folder and in our scope now everything that is inside this folder: that is main folder and file parent_file.py. To go upper we want to use ../.. and thus we're inside grand_parent_main folder and in scope of our vision parent_main folder and grand_parent_file.py file