Modules & Imports
What Are Modules?
A module is just a Python file that contains code you can reuse. Think of it like a toolbox. Instead of building a hammer from scratch every time, you just grab one from the toolbox. Python comes with a huge toolbox of built-in modules (the standard library), and you can install even more from the internet.
There are three kinds of modules:
- Built-in modules — Come with Python:
math,random,os,json, etc. - Third-party modules — Installed with
pip:requests,flask,numpy, etc. - Your own modules — Any
.pyfile you write can be imported by other files.
Import Styles
Useful Standard Library Modules
Python's standard library is famously described as "batteries included." Here are some you'll use constantly:
math— Math functions:sqrt,ceil,floor,log, constants likepirandom— Random numbers:randint,choice,shuffle,sampleos— Operating system: file paths, environment variables, directoriesjson— Read and write JSON datadatetime— Dates and timescollections— Fancy containers:Counter,defaultdict, dequepathlib— Modern file path handling
Standard Library Highlights
The __name__ Guard & pip
When you run a Python file directly, Python sets a special variable __name__ to "__main__". When the file is imported as a module, __name__ is set to the module's name instead. This lets you write code that only runs when the file is executed directly — not when it's imported.
To install third-party packages, use pip — Python's package installer:
pip install requests— Install a packagepip install -r requirements.txt— Install from a filepip list— See what's installedpip uninstall requests— Remove a package
The __name__ Guard
from module import specific_thing when you only need a few items. Importing everything with from math import * is like dumping the entire toolbox on the floor — you can't tell where anything came from, and names might clash.