intermediate20 min
Modules and Imports
Organize code across files and use the standard library
What Are Modules?
A module is simply a Python file (.py) containing functions, classes, and variables. Modules let you:
- Organize code into manageable files
- Reuse code across projects
- Use Python's massive standard library
Import Basics
Import Styles
Output
Run your code to see output here
Check Your Understanding
Why should you avoid `from module import *`?
Explore the Standard Library
Python comes with "batteries included" — hundreds of useful modules:
Standard Library Gems
Output
Run your code to see output here
Creating Your Own Module
Any .py file is a module. Let's see how it works:
Creating Your Own Module (Conceptual)
Output
Run your code to see output here
Packages
A package is a directory of modules with an __init__.py file:
my_package/
├── __init__.py
├── core.py
├── utils.py
└── sub_package/
├── __init__.py
└── helpers.py
# Import from packages
from my_package.core import GameEngine
from my_package.utils.helpers import validate_input
Package Structure
Output
Run your code to see output here
Check Your Understanding
What makes a directory a Python package?
Common Import Patterns
Import Patterns
Output
Run your code to see output here
Exercise
Import the `statistics` module (standard library) and use it to: (1) Calculate the mean of [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], (2) Calculate the median, (3) Calculate the standard deviation. Print all three results clearly labeled.
Python will load on first run
Key Takeaways
- Modules =
.pyfiles; Packages = directories with__init__.py - Use
import moduleorfrom module import item import ... as ...for aliases- Avoid
from module import * - Python's standard library is huge — explore
json,pathlib,collections,statistics,datetime if __name__ == "__main__"makes a file both importable and executable- Organizing code into modules is essential for projects larger than one file