Part 3: Python Programming
11. Modules & the Standard Library
Modules & the Standard Library
No one writes every program from scratch. Python comes with a huge standard library of ready-made code, grouped into modules. A module is simply a file of Python definitions you can bring into your program. This chapter shows how to import modules, tours a few useful ones, and explains how to install extra packages.
Import forms
There are three common ways to import. The first brings in the whole module; you then use its contents with a dot. The second imports specific names directly. The third renames a module to a shorter alias:
Prefer import math over from math import * (which imports everything): keeping the module name makes it obvious where a function came from.
The random module
The random module produces random numbers and choices, perfect for games and simulations. (Your exact numbers will differ each run because they are random.)
randint(1, 6) returns a whole number between 1 and 6 inclusive, like rolling a die. choice picks one item from a list, and shuffle rearranges a list in place.
The datetime module
The datetime module works with dates and times. Here we get today's date and format it nicely:
In a real program you would call date.today() to get the current date automatically. The strftime method turns a date into text using format codes such as %Y for the four-digit year and %B for the month name.
pip and third-party packages
Beyond the standard library, the community has published hundreds of thousands of free packages on the Python Package Index (PyPI). You install them with pip, Python's package installer, from your terminal (not inside a Python script):
Once installed, you import it just like a standard module:
Popular packages include requests for web requests, pandas for data analysis, and pygame for games. Installing packages per project, inside a virtual environment, is a good habit you will learn as you progress.
Splitting your own code into modules
Any .py file you write is itself a module that other files can import. Suppose you save this as tools.py:
Then in another file in the same folder you can use it:
Splitting code into modules keeps each file focused and lets you reuse your work across projects. As your programs grow, organising them into several small modules is far easier to manage than one enormous file.
The standard library is sometimes called "batteries included" because so much is ready to use. Whenever you face a common task, search the documentation first; the tool you need may already exist.