The Python Standard Library
By Flavio Copes
Learn what Python's standard library includes, how it differs from built-ins and third-party packages, and how to import its modules.
Python ships with a large standard library.
It includes modules for working with files, dates, JSON, databases, networking, testing, logging, and much more. You do not install these modules from PyPI before importing them.
Use the standard library reference for the Python version you run. Module availability can vary by platform and distribution. For example, tkinter depends on Tcl/Tk being available.
Built-ins, the standard library, and third-party packages
These three groups are related, but they are not the same:
- Built-in functions and types such as
print(),len(),str, andlistare available without an import. - Standard library modules ship with Python and normally need an
import. - Third-party packages are installed separately, usually from the Python Package Index.
For example, requests is a popular third-party HTTP package. It is not part of the standard library. Python’s standard library includes urllib.request for opening URLs.
Useful standard library modules
Here are some modules worth knowing:
mathfor math utilitiesrefor regular expressionsjsonto work with JSONdatetimeto work with datespathlibto work with filesystem pathssqlite3to use SQLiteosandsysfor operating system and interpreter functionalitycollectionsfor specialized container data typesitertoolsandfunctoolsfor iteration and function toolssubprocessto start and communicate with other programsloggingfor application logsunittestfor automated testsvenvto create virtual environmentsrandomfor simulations and other non-security usessecretsfor security-sensitive random valuesstatisticsfor statistics utilitiesurllib.requestto open URLs
The random documentation explicitly recommends secrets for cryptographic and security uses.
How to import a module
You import a standard library module in the same way you import code from another module:
import math
result = math.sqrt(4)
print(result) # 2.0
You can also import a specific name:
from math import sqrt
result = sqrt(4)
print(result) # 2.0
Importing the module is often clearer because math.sqrt() immediately tells the reader where sqrt() came from.
Here is a small HTTP example using only the standard library:
from urllib.request import urlopen
with urlopen("https://www.python.org/", timeout=10) as response:
html = response.read()
print(len(html))
For a real application, also handle network errors and decide how much response data you are willing to read.
Related posts about python: