Standard library · 4 / 17 Theory

How to find and read the documentation

Nobody knows the standard library by heart. The most useful skill of a programmer is not remembering every function, but knowing how to find it and understand how it is used. These are the tools to do it.

Inside Python: dir and help

import datetime

print(dir(datetime.date)[-5:])    # the last names available
help(datetime.date.fromisoformat)
  • dir(object) lists the available names: functions, methods and constants.
  • help(object) shows the official description of that element.
  • object.__doc__ returns that same text as a string.

The official documentation

The complete reference is at docs.python.org (in the section "The Python Standard Library"). Each module has its page with the list of functions, what each one is for and examples. The steps to get the most out of it:

  • Look for the module by its name, or by the task ("python date difference in days" will take you to datetime).
  • Read first the description at the beginning of the page and the examples.
  • Look for the specific function and pay attention to its signature: the required and optional parameters.
  • Try a small example in your own code before using it in the real program.

Reading a function signature

The documentation describes each function with its signature. For example, that of random.sample:

random.sample(population, k)
# population: the collection to choose from
# k: how many elements to choose

Brackets or default values indicate optional parameters:

statistics.mean(data)
round(number, ndigits=None)   # ndigits is optional

Which module do I need

I need…Module
Roots, rounding, mathematical constantsmath
Random numbers or choicesrandom
Dates and timesdatetime
Counting, grouping, queuescollections
Mean, median, deviationstatistics
Combining elementsitertools
Letters, digits, signsstring
Reading and writing JSON filesjson
Reading and writing CSV filescsv
Working with paths and foldersos, pathlib

Modules that do not come with Python

The standard library comes installed with Python. There are also hundreds of thousands of third-party packages on PyPI, the official catalog, which are installed with the command pip install name:

pip install requests

Once installed, it is imported like any other module: import requests.

Good practices

  • Before writing a utility function, check whether the standard library already has it: it is usually better tested and faster.
  • Import only what you need and put the import lines at the top of the file.
  • If you use a module that is not standard, note its name so you can install it on another computer.

Review what you have learned with Statistics summary and Anagrams.