How Imports Work¶
When your Python file needs code from another file or library, you use import.
Learn Your Way¶
| Read | Build | Watch | Test | Review | Visualize |
|---|---|---|---|---|---|
| You are here | Projects | Videos | Quiz | Flashcards | Diagrams |
Visualize It¶
See how Python searches for and loads modules when you import: Open in Python Tutor
Basic import¶
Import specific things¶
Import your own files¶
If you have two files in the same folder:
# helpers.py
def greet(name):
return f"Hello, {name}!"
# main.py
from helpers import greet
print(greet("Alice"))
Packages — folders of modules¶
A package is a folder that contains Python files and an __init__.py:
my_package/
├── __init__.py # Makes this folder a package (can be empty)
├── calculator.py # A module
└── statistics.py # Another module
What __init__.py does¶
__init__.py runs when you import the package. It controls what gets exported:
# my_package/__init__.py
from my_package.calculator import add, subtract
from my_package.statistics import mean
# Now users can do:
# from my_package import add, mean
Without __init__.py, Python does not recognize the folder as a package.
The import search path¶
When you write import something, Python looks in this order:
- Current directory (the folder your script is in)
- Installed packages (
site-packages/— things you installed with pip) - Standard library (modules that come with Python, like
os,json,math)
You can see the full search path:
Common patterns¶
Alias (rename on import):
Import everything (avoid this):
Conditional import:
try:
import ujson as json # Faster JSON library
except ImportError:
import json # Fall back to standard library
Common mistakes¶
Circular imports:
# file_a.py
from file_b import helper_b # file_b imports from file_a → circular!
# file_b.py
from file_a import helper_a # Fails with ImportError
Naming conflicts:
# Don't name your file "random.py" — it shadows the built-in random module!
import random # Imports YOUR random.py instead of Python's
Missing __init__.py:
# If my_package/ has no __init__.py:
from my_package import calculator # May fail in some Python versions
Practice¶
- Module 11 Package Publishing
- Level 01 projects
- Level 0 / 15 Level0 Mini Toolkit
- Level 1 / 01 Input Validator Lab
- Level 1 / 02 Password Strength Checker
- Level 1 / 03 Unit Price Calculator
- Level 1 / 04 Log Line Parser
- Level 1 / 05 Csv First Reader
- Level 1 / 06 Simple Gradebook Engine
- Level 1 / 07 Date Difference Helper
- Level 1 / 08 Path Exists Checker
- Level 1 / 09 Json Settings Loader
Quick check: Take the quiz
Review: Flashcard decks Practice reps: Coding challenges
| ← Prev | Home | Next → |
|---|---|---|