Skip to content
FLAVIO COPES
flaviocopes.com

The Python Standard Library

By

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:

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:

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.

Tagged: Python · All topics
~~~

Related posts about python: