You're unable to read via this Friend Link since it's expired. Learn more
Member-only story
How Imports Work in Python
And a bit about packages
The Python import system is pretty straightforward... to a point. Importing code present in the same directory you’re working in is very different from importing between multiple files present in multiple directories. Through this post, I analyse some scenarios commonly encountered when working with imports, hopefully making it easier for you to create your own packages.
Table of Contents
An Example
What Happens When You Import a Python File?
Terminology
Import Scenarios
Analysis
Building a Package
The Syntax of Your Import Statement
Notes and Resources
An Example
We’ll start with a simple example and build on it throughout the post. Let’s say we have two simple Python files in a directory called PythonImportExample
.

PythonImportExample/ file1.py
file2.py
Let’s say file1.py
contains the following:
print("This is file1.py")
And file2.py
imports file1.py
.
import file1print("This is file2.py")
The import looks something like this:

What Happens When You Import a Python File?
When a Python file is imported, it is executed, and then added to the namespace of the file importing it.
For example, when file2.py
is executed, we get the following output:
$ cd PythonImportExample
$ python file2.pyThis is file1.py
This is file2.py
The imported file is executed right before its imported. So if we put the import statement in file2.py
below the print statement like so:
print("This is file2.py")import file1