0
0
Pythonprogramming~10 mins

Import statement behavior in Python - Step-by-Step Execution

Choose your learning style9 modes available
Concept Flow - Import statement behavior
Start program
Encounter import statement
Check if module is loaded
Use cached
Access module contents
Continue program execution
When Python sees an import, it checks if the module is already loaded. If yes, it uses the cached module. If not, it loads the module, then continues.
Execution Sample
Python
import math
print(math.sqrt(16))
import math
print(math.pi)
This code imports the math module twice and uses its functions and constants.
Execution Table
StepActionModule Loaded?ResultOutput
1import mathNoLoad math module
2print(math.sqrt(16))YesCall sqrt(16)4.0
3import mathYesUse cached math module
4print(math.pi)YesAccess pi constant3.141592653589793
💡 Program ends after printing results
Variable Tracker
VariableStartAfter Step 1After Step 2After Step 3After Step 4
mathundefinedmodule objectmodule objectmodule objectmodule object
Key Moments - 2 Insights
Why does importing the same module twice not reload it?
Because Python checks if the module is already loaded (see Step 3 in execution_table) and uses the cached version to save time.
What happens if you try to use a module before importing it?
You get an error because the module variable is undefined until the import runs (see variable_tracker start state).
Visual Quiz - 3 Questions
Test your understanding
Look at the execution table, what is the output after Step 2?
A4.0
B16
CError
DNone
💡 Hint
Check the Output column at Step 2 in execution_table
At which step does Python decide to use the cached module instead of loading it again?
AStep 1
BStep 2
CStep 3
DStep 4
💡 Hint
Look at the Module Loaded? and Result columns in execution_table
If the first import was removed, what would happen at Step 2?
Aprint would output 4.0 anyway
BError because math is not defined
Cmath module would be loaded at Step 2
DProgram would skip Step 2
💡 Hint
Refer to variable_tracker start state and key moment about using module before import
Concept Snapshot
import module_name

- Loads module if not loaded yet
- Uses cached module if already loaded
- Access module contents with module_name.member
- Importing twice does not reload
- Must import before use
Full Transcript
When Python runs a program and sees an import statement, it checks if the module is already loaded in memory. If not, it loads the module and makes it available. If yes, it uses the cached module to save time. This means importing the same module multiple times does not reload it again. You must import a module before using it, or you get an error. In the example, math is imported first, then used to calculate square root and access pi. The second import just uses the cached math module.