How To Import In python

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

Python

Computer Science

Guide

How to use linking with packages in Python :

To start off, let’s get an example folder to be able to use it later on

Example Project

Project Folder
    |- Package
    |   |- __innit__.py
    |   |- ScriptA.py
    |   |- ScriptB.py
    |   
    |- ScriptY.py
    |- ScriptZ.py

1.0 Learn How to use relative Paths

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

1.1 -:- Same folder Access

In this example we are in the ScriptZ File, being the "__main__" script,
trying to access the ScriptY File

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

1.2 -:- SubFolder Access

In this example we are in the ScriptZ File, being the "__main__" script,
trying to access the ScriptA File in Package, a subFolder of the project

1.2.1 -:- Imported Script Does Not Use Imports

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
1.2.2 -:- Imported Script Uses Imports

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

DO

# 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

DON’T

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`