The standard library#
The Python standard library (see also this tuto) is a quite impressive set of packages useful for many many things. These packages are included natively in Python. They are very robust. Here is a small list:
math - Mathematical functions
sys - System-specific parameters and functions (a lot about the Python system)
copy - Shallow and deep copy operations
os - Miscellaneous operating system interfaces
shutil - High-level file operations
pdb - activate the python debugger
subprocess - Subprocesses with accessible I/O streams
datetime - Basic date and time types
pickle - Python object serialization
re - Regular expressions
argparse - Parser for command-line options, arguments and sub-commands
unittest - Unit testing framework
logging - Event logging system
platform - Access to underlying platform’s identifying data
threading - Higher-level threading interface
multiprocessing - Process-based “threading” interface
In the following we present few very common packages. For some packages we also mention very popular third-party projects which are interesting alternatives.
Presentation of few very common packages#
math - Mathematical functions#
For example to use \(\pi\) in an environment where Numpy might not be installed:
import math
print(type(math))
<class 'module'>
from math import cos
print("pi is approximately equal to ", math.pi)
print("cos(pi) is approximately equal to", cos(math.pi))
pi is approximately equal to 3.141592653589793
cos(pi) is approximately equal to -1.0
pprint - Pretty-print lists, tuples, & dictionaries recursively#
from pprint import pprint
sys - System-specific parameters and functions (a lot about the Python system)#
If you want to know where Python looks for module during the import statements, you can do
import sys
pprint(sys.path)
['/usr/local/lib/python313.zip',
'/usr/local/lib/python3.13',
'/usr/local/lib/python3.13/lib-dynload',
'',
'/builds/py-edu-fr/py-edu-fr/.venv/lib/python3.13/site-packages']
os: Miscellaneous operating system interfaces#
os is a very important module.
import os
os.getcwd()
'/builds/py-edu-fr/py-edu-fr/books/science/book/structure-reuse-code'
The os.path module is the historical module to work with paths
towards files and directories.
pathlib: Object-oriented filesystem paths#
A modern (Python 3) and nicer method to manipulate file paths.
from pathlib import Path
path_tmp = Path("/tmp/tmp_dir_example_python")
print(path_tmp.exists())
path_tmp.mkdir(exist_ok=True)
for i in range(4):
(path_tmp / f"tmp{i}.xml").touch()
(path_tmp / f"tmp{i}.txt").touch()
pprint(sorted(path_tmp.glob("*.txt")))
False
[PosixPath('/tmp/tmp_dir_example_python/tmp0.txt'),
PosixPath('/tmp/tmp_dir_example_python/tmp1.txt'),
PosixPath('/tmp/tmp_dir_example_python/tmp2.txt'),
PosixPath('/tmp/tmp_dir_example_python/tmp3.txt')]
Note
Code using libpath.Path is often nicer than the equivalent using os.path
and glob.
shutil - High-level file operations#
Copy of files and directories can be done with shutil, in particular with
shutil.copytree.
shutil.rmtree(path_tmp, ignore_errors=True)
pdb: useful to debug code#
On a script:
import pdb
write pdb.set_trace() to set up a breakpoint
run the script
At execution time, the script will stop at the first line containing pdb.set_trace() and gives the user access to the interpreter.
Remarks:
even nicer:
ipdb(but not part of the standard library).even nicer:
breakpoint()built-in function in Python 3.7.
Third party alternative
We have to mention ipdb.
subprocess#
subprocess is very important since it is the simple way to launch other programs and bash commands from Python. For example, in order to run bash (and not sh) commands, you can do
import subprocess
def call_bash(commands):
return subprocess.call(["/bin/bash", "-c", commands])
ret = call_bash(
"""
echo The files in this directory are:; ls
"""
)
if ret == 0:
print("command succeed")
else:
print(f"command failed with return code {ret}")
The files in this directory are:
classes.md
documentation.md
functions-again.md
functions.md
index.md
modules-packages.md
practical_functions.md
standard-library.md
tests.md
command succeed
argparse - Parser for command-line options, arguments and sub-commands#
argparse is the right tool to develop a command line script with options and help. Example from the tutorial at https://docs.python.org/3/howto/argparse.html :
# File prog.py
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("echo", help="echo the string you use here")
args = parser.parse_args()
print(args.echo)
Usage :#
$ python3 prog.py
usage: prog.py [-h] echo
prog.py: error: the following arguments are required: echo
$ python3 prog.py --help
usage: prog.py [-h] echo
positional arguments:
echo echo the string you use here
optional arguments:
-h, --help show this help message and exit
$ python3 prog.py foo
foo
logging - Event logging system#
logging allows the programmer to print (or not) different levels of messages.
import logging
log_level = logging.INFO # to get information messages
# log_level = logging.WARNING # no information messages
logging.basicConfig(
format="%(asctime)s - %(name)s - %(levelname)s - %(message)s", level=log_level
)
thing = "beer"
logging.info('Would you like to have a "%s"?', thing)
2025-11-21 16:26:41,907 - root - INFO - Would you like to have a "beer"?
Todo
Check standard library
Small examples from (or just mention)
sys,os/shutils,copy,pathlib/globargparse,math,re,dataclasses,itertools,turtle,functools,unittest,collections,datetimeMention good alternatives outside of the standard library (pytest, click, requests/urllib3, typing-extensions, python-dateutil/pendulum, fsspec, certifi, idna, …)