Python Modules: import, from and the Standard Library
A module is simply a .py file whose functions and variables you can reuse in other files. Python ships with a large standard library of modules, so many everyday tasks, such as maths, dates, random numbers, JSON or file paths, need no installation at all.
Three ways to import
import mathloads the module and gives you one name,math. You then writemath.sqrt(81). This keeps it obvious where each function comes from.from collections import Countercopies just the names you list into your file, so you writeCounter(...)directly.import random as rndgives a module a shorter alias. Some aliases are community conventions, likeimport numpy as np.
Avoid from module import *. It dumps every public name into your file and makes it unclear where a name came from.
Expected output
9.0 3.141592653589793
2 3
[('i', 4), ('s', 4)]
Saturday
TrueA quick tour of the example
mathofferssqrt,floor,ceil, constants likepi, and much more. Note thatsqrtreturns a float.Countercounts how often each item appears;most_common(2)lists the top two. In"mississippi",iandstie at four, and ties keep the order in which they were first seen.datetime.daterepresents calendar dates;strftime("%A")formats the weekday name.randomproduces pseudo-random numbers. Callingseed()makes the sequence repeatable, which is useful in tests. For passwords or tokens use thesecretsmodule instead.
Your own modules
Save functions in helpers.py, and another file in the same folder can import helpers. When Python imports a file, it runs the file's top-level code once. That is why scripts often end with if __name__ == "__main__": followed by the code that should run only when the file is executed directly, not when it is imported.
Third-party packages
Packages from the Python Package Index are installed with pip, for example python3 -m pip install requests, ideally inside a virtual environment created with python3 -m venv .venv. The import syntax is exactly the same as for standard-library modules.
Common mistakes
- Naming your own file
math.pyorrandom.py, which shadows the standard module. - Importing inside a loop; imports belong at the top of the file.
- Forgetting the module prefix after
import math:sqrt(4)alone raisesNameError.
Summary
import m,from m import nameandimport m as aliasload code from modules.- The standard library covers maths, dates, counting, randomness and much more.
- Any
.pyfile can be imported; guard script-only code withif __name__ == "__main__":.
Quiz: Modules and imports