Published on : 25/08/24
A quick guide to help you understand how linking your files works in python to save you the struggle of searching how
Written by Aline
To start off, let’s get an example folder to be able to use it later on
Project Folder
|- Package
| |- __innit__.py
| |- ScriptA.py
| |- ScriptB.py
|
|- ScriptY.py
|- ScriptZ.py
Your running script, the one being “elevated” will ALWAYS be named "__main__".
Such as "name" == "__main__"
It will be subsequently be considered as your root for relative path
In this example we are in the
ScriptZFile, being the"__main__"script,
trying to access theScriptYFile
To Import a function from ScriptY, the import statement should look like :
from ScriptY import func_name, func_name2
# OR
from ScriptY import *
# OR
import ScriptY
Because your file being imported is in the same folder, you are able to use the name without much concerns
In this example we are in the
ScriptZFile, being the"__main__"script,
trying to access theScriptAFile inPackage, a subFolder of the project
Your import statement should look like :
from Package import ScriptA
if your __innit__.py file contains and import statement for scriptA, you can also do :
from Package import *
# OR
import Package
The Import statement Will NOT be different in "__main__" HOWEVER
It will have to be compatible with the "__main__" script :
Here’s what I mean by that :
Your import statement in the imported script will not count the imported script as root, but the main script. which means it will try to import from the current - running - script.
ScriptA Import Statement
# ScriptA importing ScriptB
from Package import ScriptB # Notice the root is from ScriptZ, outside of the folder
# OR
if __name__ == "__main__" : # Debug purposes (when the script is main)
from ScriptB import ScrpitB
else : # General Import
from Package import ScriptB
from ScriptB import func
from .ScriptB import func
# In both cases, the script will try to import "ScriptB" as :
# `Project Folder\ScriptB`
#
# and not :
#
# `Project Folder\Package\ScriptB`