You think
importjust brings code into your file. It does much more than that.
Today, you understand how Python loads, initializes, and caches modules.
Today’s Goal
By the end of today, you will:
- Understand how Python resolves imports
- Learn module execution model
- Understand import caching
- Avoid common import pitfalls
The Illusion
import math
You think:
Python just loads math
Reality:
Python searches, loads, compiles (if needed), executes, and caches the module
Import Pipeline
import statement
↓
check sys.modules cache
↓
find module (sys.meta_path / sys.path)
↓
load module (loader)
↓
execute module top-level code
↓
store in sys.modules
Step 1 — Cache Check
import sys
print('math' in sys.modules)
If present → reuse
If not → load
Step 2 — Finding the Module
Search order:
- built-in modules
- current directory
- sys.path
import sys
print(sys.path)
Step 3 — Loading & Execution
- file is read
- compiled to bytecode (if needed)
- executed top-to-bottom
Important Insight
Importing a module runs its code.
Example
module.py
print("module executed")
x = 10
main.py
import module
Output:
module executed
Import Happens Once
import module
import module
Executed once due to sys.modules cache.
Import Styles
import math
math.sqrt(4)
from math import sqrt
sqrt(4)
import math as m
m.sqrt(4)
Avoid Wildcard Imports
from module import *
Problems:
- namespace pollution
- conflicts
- harder debugging
Module as Singleton
Modules are singletons.
Shared state across imports.
Reloading
import importlib
import module
importlib.reload(module)
Circular Imports
Cause partially initialized modules and runtime errors.
__name__ and Entry Points
print(__name__)
- Direct run → “main”
- Imported → module name
Example
def run():
print("running")
if __name__ == "__main__":
run()
__init__.py
Marks directory as package and executes on import.
# __init__.py
print("package initialized")
Modern Note
Optional in Python 3.3+, but still useful.
Your Task
- inspect sys.modules
- print sys.path
- create module and observe execution
Common Mistakes
- assuming import is free
- circular imports
- wildcard imports
Think Deeper
- Why cache modules?
- What if import fails?
- How does order affect behavior?
Final Insight
Import system defines how your app is wired.
Tomorrow
Errors & Exceptions
Rule
- Imports execute code
- Modules are singletons
- Structure matters
See you in Day 7.