Complete Assigned Readings

Open a section to study the full text and its source attribution. Course links open the assigned section directly.

6. Modules

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

6. Modules

If you quit from the Python interpreter and enter it again, the definitions you have made (functions and variables) are lost. Therefore, if you want to write a somewhat longer program, you are better off using a text editor to prepare the input for the interpreter and running it with that file as input instead. This is known as creating a script. As your program gets longer, you may want to split it into several files for easier maintenance. You may also want to use a handy function that you’ve written in several programs without copying its definition into each program.

To support this, Python has a way to put definitions in a file and use them in a script or in an interactive instance of the interpreter. Such a file is called a module; definitions from a module can be imported into other modules or into the main module (the collection of variables that you have access to in a script executed at the top level and in calculator mode).

A module is a file containing Python definitions and statements. The file name is the module name with the suffix .py appended. Within a module, the module’s name (as a string) is available as the value of the global variable __name__. For instance, use your favorite text editor to create a file called fibo.py in the current directory with the following contents:

# Fibonacci numbers module

def fib(n):
    """Write Fibonacci series up to n."""
    a, b = 0, 1
    while a < n:
        print(a, end=' ')
        a, b = b, a+b
    print()

def fib2(n):
    """Return Fibonacci series up to n."""
    result = []
    a, b = 0, 1
    while a < n:
        result.append(a)
        a, b = b, a+b
    return result

Now enter the Python interpreter and import this module with the following command:

>>> import fibo

This does not add the names of the functions defined in fibo directly to the current namespace (see Python Scopes and Namespaces for more details); it only adds the module name fibo there. Using the module name you can access the functions:

>>> fibo.fib(1000)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
>>> fibo.fib2(100)
[0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
>>> fibo.__name__
'fibo'

If you intend to use a function often you can assign it to a local name:

>>> fib = fibo.fib
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

6.1. More on Modules

A module can contain executable statements as well as function definitions. These statements are intended to initialize the module. They are executed only the first time the module name is encountered in an import statement. [1] (They are also run if the file is executed as a script.)

Each module has its own private namespace, which is used as the global namespace by all functions defined in the module. Thus, the author of a module can use global variables in the module without worrying about accidental clashes with a user’s global variables. On the other hand, if you know what you are doing you can touch a module’s global variables with the same notation used to refer to its functions, modname.itemname.

Modules can import other modules. It is customary but not required to place all import statements at the beginning of a module (or script, for that matter). The imported module names, if placed at the top level of a module (outside any functions or classes), are added to the module’s global namespace.

There is a variant of the import statement that imports names from a module directly into the importing module’s namespace. For example:

>>> from fibo import fib, fib2
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This does not introduce the module name from which the imports are taken in the local namespace (so in the example, fibo is not defined).

There is even a variant to import all names that a module defines:

>>> from fibo import *
>>> fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This imports all names except those beginning with an underscore (_). In most cases Python programmers do not use this facility since it introduces an unknown set of names into the interpreter, possibly hiding some things you have already defined.

Note that in general the practice of importing * from a module or package is frowned upon, since it often causes poorly readable code. However, it is okay to use it to save typing in interactive sessions.

If the module name is followed by as, then the name following as is bound directly to the imported module.

>>> import fibo as fib
>>> fib.fib(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

This is effectively importing the module in the same way that import fibo will do, with the only difference of it being available as fib.

It can also be used when utilising from with similar effects:

>>> from fibo import fib as fibonacci
>>> fibonacci(500)
0 1 1 2 3 5 8 13 21 34 55 89 144 233 377

Note

For efficiency reasons, each module is only imported once per interpreter session. Therefore, if you change your modules, you must restart the interpreter – or, if it’s just one module you want to test interactively, use importlib.reload(), e.g. import importlib; importlib.reload(modulename).

6.1.1. Executing modules as scripts

When you run a Python module with

python fibo.py <arguments>

the code in the module will be executed, just as if you imported it, but with the __name__ set to "__main__". That means that by adding this code at the end of your module:

if __name__ == "__main__":
    import sys
    fib(int(sys.argv[1]))

you can make the file usable as a script as well as an importable module, because the code that parses the command line only runs if the module is executed as the “main” file:

$ python fibo.py 50
0 1 1 2 3 5 8 13 21 34

If the module is imported, the code is not run:

>>> import fibo
>>>

This is often used either to provide a convenient user interface to a module, or for testing purposes (running the module as a script executes a test suite).

6.1.2. The Module Search Path

When a module named spam is imported, the interpreter first searches for a built-in module with that name. These module names are listed in sys.builtin_module_names. If not found, it then searches for a file named spam.py in a list of directories given by the variable sys.path. sys.path is initialized from these locations:

  • The directory containing the input script (or the current directory when no file is specified).

  • PYTHONPATH (a list of directory names, with the same syntax as the shell variable PATH).

  • The installation-dependent default (by convention including a site-packages directory, handled by the site module).

More details are at The initialization of the sys.path module search path.

Note

On file systems which support symlinks, the directory containing the input script is calculated after the symlink is followed. In other words the directory containing the symlink is not added to the module search path.

After initialization, Python programs can modify sys.path. The directory containing the script being run is placed at the beginning of the search path, ahead of the standard library path. This means that scripts in that directory will be loaded instead of modules of the same name in the library directory. This is an error unless the replacement is intended. See section Standard Modules for more information.

6.1.3. “Compiled” Python files

To speed up loading modules, Python caches the compiled version of each module in the __pycache__ directory under the name module.version.pyc, where the version encodes the format of the compiled file; it generally contains the Python version number. For example, in CPython release 3.3 the compiled version of spam.py would be cached as __pycache__/spam.cpython-33.pyc. This naming convention allows compiled modules from different releases and different versions of Python to coexist.

Python checks the modification date of the source against the compiled version to see if it’s out of date and needs to be recompiled. This is a completely automatic process. Also, the compiled modules are platform-independent, so the same library can be shared among systems with different architectures.

Python does not check the cache in two circumstances. First, it always recompiles and does not store the result for the module that’s loaded directly from the command line. Second, it does not check the cache if there is no source module. To support a non-source (compiled only) distribution, the compiled module must be in the source directory, and there must not be a source module.

Some tips for experts:

  • You can use the -O or -OO switches on the Python command to reduce the size of a compiled module. The -O switch removes assert statements, the -OO switch removes both assert statements and __doc__ strings. Since some programs may rely on having these available, you should only use this option if you know what you’re doing. “Optimized” modules have an opt- tag and are usually smaller. Future releases may change the effects of optimization.

  • A program doesn’t run any faster when it is read from a .pyc file than when it is read from a .py file; the only thing that’s faster about .pyc files is the speed with which they are loaded.

  • The module compileall can create .pyc files for all modules in a directory.

  • There is more detail on this process, including a flow chart of the decisions, in PEP 3147.

6.2. Standard Modules

Python comes with a library of standard modules, described in a separate document, the Python Library Reference (“Library Reference” hereafter). Some modules are built into the interpreter; these provide access to operations that are not part of the core of the language but are nevertheless built in, either for efficiency or to provide access to operating system primitives such as system calls. The set of such modules is a configuration option which also depends on the underlying platform. For example, the winreg module is only provided on Windows systems. One particular module deserves some attention: sys, which is built into every Python interpreter. The variables sys.ps1 and sys.ps2 define the strings used as primary and secondary prompts:

>>> import sys
>>> sys.ps1
'>>> '
>>> sys.ps2
'... '
>>> sys.ps1 = 'C> '
C> print('Yuck!')
Yuck!
C>

These two variables are only defined if the interpreter is in interactive mode.

The variable sys.path is a list of strings that determines the interpreter’s search path for modules. It is initialized to a default path taken from the environment variable PYTHONPATH, or from a built-in default if PYTHONPATH is not set. You can modify it using standard list operations:

>>> import sys
>>> sys.path.append('/ufs/guido/lib/python')

6.3. The dir() Function

The built-in function dir() is used to find out which names a module defines. It returns a sorted list of strings:

>>> import fibo, sys
>>> dir(fibo)
['__name__', 'fib', 'fib2']
>>> dir(sys)
['__breakpointhook__', '__displayhook__', '__doc__', '__excepthook__',
 '__interactivehook__', '__loader__', '__name__', '__package__', '__spec__',
 '__stderr__', '__stdin__', '__stdout__', '__unraisablehook__',
 '_clear_type_cache', '_current_frames', '_debugmallocstats', '_framework',
 '_getframe', '_git', '_home', '_xoptions', 'abiflags', 'addaudithook',
 'api_version', 'argv', 'audit', 'base_exec_prefix', 'base_prefix',
 'breakpointhook', 'builtin_module_names', 'byteorder', 'call_tracing',
 'callstats', 'copyright', 'displayhook', 'dont_write_bytecode', 'exc_info',
 'excepthook', 'exec_prefix', 'executable', 'exit', 'flags', 'float_info',
 'float_repr_style', 'get_asyncgen_hooks', 'get_coroutine_origin_tracking_depth',
 'getallocatedblocks', 'getdefaultencoding', 'getdlopenflags',
 'getfilesystemencodeerrors', 'getfilesystemencoding', 'getprofile',
 'getrecursionlimit', 'getrefcount', 'getsizeof', 'getswitchinterval',
 'gettrace', 'hash_info', 'hexversion', 'implementation', 'int_info',
 'intern', 'is_finalizing', 'last_traceback', 'last_type', 'last_value',
 'maxsize', 'maxunicode', 'meta_path', 'modules', 'path', 'path_hooks',
 'path_importer_cache', 'platform', 'prefix', 'ps1', 'ps2', 'pycache_prefix',
 'set_asyncgen_hooks', 'set_coroutine_origin_tracking_depth', 'setdlopenflags',
 'setprofile', 'setrecursionlimit', 'setswitchinterval', 'settrace', 'stderr',
 'stdin', 'stdout', 'thread_info', 'unraisablehook', 'version', 'version_info',
 'warnoptions']

Without arguments, dir() lists the names you have defined currently:

>>> a = [1, 2, 3, 4, 5]
>>> import fibo
>>> fib = fibo.fib
>>> dir()
['__builtins__', '__name__', 'a', 'fib', 'fibo', 'sys']

Note that it lists all types of names: variables, modules, functions, etc.

dir() does not list the names of built-in functions and variables. If you want a list of those, they are defined in the standard module builtins:

>>> import builtins
>>> dir(builtins)
['ArithmeticError', 'AssertionError', 'AttributeError', 'BaseException',
 'BlockingIOError', 'BrokenPipeError', 'BufferError', 'BytesWarning',
 'ChildProcessError', 'ConnectionAbortedError', 'ConnectionError',
 'ConnectionRefusedError', 'ConnectionResetError', 'DeprecationWarning',
 'EOFError', 'Ellipsis', 'EnvironmentError', 'Exception', 'False',
 'FileExistsError', 'FileNotFoundError', 'FloatingPointError',
 'FutureWarning', 'GeneratorExit', 'IOError', 'ImportError',
 'ImportWarning', 'IndentationError', 'IndexError', 'InterruptedError',
 'IsADirectoryError', 'KeyError', 'KeyboardInterrupt', 'LookupError',
 'MemoryError', 'NameError', 'None', 'NotADirectoryError', 'NotImplemented',
 'NotImplementedError', 'OSError', 'OverflowError',
 'PendingDeprecationWarning', 'PermissionError', 'ProcessLookupError',
 'ReferenceError', 'ResourceWarning', 'RuntimeError', 'RuntimeWarning',
 'StopIteration', 'SyntaxError', 'SyntaxWarning', 'SystemError',
 'SystemExit', 'TabError', 'TimeoutError', 'True', 'TypeError',
 'UnboundLocalError', 'UnicodeDecodeError', 'UnicodeEncodeError',
 'UnicodeError', 'UnicodeTranslateError', 'UnicodeWarning', 'UserWarning',
 'ValueError', 'Warning', 'ZeroDivisionError', '_', '__build_class__',
 '__debug__', '__doc__', '__import__', '__name__', '__package__', 'abs',
 'all', 'any', 'ascii', 'bin', 'bool', 'bytearray', 'bytes', 'callable',
 'chr', 'classmethod', 'compile', 'complex', 'copyright', 'credits',
 'delattr', 'dict', 'dir', 'divmod', 'enumerate', 'eval', 'exec', 'exit',
 'filter', 'float', 'format', 'frozenset', 'getattr', 'globals', 'hasattr',
 'hash', 'help', 'hex', 'id', 'input', 'int', 'isinstance', 'issubclass',
 'iter', 'len', 'license', 'list', 'locals', 'map', 'max', 'memoryview',
 'min', 'next', 'object', 'oct', 'open', 'ord', 'pow', 'print', 'property',
 'quit', 'range', 'repr', 'reversed', 'round', 'set', 'setattr', 'slice',
 'sorted', 'staticmethod', 'str', 'sum', 'super', 'tuple', 'type', 'vars',
 'zip']

6.4. Packages

Packages are a way of structuring Python’s module namespace by using “dotted module names”. For example, the module name A.B designates a submodule named B in a package named A. Just like the use of modules saves the authors of different modules from having to worry about each other’s global variable names, the use of dotted module names saves the authors of multi-module packages like NumPy or Pillow from having to worry about each other’s module names.

Suppose you want to design a collection of modules (a “package”) for the uniform handling of sound files and sound data. There are many different sound file formats (usually recognized by their extension, for example: .wav, .aiff, .au), so you may need to create and maintain a growing collection of modules for the conversion between the various file formats. There are also many different operations you might want to perform on sound data (such as mixing, adding echo, applying an equalizer function, creating an artificial stereo effect), so in addition you will be writing a never-ending stream of modules to perform these operations. Here’s a possible structure for your package (expressed in terms of a hierarchical filesystem):

sound/                          Top-level package
      __init__.py               Initialize the sound package
      formats/                  Subpackage for file format conversions
              __init__.py
              wavread.py
              wavwrite.py
              aiffread.py
              aiffwrite.py
              auread.py
              auwrite.py
              ...
      effects/                  Subpackage for sound effects
              __init__.py
              echo.py
              surround.py
              reverse.py
              ...
      filters/                  Subpackage for filters
              __init__.py
              equalizer.py
              vocoder.py
              karaoke.py
              ...

When importing the package, Python searches through the directories on sys.path looking for the package subdirectory.

The __init__.py files are required to make Python treat directories containing the file as packages (unless using a namespace package, a relatively advanced feature). This prevents directories with a common name, such as string, from unintentionally hiding valid modules that occur later on the module search path. In the simplest case, __init__.py can just be an empty file, but it can also execute initialization code for the package or set the __all__ variable, described later.

Users of the package can import individual modules from the package, for example:

import sound.effects.echo

This loads the submodule sound.effects.echo. It must be referenced with its full name.

sound.effects.echo.echofilter(input, output, delay=0.7, atten=4)

An alternative way of importing the submodule is:

from sound.effects import echo

This also loads the submodule echo, and makes it available without its package prefix, so it can be used as follows:

echo.echofilter(input, output, delay=0.7, atten=4)

Yet another variation is to import the desired function or variable directly:

from sound.effects.echo import echofilter

Again, this loads the submodule echo, but this makes its function echofilter() directly available:

echofilter(input, output, delay=0.7, atten=4)

Note that when using from package import item, the item can be either a submodule (or subpackage) of the package, or some other name defined in the package, like a function, class or variable. The import statement first tests whether the item is defined in the package; if not, it assumes it is a module and attempts to load it. If it fails to find it, an ImportError exception is raised.

Contrarily, when using syntax like import item.subitem.subsubitem, each item except for the last must be a package; the last item can be a module or a package but can’t be a class or function or variable defined in the previous item.

6.4.1. Importing * From a Package

Now what happens when the user writes from sound.effects import *? Ideally, one would hope that this somehow goes out to the filesystem, finds which submodules are present in the package, and imports them all. This could take a long time and importing sub-modules might have unwanted side-effects that should only happen when the sub-module is explicitly imported.

The only solution is for the package author to provide an explicit index of the package. The import statement uses the following convention: if a package’s __init__.py code defines a list named __all__, it is taken to be the list of module names that should be imported when from package import * is encountered. It is up to the package author to keep this list up-to-date when a new version of the package is released. Package authors may also decide not to support it, if they don’t see a use for importing * from their package. For example, the file sound/effects/__init__.py could contain the following code:

__all__ = ["echo", "surround", "reverse"]

This would mean that from sound.effects import * would import the three named submodules of the sound.effects package.

Be aware that submodules might become shadowed by locally defined names. For example, if you added a reverse function to the sound/effects/__init__.py file, the from sound.effects import * would only import the two submodules echo and surround, but not the reverse submodule, because it is shadowed by the locally defined reverse function:

__all__ = [
    "echo",      # refers to the 'echo.py' file
    "surround",  # refers to the 'surround.py' file
    "reverse",   # !!! refers to the 'reverse' function now !!!
]

def reverse(msg: str):  # <-- this name shadows the 'reverse.py' submodule
    return msg[::-1]    #     in the case of a 'from sound.effects import *'

If __all__ is not defined, the statement from sound.effects import * does not import all submodules from the package sound.effects into the current namespace; it only ensures that the package sound.effects has been imported (possibly running any initialization code in __init__.py) and then imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py. It also includes any submodules of the package that were explicitly loaded by previous import statements. Consider this code:

import sound.effects.echo
import sound.effects.surround
from sound.effects import *

In this example, the echo and surround modules are imported in the current namespace because they are defined in the sound.effects package when the from...import statement is executed. (This also works when __all__ is defined.)

Although certain modules are designed to export only names that follow certain patterns when you use import *, it is still considered bad practice in production code.

Remember, there is nothing wrong with using from package import specific_submodule! In fact, this is the recommended notation unless the importing module needs to use submodules with the same name from different packages.

6.4.2. Intra-package References

When packages are structured into subpackages (as with the sound package in the example), you can use absolute imports to refer to submodules of siblings packages. For example, if the module sound.filters.vocoder needs to use the echo module in the sound.effects package, it can use from sound.effects import echo.

You can also write relative imports, with the from module import name form of import statement. These imports use leading dots to indicate the current and parent packages involved in the relative import. From the surround module for example, you might use:

from . import echo
from .. import formats
from ..filters import equalizer

Note that relative imports are based on the name of the current module’s package. Since the main module does not have a package, modules intended for use as the main module of a Python application must always use absolute imports.

Footnotes

logging — Logging facility for Python

Assigned source reading · Python Software Foundation and Python documentation contributors

Copyright © 2001 Python Software Foundation; All Rights Reserved

Original source · Python Software Foundation License Version 2 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
PYTHON SOFTWARE FOUNDATION LICENSE VERSION 2
¶
1. This LICENSE AGREEMENT is between the Python Software Foundation ("PSF"), and
   the Individual or Organization ("Licensee") accessing and otherwise using this
   software ("Python") in source or binary form and its associated documentation.

2. Subject to the terms and conditions of this License Agreement, PSF hereby
   grants Licensee a nonexclusive, royalty-free, world-wide license to reproduce,
   analyze, test, perform and/or display publicly, prepare derivative works,
   distribute, and otherwise use Python alone or in any derivative
   version, provided, however, that PSF's License Agreement and PSF's notice of
   copyright, i.e., "Copyright © 2001 Python Software Foundation; All Rights
   Reserved" are retained in Python alone or in any derivative version
   prepared by Licensee.

3. In the event Licensee prepares a derivative work that is based on or
   incorporates Python or any part thereof, and wants to make the
   derivative work available to others as provided herein, then Licensee hereby
   agrees to include in any such work a brief summary of the changes made to Python.

4. PSF is making Python available to Licensee on an "AS IS" basis.
   PSF MAKES NO REPRESENTATIONS OR WARRANTIES, EXPRESS OR IMPLIED.  BY WAY OF
   EXAMPLE, BUT NOT LIMITATION, PSF MAKES NO AND DISCLAIMS ANY REPRESENTATION OR
   WARRANTY OF MERCHANTABILITY OR FITNESS FOR ANY PARTICULAR PURPOSE OR THAT THE
   USE OF PYTHON WILL NOT INFRINGE ANY THIRD PARTY RIGHTS.

5. PSF SHALL NOT BE LIABLE TO LICENSEE OR ANY OTHER USERS OF PYTHON
   FOR ANY INCIDENTAL, SPECIAL, OR CONSEQUENTIAL DAMAGES OR LOSS AS A RESULT OF
   MODIFYING, DISTRIBUTING, OR OTHERWISE USING PYTHON, OR ANY DERIVATIVE
   THEREOF, EVEN IF ADVISED OF THE POSSIBILITY THEREOF.

6. This License Agreement will automatically terminate upon a material breach of
   its terms and conditions.

7. Nothing in this License Agreement shall be deemed to create any relationship
   of agency, partnership, or joint venture between PSF and Licensee.  This License
   Agreement does not grant permission to use PSF trademarks or trade name in a
   trademark sense to endorse or promote products or services of Licensee, or any
   third party.

8. By copying, installing or otherwise using Python, Licensee agrees
   to be bound by the terms and conditions of this License Agreement.

logging — Logging facility for Python

Source code: Lib/logging/__init__.py


This module defines functions and classes which implement a flexible event logging system for applications and libraries.

The key benefit of having the logging API provided by a standard library module is that all Python modules can participate in logging, so your application log can include your own messages integrated with messages from third-party modules.

Here’s a simple example of idiomatic usage:

# myapp.py
import logging
import mylib
logger = logging.getLogger(__name__)

def main():
    logging.basicConfig(filename='myapp.log', level=logging.INFO)
    logger.info('Started')
    mylib.do_something()
    logger.info('Finished')

if __name__ == '__main__':
    main()
# mylib.py
import logging
logger = logging.getLogger(__name__)

def do_something():
    logger.info('Doing something')

If you run myapp.py, you should see this in myapp.log:

INFO:__main__:Started
INFO:mylib:Doing something
INFO:__main__:Finished

The key feature of this idiomatic usage is that the majority of code is simply creating a module level logger with getLogger(__name__), and using that logger to do any needed logging. This is concise, while allowing downstream code fine-grained control if needed. Logged messages to the module-level logger get forwarded to handlers of loggers in higher-level modules, all the way up to the highest-level logger known as the root logger; this approach is known as hierarchical logging.

For logging to be useful, it needs to be configured: setting the levels and destinations for each logger, potentially changing how specific modules log, often based on command-line arguments or application configuration. In most cases, like the one above, only the root logger needs to be so configured, since all the lower level loggers at module level eventually forward their messages to its handlers. basicConfig() provides a quick way to configure the root logger that handles many use cases.

The module provides a lot of functionality and flexibility. If you are unfamiliar with logging, the best way to get to grips with it is to view the tutorials (see the links above and on the right).

The basic classes defined by the module, together with their attributes and methods, are listed in the sections below.

  • Loggers expose the interface that application code directly uses.

  • Handlers send the log records (created by loggers) to the appropriate destination.

  • Filters provide a finer grained facility for determining which log records to output.

  • Formatters specify the layout of log records in the final output.

Logger Objects

Loggers have the following attributes and methods. Note that Loggers should NEVER be instantiated directly, but always through the module-level function logging.getLogger(name). Multiple calls to getLogger() with the same name will always return a reference to the same Logger object.

The name is potentially a period-separated hierarchical value, like foo.bar.baz (though it could also be just plain foo, for example). Loggers that are further down in the hierarchical list are children of loggers higher up in the list. For example, given a logger with a name of foo, loggers with names of foo.bar, foo.bar.baz, and foo.bam are all descendants of foo. In addition, all loggers are descendants of the root logger. The logger name hierarchy is analogous to the Python package hierarchy, and identical to it if you organise your loggers on a per-module basis using the recommended construction logging.getLogger(__name__). That’s because in a module, __name__ is the module’s name in the Python package namespace.

class logging.Logger
name

This is the logger’s name, and is the value that was passed to getLogger() to obtain the logger.

Note

This attribute should be treated as read-only.

level

The threshold of this logger, as set by the setLevel() method.

Note

Do not set this attribute directly - always use setLevel(), which has checks for the level passed to it.

parent

The parent logger of this logger. It may change based on later instantiation of loggers which are higher up in the namespace hierarchy.

Note

This value should be treated as read-only.

propagate

If this attribute evaluates to true, events logged to this logger will be passed to the handlers of higher level (ancestor) loggers, in addition to any handlers attached to this logger. Messages are passed directly to the ancestor loggers’ handlers - neither the level nor filters of the ancestor loggers in question are considered.

If this evaluates to false, logging messages are not passed to the handlers of ancestor loggers.

Spelling it out with an example: If the propagate attribute of the logger named A.B.C evaluates to true, any event logged to A.B.C via a method call such as logging.getLogger('A.B.C').error(...) will [subject to passing that logger’s level and filter settings] be passed in turn to any handlers attached to loggers named A.B, A and the root logger, after first being passed to any handlers attached to A.B.C. If any logger in the chain A.B.C, A.B, A has its propagate attribute set to false, then that is the last logger whose handlers are offered the event to handle, and propagation stops at that point.

The constructor sets this attribute to True.

Note

If you attach a handler to a logger and one or more of its ancestors, it may emit the same record multiple times. In general, you should not need to attach a handler to more than one logger - if you just attach it to the appropriate logger which is highest in the logger hierarchy, then it will see all events logged by all descendant loggers, provided that their propagate setting is left set to True. A common scenario is to attach handlers only to the root logger, and to let propagation take care of the rest.

handlers

The list of handlers directly attached to this logger instance.

Note

This attribute should be treated as read-only; it is normally changed via the addHandler() and removeHandler() methods, which use locks to ensure thread-safe operation.

disabled

This attribute disables handling of any events. It is set to False in the initializer, and only changed by logging configuration code.

Note

This attribute should be treated as read-only.

setLevel(level)

Sets the threshold for this logger to level. Logging messages which are less severe than level will be ignored; logging messages which have severity level or higher will be emitted by whichever handler or handlers service this logger, unless a handler’s level has been set to a higher severity level than level.

When a logger is created, the level is set to NOTSET (which causes all messages to be processed when the logger is the root logger, or delegation to the parent when the logger is a non-root logger). Note that the root logger is created with level WARNING.

The term ‘delegation to the parent’ means that if a logger has a level of NOTSET, its chain of ancestor loggers is traversed until either an ancestor with a level other than NOTSET is found, or the root is reached.

If an ancestor is found with a level other than NOTSET, then that ancestor’s level is treated as the effective level of the logger where the ancestor search began, and is used to determine how a logging event is handled.

If the root is reached, and it has a level of NOTSET, then all messages will be processed. Otherwise, the root’s level will be used as the effective level.

See Logging Levels for a list of levels.

Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as INFO. Note, however, that levels are internally stored as integers, and methods such as e.g. getEffectiveLevel() and isEnabledFor() will return/expect to be passed integers.

isEnabledFor(level)

Indicates if a message of severity level would be processed by this logger. This method checks first the module-level level set by logging.disable(level) and then the logger’s effective level as determined by getEffectiveLevel().

getEffectiveLevel()

Indicates the effective level for this logger. If a value other than NOTSET has been set using setLevel(), it is returned. Otherwise, the hierarchy is traversed towards the root until a value other than NOTSET is found, and that value is returned. The value returned is an integer, typically one of logging.DEBUG, logging.INFO etc.

getChild(suffix)

Returns a logger which is a descendant to this logger, as determined by the suffix. Thus, logging.getLogger('abc').getChild('def.ghi') would return the same logger as would be returned by logging.getLogger('abc.def.ghi'). This is a convenience method, useful when the parent logger is named using e.g. __name__ rather than a literal string.

Added in version 3.2.

getChildren()

Returns a set of loggers which are immediate children of this logger. So for example logging.getLogger().getChildren() might return a set containing loggers named foo and bar, but a logger named foo.bar wouldn’t be included in the set. Likewise, logging.getLogger('foo').getChildren() might return a set including a logger named foo.bar, but it wouldn’t include one named foo.bar.baz.

Added in version 3.12.

debug(msg, *args, **kwargs)

Logs a message with level DEBUG on this logger. The msg is the message format string, and the args are the arguments which are merged into msg using the string formatting operator. (Note that this means that you can use keywords in the format string, together with a single dictionary argument.) No % formatting operation is performed on msg when no args are supplied.

There are four keyword arguments in kwargs which are inspected: exc_info, stack_info, stacklevel and extra.

If exc_info does not evaluate as false, it causes exception information to be added to the logging message. If an exception tuple (in the format returned by sys.exc_info()) or an exception instance is provided, it is used; otherwise, sys.exc_info() is called to get the exception information.

The second optional keyword argument is stack_info, which defaults to False. If true, stack information is added to the logging message, including the actual logging call. Note that this is not the same stack information as that displayed through specifying exc_info: The former is stack frames from the bottom of the stack up to the logging call in the current thread, whereas the latter is information about stack frames which have been unwound, following an exception, while searching for exception handlers.

You can specify stack_info independently of exc_info, e.g. to just show how you got to a certain point in your code, even when no exceptions were raised. The stack frames are printed following a header line which says:

Stack (most recent call last):

This mimics the Traceback (most recent call last): which is used when displaying exception frames.

The third optional keyword argument is stacklevel, which defaults to 1. If greater than 1, the corresponding number of stack frames are skipped when computing the line number and function name set in the LogRecord created for the logging event. This can be used in logging helpers so that the function name, filename and line number recorded are not the information for the helper function/method, but rather its caller. The name of this parameter mirrors the equivalent one in the warnings module.

The fourth keyword argument is extra which can be used to pass a dictionary which is used to populate the __dict__ of the LogRecord created for the logging event with user-defined attributes. These custom attributes can then be used as you like. For example, they could be incorporated into logged messages. For example:

FORMAT = '%(asctime)s %(clientip)-15s %(user)-8s %(message)s'
logging.basicConfig(format=FORMAT)
d = {'clientip': '192.168.0.1', 'user': 'fbloggs'}
logger = logging.getLogger('tcpserver')
logger.warning('Protocol problem: %s', 'connection reset', extra=d)

would print something like

2006-02-08 22:20:02,165 192.168.0.1 fbloggs  Protocol problem: connection reset

The keys in the dictionary passed in extra should not clash with the keys used by the logging system. (See the section on LogRecord attributes for more information on which keys are used by the logging system.)

If you choose to use these attributes in logged messages, you need to exercise some care. In the above example, for instance, the Formatter has been set up with a format string which expects ‘clientip’ and ‘user’ in the attribute dictionary of the LogRecord. If these are missing, the message will not be logged because a string formatting exception will occur. So in this case, you always need to pass the extra dictionary with these keys.

While this might be annoying, this feature is intended for use in specialized circumstances, such as multi-threaded servers where the same code executes in many contexts, and interesting conditions which arise are dependent on this context (such as remote client IP address and authenticated user name, in the above example). In such circumstances, it is likely that specialized Formatters would be used with particular Handlers.

If no handler is attached to this logger (or any of its ancestors, taking into account the relevant Logger.propagate attributes), the message will be sent to the handler set on lastResort.

Changed in version 3.2: The stack_info parameter was added.

Changed in version 3.5: The exc_info parameter can now accept exception instances.

Changed in version 3.8: The stacklevel parameter was added.

info(msg, *args, **kwargs)

Logs a message with level INFO on this logger. The arguments are interpreted as for debug().

warning(msg, *args, **kwargs)

Logs a message with level WARNING on this logger. The arguments are interpreted as for debug().

Note

There is an obsolete method warn which is functionally identical to warning. As warn is deprecated, please do not use it - use warning instead.

error(msg, *args, **kwargs)

Logs a message with level ERROR on this logger. The arguments are interpreted as for debug().

critical(msg, *args, **kwargs)

Logs a message with level CRITICAL on this logger. The arguments are interpreted as for debug().

log(level, msg, *args, **kwargs)

Logs a message with integer level level on this logger. The other arguments are interpreted as for debug().

exception(msg, *args, **kwargs)

Logs a message with level ERROR on this logger. The arguments are interpreted as for debug(). Exception info is added to the logging message. This method should only be called from an exception handler.

addFilter(filter)

Adds the specified filter filter to this logger.

removeFilter(filter)

Removes the specified filter filter from this logger.

filter(record)

Apply this logger’s filters to the record and return True if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be processed (passed to handlers). If one returns a false value, no further processing of the record occurs.

addHandler(hdlr)

Adds the specified handler hdlr to this logger.

removeHandler(hdlr)

Removes the specified handler hdlr from this logger.

findCaller(stack_info=False, stacklevel=1)

Finds the caller’s source filename and line number. Returns the filename, line number, function name and stack information as a 4-element tuple. The stack information is returned as None unless stack_info is True.

The stacklevel parameter is passed from code calling the debug() and other APIs. If greater than 1, the excess is used to skip stack frames before determining the values to be returned. This will generally be useful when calling logging APIs from helper/wrapper code, so that the information in the event log refers not to the helper/wrapper code, but to the code that calls it.

handle(record)

Handles a record by passing it to all handlers associated with this logger and its ancestors (until a false value of propagate is found). This method is used for unpickled records received from a socket, as well as those created locally. Logger-level filtering is applied using filter().

makeRecord(name, level, fn, lno, msg, args, exc_info, func=None, extra=None, sinfo=None)

This is a factory method which can be overridden in subclasses to create specialized LogRecord instances.

hasHandlers()

Checks to see if this logger has any handlers configured. This is done by looking for handlers in this logger and its parents in the logger hierarchy. Returns True if a handler was found, else False. The method stops searching up the hierarchy whenever a logger with the ‘propagate’ attribute set to false is found - that will be the last logger which is checked for the existence of handlers.

Added in version 3.2.

Changed in version 3.7: Loggers can now be pickled and unpickled.

Logging Levels

The numeric values of logging levels are given in the following table. These are primarily of interest if you want to define your own levels, and need them to have specific values relative to the predefined levels. If you define a level with the same numeric value, it overwrites the predefined value; the predefined name is lost.

Level

Numeric value

What it means / When to use it

logging.NOTSET

0

When set on a logger, indicates that ancestor loggers are to be consulted to determine the effective level. If that still resolves to NOTSET, then all events are logged. When set on a handler, all events are handled.

logging.DEBUG

10

Detailed information, typically only of interest to a developer trying to diagnose a problem.

logging.INFO

20

Confirmation that things are working as expected.

logging.WARNING

30

An indication that something unexpected happened, or that a problem might occur in the near future (e.g. ‘disk space low’). The software is still working as expected.

logging.ERROR

40

Due to a more serious problem, the software has not been able to perform some function.

logging.CRITICAL

50

A serious error, indicating that the program itself may be unable to continue running.

Handler Objects

Handlers have the following attributes and methods. Note that Handler is never instantiated directly; this class acts as a base for more useful subclasses. However, the __init__() method in subclasses needs to call Handler.__init__().

class logging.Handler
__init__(level=NOTSET)

Initializes the Handler instance by setting its level, setting the list of filters to the empty list and creating a lock (using createLock()) for serializing access to an I/O mechanism.

createLock()

Initializes a thread lock which can be used to serialize access to underlying I/O functionality which may not be threadsafe.

acquire()

Acquires the thread lock created with createLock().

release()

Releases the thread lock acquired with acquire().

setLevel(level)

Sets the threshold for this handler to level. Logging messages which are less severe than level will be ignored. When a handler is created, the level is set to NOTSET (which causes all messages to be processed).

See Logging Levels for a list of levels.

Changed in version 3.2: The level parameter now accepts a string representation of the level such as ‘INFO’ as an alternative to the integer constants such as INFO.

setFormatter(fmt)

Sets the formatter for this handler to fmt. The fmt argument must be a Formatter instance or None.

addFilter(filter)

Adds the specified filter filter to this handler.

removeFilter(filter)

Removes the specified filter filter from this handler.

filter(record)

Apply this handler’s filters to the record and return True if the record is to be processed. The filters are consulted in turn, until one of them returns a false value. If none of them return a false value, the record will be emitted. If one returns a false value, the handler will not emit the record.

flush()

Ensure all logging output has been flushed. This version does nothing and is intended to be implemented by subclasses.

close()

Tidy up any resources used by the handler. This version does no output but removes the handler from an internal map of handlers, which is used for handler lookup by name.

Subclasses should ensure that this gets called from overridden close() methods.

handle(record)

Conditionally emits the specified logging record, depending on filters which may have been added to the handler. Wraps the actual emission of the record with acquisition/release of the I/O thread lock.

handleError(record)

This method should be called from handlers when an exception is encountered during an emit() call. If the module-level attribute raiseExceptions is False, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors. You could, however, replace this with a custom handler if you wish. The specified record is the one which was being processed when the exception occurred. (The default value of raiseExceptions is True, as that is more useful during development).

format(record)

Do formatting for a record - if a formatter is set, use it. Otherwise, use the default formatter for the module.

emit(record)

Do whatever it takes to actually log the specified logging record. This version is intended to be implemented by subclasses and so raises a NotImplementedError.

Warning

This method is called after a handler-level lock is acquired, which is released after this method returns. When you override this method, note that you should be careful when calling anything that invokes other parts of the logging API which might do locking, because that might result in a deadlock. Specifically:

  • Logging configuration APIs acquire the module-level lock, and then individual handler-level locks as those handlers are configured.

  • Many logging APIs lock the module-level lock. If such an API is called from this method, it could cause a deadlock if a configuration call is made on another thread, because that thread will try to acquire the module-level lock before the handler-level lock, whereas this thread tries to acquire the module-level lock after the handler-level lock (because in this method, the handler-level lock has already been acquired).

For a list of handlers included as standard, see logging.handlers.

Formatter Objects

class logging.Formatter(fmt=None, datefmt=None, style='%', validate=True, *, defaults=None)

Responsible for converting a LogRecord to an output string to be interpreted by a human or external system.

Parameters:
  • fmt (str) – A format string in the given style for the logged output as a whole. The possible mapping keys are drawn from the LogRecord object’s LogRecord attributes. If not specified, '%(message)s' is used, which is just the logged message.

  • datefmt (str) – A format string for the date/time portion of the logged output. If not specified, the default described in formatTime() is used.

  • style (str) – Can be one of '%', '{' or '$' and determines how the format string will be merged with its data: using one of printf-style String Formatting (%), str.format() ({) or string.Template ($). This only applies to fmt (e.g. '%(message)s' versus '{message}'), not to the actual log messages passed to the logging methods. However, there are other ways to use {- and $-formatting for log messages.

  • validate (bool) – If True (the default), incorrect or mismatched fmt and style will raise a ValueError; for example, logging.Formatter('%(asctime)s - %(message)s', style='{').

  • defaults (dict[str, Any]) – A dictionary with default values to use in custom fields. For example, logging.Formatter('%(ip)s %(message)s', defaults={"ip": None})

Changed in version 3.2: Added the style parameter.

Changed in version 3.8: Added the validate parameter.

Changed in version 3.10: Added the defaults parameter.

format(record)

The record’s attribute dictionary is used as the operand to a string formatting operation. Returns the resulting string. Before formatting the dictionary, a couple of preparatory steps are carried out. The message attribute of the record is computed using msg % args. If the formatting string contains '(asctime)', formatTime() is called to format the event time. If there is exception information, it is formatted using formatException() and appended to the message. Note that the formatted exception information is cached in attribute exc_text. This is useful because the exception information can be pickled and sent across the wire, but you should be careful if you have more than one Formatter subclass which customizes the formatting of exception information. In this case, you will have to clear the cached value (by setting the exc_text attribute to None) after a formatter has done its formatting, so that the next formatter to handle the event doesn’t use the cached value, but recalculates it afresh.

If stack information is available, it’s appended after the exception information, using formatStack() to transform it if necessary.

formatTime(record, datefmt=None)

This method should be called from format() by a formatter which wants to make use of a formatted time. This method can be overridden in formatters to provide for any specific requirement, but the basic behavior is as follows: if datefmt (a string) is specified, it is used with time.strftime() to format the creation time of the record. Otherwise, the format ‘%Y-%m-%d %H:%M:%S,uuu’ is used, where the uuu part is a millisecond value and the other letters are as per the time.strftime() documentation. An example time in this format is 2003-01-23 00:29:50,411. The resulting string is returned.

This function uses a user-configurable function to convert the creation time to a tuple. By default, time.localtime() is used; to change this for a particular formatter instance, set the converter attribute to a function with the same signature as time.localtime() or time.gmtime(). To change it for all formatters, for example if you want all logging times to be shown in GMT, set the converter attribute in the Formatter class.

Changed in version 3.3: Previously, the default format was hard-coded as in this example: 2010-09-06 22:38:15,292 where the part before the comma is handled by a strptime format string ('%Y-%m-%d %H:%M:%S'), and the part after the comma is a millisecond value. Because strptime does not have a format placeholder for milliseconds, the millisecond value is appended using another format string, '%s,%03d' — and both of these format strings have been hardcoded into this method. With the change, these strings are defined as class-level attributes which can be overridden at the instance level when desired. The names of the attributes are default_time_format (for the strptime format string) and default_msec_format (for appending the millisecond value).

Changed in version 3.9: The default_msec_format can be None.

formatException(exc_info)

Formats the specified exception information (a standard exception tuple as returned by sys.exc_info()) as a string. This default implementation just uses traceback.print_exception(). The resulting string is returned.

formatStack(stack_info)

Formats the specified stack information (a string as returned by traceback.print_stack(), but with the last newline removed) as a string. This default implementation just returns the input value.

class logging.BufferingFormatter(linefmt=None)

A base formatter class suitable for subclassing when you want to format a number of records. You can pass a Formatter instance which you want to use to format each line (that corresponds to a single record). If not specified, the default formatter (which just outputs the event message) is used as the line formatter.

formatHeader(records)

Return a header for a list of records. The base implementation just returns the empty string. You will need to override this method if you want specific behaviour, e.g. to show the count of records, a title or a separator line.

formatFooter(records)

Return a footer for a list of records. The base implementation just returns the empty string. You will need to override this method if you want specific behaviour, e.g. to show the count of records or a separator line.

format(records)

Return formatted text for a list of records. The base implementation just returns the empty string if there are no records; otherwise, it returns the concatenation of the header, each record formatted with the line formatter, and the footer.

Filter Objects

Filters can be used by Handlers and Loggers for more sophisticated filtering than is provided by levels. The base filter class only allows events which are below a certain point in the logger hierarchy. For example, a filter initialized with ‘A.B’ will allow events logged by loggers ‘A.B’, ‘A.B.C’, ‘A.B.C.D’, ‘A.B.D’ etc. but not ‘A.BB’, ‘B.A.B’ etc. If initialized with the empty string, all events are passed.

class logging.Filter(name='')

Returns an instance of the Filter class. If name is specified, it names a logger which, together with its children, will have its events allowed through the filter. If name is the empty string, allows every event.

filter(record)

Is the specified record to be logged? Returns false for no, true for yes. Filters can either modify log records in-place or return a completely different record instance which will replace the original log record in any future processing of the event.

Note that filters attached to handlers are consulted before an event is emitted by the handler, whereas filters attached to loggers are consulted whenever an event is logged (using debug(), info(), etc.), before sending an event to handlers. This means that events which have been generated by descendant loggers will not be filtered by a logger’s filter setting, unless the filter has also been applied to those descendant loggers.

You don’t actually need to subclass Filter: you can pass any instance which has a filter method with the same semantics.

Changed in version 3.2: You don’t need to create specialized Filter classes, or use other classes with a filter method: you can use a function (or other callable) as a filter. The filtering logic will check to see if the filter object has a filter attribute: if it does, it’s assumed to be a Filter and its filter() method is called. Otherwise, it’s assumed to be a callable and called with the record as the single parameter. The returned value should conform to that returned by filter().

Changed in version 3.12: You can now return a LogRecord instance from filters to replace the log record rather than modifying it in place. This allows filters attached to a Handler to modify the log record before it is emitted, without having side effects on other handlers.

Although filters are used primarily to filter records based on more sophisticated criteria than levels, they get to see every record which is processed by the handler or logger they’re attached to: this can be useful if you want to do things like counting how many records were processed by a particular logger or handler, or adding, changing or removing attributes in the LogRecord being processed. Obviously changing the LogRecord needs to be done with some care, but it does allow the injection of contextual information into logs (see Using Filters to impart contextual information).

LogRecord Objects

LogRecord instances are created automatically by the Logger every time something is logged, and can be created manually via makeLogRecord() (for example, from a pickled event received over the wire).

class logging.LogRecord(name, level, pathname, lineno, msg, args, exc_info, func=None, sinfo=None)

Contains all the information pertinent to the event being logged.

The primary information is passed in msg and args, which are combined using msg % args to create the message attribute of the record.

Parameters:
  • name (str) – The name of the logger used to log the event represented by this LogRecord. Note that the logger name in the LogRecord will always have this value, even though it may be emitted by a handler attached to a different (ancestor) logger.

  • level (int) – The numeric level of the logging event (such as 10 for DEBUG, 20 for INFO, etc). Note that this is converted to two attributes of the LogRecord: levelno for the numeric value and levelname for the corresponding level name.

  • pathname (str) – The full string path of the source file where the logging call was made.

  • lineno (int) – The line number in the source file where the logging call was made.

  • msg (Any) – The event description message, which can be a %-format string with placeholders for variable data, or an arbitrary object (see Using arbitrary objects as messages).

  • args (tuple | dict[str, Any]) – Variable data to merge into the msg argument to obtain the event description.

  • exc_info (tuple[type[BaseException], BaseException, types.TracebackType] | None) – An exception tuple with the current exception information, as returned by sys.exc_info(), or None if no exception information is available.

  • func (str | None) – The name of the function or method from which the logging call was invoked.

  • sinfo (str | None) – A text string representing stack information from the base of the stack in the current thread, up to the logging call.

getMessage()

Returns the message for this LogRecord instance after merging any user-supplied arguments with the message. If the user-supplied message argument to the logging call is not a string, str() is called on it to convert it to a string. This allows use of user-defined classes as messages, whose __str__ method can return the actual format string to be used.

Changed in version 3.2: The creation of a LogRecord has been made more configurable by providing a factory which is used to create the record. The factory can be set using getLogRecordFactory() and setLogRecordFactory() (see this for the factory’s signature).

This functionality can be used to inject your own values into a LogRecord at creation time. You can use the following pattern:

old_factory = logging.getLogRecordFactory()

def record_factory(*args, **kwargs):
    record = old_factory(*args, **kwargs)
    record.custom_attribute = 0xdecafbad
    return record

logging.setLogRecordFactory(record_factory)

With this pattern, multiple factories could be chained, and as long as they don’t overwrite each other’s attributes or unintentionally overwrite the standard attributes listed above, there should be no surprises.

LogRecord attributes

The LogRecord has a number of attributes, most of which are derived from the parameters to the constructor. (Note that the names do not always correspond exactly between the LogRecord constructor parameters and the LogRecord attributes.) These attributes can be used to merge data from the record into the format string. The following table lists (in alphabetical order) the attribute names, their meanings and the corresponding placeholder in a %-style format string.

If you are using {}-formatting (str.format()), you can use {attrname} as the placeholder in the format string. If you are using $-formatting (string.Template), use the form ${attrname}. In both cases, of course, replace attrname with the actual attribute name you want to use.

In the case of {}-formatting, you can specify formatting flags by placing them after the attribute name, separated from it with a colon. For example: a placeholder of {msecs:03.0f} would format a millisecond value of 4 as 004. Refer to the str.format() documentation for full details on the options available to you.

Attribute name

Format

Description

args

You shouldn’t need to format this yourself.

The tuple of arguments merged into msg to produce message, or a dict whose values are used for the merge (when there is only one argument, and it is a dictionary).

asctime

%(asctime)s

Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond portion of the time).

created

%(created)f

Time when the LogRecord was created (as returned by time.time_ns() / 1e9).

exc_info

You shouldn’t need to format this yourself.

Exception tuple (à la sys.exc_info) or, if no exception has occurred, None.

exc_text

You shouldn’t need to format this yourself.

Exception information formatted as a string. This is set when Formatter.format() is invoked, or None if no exception has occurred.

filename

%(filename)s

Filename portion of pathname.

funcName

%(funcName)s

Name of function containing the logging call.

levelname

%(levelname)s

Text logging level for the message ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').

levelno

%(levelno)s

Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).

lineno

%(lineno)d

Source line number where the logging call was issued (if available).

message

%(message)s

The logged message, computed as msg % args. This is set when Formatter.format() is invoked.

module

%(module)s

Module (name portion of filename).

msecs

%(msecs)d

Millisecond portion of the time when the LogRecord was created.

msg

You shouldn’t need to format this yourself.

The format string passed in the original logging call. Merged with args to produce message, or an arbitrary object (see Using arbitrary objects as messages).

name

%(name)s

Name of the logger used to log the call.

pathname

%(pathname)s

Full pathname of the source file where the logging call was issued (if available).

process

%(process)d

Process ID (if available).

processName

%(processName)s

Process name (if available).

relativeCreated

%(relativeCreated)d

Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.

stack_info

You shouldn’t need to format this yourself.

Stack frame information (where available) from the bottom of the stack in the current thread, up to and including the stack frame of the logging call which resulted in the creation of this record.

thread

%(thread)d

Thread ID (if available).

threadName

%(threadName)s

Thread name (if available).

taskName

%(taskName)s

asyncio.Task name (if available).

Changed in version 3.1: processName was added.

Changed in version 3.12: taskName was added.

LoggerAdapter Objects

LoggerAdapter instances are used to conveniently pass contextual information into logging calls. For a usage example, see the section on adding contextual information to your logging output.

class logging.LoggerAdapter(logger, extra=None, merge_extra=False)

Returns an instance of LoggerAdapter initialized with an underlying Logger instance, an optional dict-like object (extra), and an optional boolean (merge_extra) indicating whether or not the extra argument of individual log calls should be merged with the LoggerAdapter extra. The default behavior is to ignore the extra argument of individual log calls and only use the one of the LoggerAdapter instance

process(msg, kwargs)

Modifies the message and/or keyword arguments passed to a logging call in order to insert contextual information. This implementation takes the object passed as extra to the constructor and adds it to kwargs using key ‘extra’. The return value is a (msg, kwargs) tuple which has the (possibly modified) versions of the arguments passed in.

manager

Delegates to the underlying manager on logger.

_log

Delegates to the underlying _log() method on logger.

In addition to the above, LoggerAdapter supports the following methods of Logger: debug(), info(), warning(), error(), exception(), critical(), log(), isEnabledFor(), getEffectiveLevel(), setLevel() and hasHandlers(). These methods have the same signatures as their counterparts in Logger, so you can use the two types of instances interchangeably.

Changed in version 3.2: The isEnabledFor(), getEffectiveLevel(), setLevel() and hasHandlers() methods were added to LoggerAdapter. These methods delegate to the underlying logger.

Changed in version 3.6: Attribute manager and method _log() were added, which delegate to the underlying logger and allow adapters to be nested.

Changed in version 3.10: The extra argument is now optional.

Changed in version 3.13: The merge_extra parameter was added.

Thread Safety

The logging module is intended to be thread-safe without any special work needing to be done by its clients. It achieves this through using threading locks; there is one lock to serialize access to the module’s shared data, and each handler also creates a lock to serialize access to its underlying I/O.

If you are implementing asynchronous signal handlers using the signal module, you may not be able to use logging from within such handlers. This is because lock implementations in the threading module are not always re-entrant, and so cannot be invoked from such signal handlers.

Module-Level Functions

In addition to the classes described above, there are a number of module-level functions.

logging.getLogger(name=None)

Return a logger with the specified name or, if name is None, return the root logger of the hierarchy. If specified, the name is typically a dot-separated hierarchical name like ‘a’, ‘a.b’ or ‘a.b.c.d’. Choice of these names is entirely up to the developer who is using logging, though it is recommended that __name__ be used unless you have a specific reason for not doing that, as mentioned in Logger Objects.

All calls to this function with a given name return the same logger instance. This means that logger instances never need to be passed between different parts of an application.

logging.getLoggerClass()

Return either the standard Logger class, or the last class passed to setLoggerClass(). This function may be called from within a new class definition, to ensure that installing a customized Logger class will not undo customizations already applied by other code. For example:

class MyLogger(logging.getLoggerClass()):
    # ... override behaviour here
logging.getLogRecordFactory()

Return a callable which is used to create a LogRecord.

Added in version 3.2: This function has been provided, along with setLogRecordFactory(), to allow developers more control over how the LogRecord representing a logging event is constructed.

See setLogRecordFactory() for more information about the how the factory is called.

logging.debug(msg, *args, **kwargs)

This is a convenience function that calls Logger.debug(), on the root logger. The handling of the arguments is in every way identical to what is described in that method.

The only difference is that if the root logger has no handlers, then basicConfig() is called, prior to calling debug on the root logger.

For very short scripts or quick demonstrations of logging facilities, debug and the other module-level functions may be convenient. However, most programs will want to carefully and explicitly control the logging configuration, and should therefore prefer creating a module-level logger and calling Logger.debug() (or other level-specific methods) on it, as described at the beginning of this documentation.

logging.info(msg, *args, **kwargs)

Logs a message with level INFO on the root logger. The arguments and behavior are otherwise the same as for debug().

logging.warning(msg, *args, **kwargs)

Logs a message with level WARNING on the root logger. The arguments and behavior are otherwise the same as for debug().

Note

There is an obsolete function warn which is functionally identical to warning. As warn is deprecated, please do not use it - use warning instead.

logging.error(msg, *args, **kwargs)

Logs a message with level ERROR on the root logger. The arguments and behavior are otherwise the same as for debug().

logging.critical(msg, *args, **kwargs)

Logs a message with level CRITICAL on the root logger. The arguments and behavior are otherwise the same as for debug().

logging.exception(msg, *args, **kwargs)

Logs a message with level ERROR on the root logger. The arguments and behavior are otherwise the same as for debug(). Exception info is added to the logging message. This function should only be called from an exception handler.

logging.log(level, msg, *args, **kwargs)

Logs a message with level level on the root logger. The arguments and behavior are otherwise the same as for debug().

logging.disable(level=CRITICAL)

Provides an overriding level level for all loggers which takes precedence over the logger’s own level. When the need arises to temporarily throttle logging output down across the whole application, this function can be useful. Its effect is to disable all logging calls of severity level and below, so that if you call it with a value of INFO, then all INFO and DEBUG events would be discarded, whereas those of severity WARNING and above would be processed according to the logger’s effective level. If logging.disable(logging.NOTSET) is called, it effectively removes this overriding level, so that logging output again depends on the effective levels of individual loggers.

Note that if you have defined any custom logging level higher than CRITICAL (this is not recommended), you won’t be able to rely on the default value for the level parameter, but will have to explicitly supply a suitable value.

Changed in version 3.7: The level parameter was defaulted to level CRITICAL. See bpo-28524 for more information about this change.

logging.addLevelName(level, levelName)

Associates level level with text levelName in an internal dictionary, which is used to map numeric levels to a textual representation, for example when a Formatter formats a message. This function can also be used to define your own levels. The only constraints are that all levels used must be registered using this function, levels should be positive integers and they should increase in increasing order of severity.

Note

If you are thinking of defining your own levels, please see the section on Custom Levels.

logging.getLevelNamesMapping()

Returns a mapping from level names to their corresponding logging levels. For example, the string “CRITICAL” maps to CRITICAL. The returned mapping is copied from an internal mapping on each call to this function.

Added in version 3.11.

logging.getLevelName(level)

Returns the textual or numeric representation of logging level level.

If level is one of the predefined levels CRITICAL, ERROR, WARNING, INFO or DEBUG then you get the corresponding string. If you have associated levels with names using addLevelName() then the name you have associated with level is returned. If a numeric value corresponding to one of the defined levels is passed in, the corresponding string representation is returned.

The level parameter also accepts a string representation of the level such as ‘INFO’. In such cases, this functions returns the corresponding numeric value of the level.

If no matching numeric or string value is passed in, the string ‘Level %s’ % level is returned.

Note

Levels are internally integers (as they need to be compared in the logging logic). This function is used to convert between an integer level and the level name displayed in the formatted log output by means of the %(levelname)s format specifier (see LogRecord attributes), and vice versa.

Changed in version 3.4: In Python versions earlier than 3.4, this function could also be passed a text level, and would return the corresponding numeric value of the level. This undocumented behaviour was considered a mistake, and was removed in Python 3.4, but reinstated in 3.4.2 in order to retain backward compatibility.

logging.getHandlerByName(name)

Returns a handler with the specified name, or None if there is no handler with that name.

Added in version 3.12.

logging.getHandlerNames()

Returns an immutable set of all known handler names.

Added in version 3.12.

logging.makeLogRecord(attrdict)

Creates and returns a new LogRecord instance whose attributes are defined by attrdict. This function is useful for taking a pickled LogRecord attribute dictionary, sent over a socket, and reconstituting it as a LogRecord instance at the receiving end.

logging.basicConfig(**kwargs)

Does basic configuration for the logging system by either creating a StreamHandler with a default Formatter or using the given formatter instance, and adding it to the root logger. The functions debug(), info(), warning(), error() and critical() will call basicConfig() automatically if no handlers are defined for the root logger.

This function does nothing if the root logger already has handlers configured, unless the keyword argument force is set to True.

Note

This function should be called from the main thread before other threads are started. In versions of Python prior to 2.7.1 and 3.2, if this function is called from multiple threads, it is possible (in rare circumstances) that a handler will be added to the root logger more than once, leading to unexpected results such as messages being duplicated in the log.

The following keyword arguments are supported.

Format

Description

filename

Specifies that a FileHandler be created, using the specified filename, rather than a StreamHandler.

filemode

If filename is specified, open the file in this mode. Defaults to 'a'.

format

Use the specified format string for the handler. Defaults to attributes levelname, name and message separated by colons.

datefmt

Use the specified date/time format, as accepted by time.strftime().

style

If format is specified, use this style for the format string. One of '%', '{' or '$' for printf-style, str.format() or string.Template respectively. Defaults to '%'.

level

Set the root logger level to the specified level.

stream

Use the specified stream to initialize the StreamHandler. Note that this argument is incompatible with filename - if both are present, a ValueError is raised.

handlers

If specified, this should be an iterable of already created handlers to add to the root logger. Any handlers which don’t already have a formatter set will be assigned the default formatter created in this function. Note that this argument is incompatible with filename or stream - if both are present, a ValueError is raised.

force

If this keyword argument is specified as true, any existing handlers attached to the root logger are removed and closed, before carrying out the configuration as specified by the other arguments.

encoding

If this keyword argument is specified along with filename, its value is used when the FileHandler is created, and thus used when opening the output file.

errors

If this keyword argument is specified along with filename, its value is used when the FileHandler is created, and thus used when opening the output file. If not specified, the value ‘backslashreplace’ is used. Note that if None is specified, it will be passed as such to open(), which means that it will be treated the same as passing ‘errors’.

formatter

If specified, set this formatter instance (see Formatter Objects) for all involved handlers. If not specified, the default is to create and use an instance of logging.Formatter based on arguments format, datefmt and style. When formatter is specified together with any of the three arguments format, datefmt and style, a ValueError is raised to signal that these arguments would lose meaning otherwise.

Changed in version 3.2: The style argument was added.

Changed in version 3.3: The handlers argument was added. Additional checks were added to catch situations where incompatible arguments are specified (e.g. handlers together with stream or filename, or stream together with filename).

Changed in version 3.8: The force argument was added.

Changed in version 3.9: The encoding and errors arguments were added.

Changed in version 3.15: The formatter argument was added.

logging.shutdown()

Informs the logging system to perform an orderly shutdown by flushing and closing all handlers. This should be called at application exit and no further use of the logging system should be made after this call.

When the logging module is imported, it registers this function as an exit handler (see atexit), so normally there’s no need to do that manually.

logging.setLoggerClass(klass)

Tells the logging system to use the class klass when instantiating a logger. The class should define __init__() such that only a name argument is required, and the __init__() should call Logger.__init__(). This function is typically called before any loggers are instantiated by applications which need to use custom logger behavior. After this call, as at any other time, do not instantiate loggers directly using the subclass: continue to use the logging.getLogger() API to get your loggers.

logging.setLogRecordFactory(factory)

Set a callable which is used to create a LogRecord.

Parameters:

factory – The factory callable to be used to instantiate a log record.

Added in version 3.2: This function has been provided, along with getLogRecordFactory(), to allow developers more control over how the LogRecord representing a logging event is constructed.

The factory has the following signature:

factory(name, level, fn, lno, msg, args, exc_info, func=None, sinfo=None, **kwargs)

name:

The logger name.

level:

The logging level (numeric).

fn:

The full pathname of the file where the logging call was made.

lno:

The line number in the file where the logging call was made.

msg:

The logging message.

args:

The arguments for the logging message.

exc_info:

An exception tuple, or None.

func:

The name of the function or method which invoked the logging call.

sinfo:

A stack traceback such as is provided by traceback.print_stack(), showing the call hierarchy.

kwargs:

Additional keyword arguments.

Module-Level Attributes

logging.lastResort

A “handler of last resort” is available through this attribute. This is a StreamHandler writing to sys.stderr with a level of WARNING, and is used to handle logging events in the absence of any logging configuration. The end result is to just print the message to sys.stderr. This replaces the earlier error message saying that “no handlers could be found for logger XYZ”. If you need the earlier behaviour for some reason, lastResort can be set to None.

Added in version 3.2.

logging.raiseExceptions

Used to see if exceptions during handling should be propagated.

Default: True.

If raiseExceptions is False, exceptions get silently ignored. This is what is mostly wanted for a logging system - most users will not care about errors in the logging system, they are more interested in application errors.

Integration with the warnings module

The captureWarnings() function can be used to integrate logging with the warnings module.

logging.captureWarnings(capture)

This function is used to turn the capture of warnings by logging on and off.

If capture is True, warnings issued by the warnings module will be redirected to the logging system. Specifically, a warning will be formatted using warnings.formatwarning() and the resulting string logged to a logger named 'py.warnings' with a severity of WARNING.

If capture is False, the redirection of warnings to the logging system will stop, and warnings will be redirected to their original destinations (i.e. those in effect before captureWarnings(True) was called).

See also

Module logging.config

Configuration API for the logging module.

Module logging.handlers

Useful handlers included with the logging module.

PEP 282 - A Logging System

The proposal which described this feature for inclusion in the Python standard library.

Original Python logging package

This is the original source for the logging package. The version of the package available from this site is suitable for use with Python 1.5.2, 2.1.x and 2.2.x, which do not include the logging package in the standard library.

2 . 6 RootishArrayStack: A Space-Efficient Array Stack

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Subsections


2.6 RootishArrayStack: A Space-Efficient Array Stack

One of the drawbacks of all previous data structures in this chapter is that, because they store their data in one or two arrays and they avoid resizing these arrays too often, the arrays frequently are not very full. For example, immediately after a $ \ensuremath{\mathrm{resize}()}$ operation on an ArrayStack, the backing array $ \ensuremath{\ensuremath{\mathit{a}}}$ is only half full. Even worse, there are times when only one third of $ \ensuremath{\ensuremath{\mathit{a}}}$ contains data.

In this section, we discuss the RootishArrayStack data structure, that addresses the problem of wasted space. The RootishArrayStack stores $ \ensuremath{\ensuremath{\mathit{n}}}$ elements using $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$ arrays. In these arrays, at most $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$ array locations are unused at any time. All remaining array locations are used to store data. Therefore, these data structures waste at most $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$ space when storing $ \ensuremath{\ensuremath{\mathit{n}}}$ elements.

A RootishArrayStack stores its elements in a list of $ \ensuremath{\ensuremath{\mathit{r}}}$ arrays called blocks that are numbered $ 0,1,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}-1$. See Figure 2.5. Block $ b$ contains $ b+1$ elements. Therefore, all $ \ensuremath{\ensuremath{\mathit{r}}}$ blocks contain a total of

$\displaystyle 1+ 2+ 3+\cdots +\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}...
...nsuremath{\mathit{r}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}+1)/2
$

elements. The above formula can be obtained as shown in Figure 2.6.

Figure 2.5: A sequence of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations on a RootishArrayStack. Arrows denote elements being copied.
\includegraphics[width=\textwidth ]{figs-python/rootisharraystack}


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...ets \ensuremath{\mathrm{\mathrm{ArrayStack}}()}}\\
\end{flushleft}\end{leftbar}

Figure 2.6: The number of white squares is $ 1+2+3+\cdots+\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}$. The number of shaded squares is the same. Together the white and shaded squares make a rectangle consisting of $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}+1)$ squares.
\includegraphics[scale=0.90909]{figs-python/gauss}

As we might expect, the elements of the list are laid out in order within the blocks. The list element with index 0 is stored in block 0, elements with list indices 1 and 2 are stored in block 1, elements with list indices 3, 4, and 5 are stored in block 2, and so on. The main problem we have to address is that of determining, given an index $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}$, which block contains $ \ensuremath{\ensuremath{\mathit{i}}}$ as well as the index corresponding to $ \ensuremath{\ensuremath{\mathit{i}}}$ within that block.

Determining the index of $ \ensuremath{\ensuremath{\mathit{i}}}$ within its block turns out to be easy. If index $ \ensuremath{\ensuremath{\mathit{i}}}$ is in block $ \ensuremath{\ensuremath{\mathit{b}}}$, then the number of elements in blocks $ 0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}-1$ is $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1)/2$. Therefore, $ \ensuremath{\ensuremath{\mathit{i}}}$ is stored at location

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{j}}}} = \ensuremath{\...
...nsuremath{\mathit{b}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1)/2
$

within block $ \ensuremath{\ensuremath{\mathit{b}}}$. Somewhat more challenging is the problem of determining the value of $ \ensuremath{\ensuremath{\mathit{b}}}$. The number of elements that have indices less than or equal to $ \ensuremath{\ensuremath{\mathit{i}}}$ is $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1$. On the other hand, the number of elements in blocks 0,...,b is $ (\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1)(\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+2)/2$. Therefore, $ \ensuremath{\ensuremath{\mathit{b}}}$ is the smallest integer such that

$\displaystyle (\ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}+1)(\ensuremath...
...{b}}}}+2)/2 \ge \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1 \enspace .
$

We can rewrite this equation as

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}^2 + 3\ensuremat...
...it{b}}}} - 2\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}} \ge 0 \enspace .
$

The corresponding quadratic equation $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}^2 + 3\ensuremath{\ensuremath...
...suremath{\mathit{b}}}} - 2\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}} = 0$ has two solutions: $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}=(-3 + \sqrt{9+8\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}}) / 2$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}=(-3 - \sqrt{9+8\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}}) / 2$. The second solution makes no sense in our application since it always gives a negative value. Therefore, we obtain the solution $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}} = (-3 +
\sqrt{9+8i}) / 2$. In general, this solution is not an integer, but going back to our inequality, we want the smallest integer $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}}$ such that $ \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}} \ge (-3 + \sqrt{9+8i}) / 2$. This is simply

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{b}}}} = \left\lceil(-3 + \sqrt{9+8i}) / 2\right\rceil \enspace .
$


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{i2b}(\ensure...
... \ensuremath{\mathit{i}})}) / \ensuremath{2.0})}\\
\end{flushleft}\end{leftbar}

With this out of the way, the $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ methods are straightforward. We first compute the appropriate block $ \ensuremath{\ensuremath{\mathit{b}}}$ and the appropriate index $ \ensuremath{\ensuremath{\mathit{j}}}$ within the block and then perform the appropriate operation:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{get}(\ensure...
...bf{return}} \ensuremath{\ensuremath{\mathit{y}}}\\
\end{flushleft}\end{leftbar}

If we use any of the data structures in this chapter for representing the $ \ensuremath{\ensuremath{\mathit{blocks}}}$ list, then $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ will each run in constant time.

The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ method will, by now, look familiar. We first check to see if our data structure is full, by checking if the number of blocks, $ \ensuremath{\ensuremath{\mathit{r}}}$, is such that $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}(\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}+1)/2 = \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. If so, we call $ \ensuremath{\mathrm{grow}()}$ to add another block. With this done, we shift elements with indices $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-1$ to the right by one position to make room for the new element with index $ \ensuremath{\ensuremath{\mathit{i}}}$:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...nsuremath{\mathit{i}}, \ensuremath{\mathit{x}})}\\
\end{flushleft}\end{leftbar}

The $ \ensuremath{\mathrm{grow}()}$ method does what we expect. It adds a new block:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{grow}()}\\
...
...ensuremath{\mathit{blocks}}.\mathrm{size}()+1}))\\
\end{flushleft}\end{leftbar}

Ignoring the cost of the $ \ensuremath{\mathrm{grow}()}$ operation, the cost of an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operation is dominated by the cost of shifting and is therefore $ O(1+\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$, just like an ArrayStack.

The $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation is similar to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$. It shifts the elements with indices $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ left by one position and then, if there is more than one empty block, it calls the $ \ensuremath{\mathrm{shrink}()}$ method to remove all but one of the unused blocks:


\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...bf{return}} \ensuremath{\ensuremath{\mathit{x}}}\\
\end{flushleft}\end{leftbar}

\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{shrink}()}\\...
... \gets \ensuremath{\ensuremath{\mathit{r}} - 1}}\\
\end{flushleft}\end{leftbar}

Once again, ignoring the cost of the $ \ensuremath{\mathrm{shrink}()}$ operation, the cost of a $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation is dominated by the cost of shifting and is therefore $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$.

2.6.1 Analysis of Growing and Shrinking

The above analysis of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ does not account for the cost of $ \ensuremath{\mathrm{grow}()}$ and $ \ensuremath{\mathrm{shrink}()}$. Note that, unlike the $ \ensuremath{\mathrm{ArrayStack}.\mathrm{resize}()}$ operation, $ \ensuremath{\mathrm{grow}()}$ and $ \ensuremath{\mathrm{shrink}()}$ do not copy any data. They only allocate or free an array of size $ \ensuremath{\ensuremath{\mathit{r}}}$. In some environments, this takes only constant time, while in others, it may require time proportional to $ \ensuremath{\ensuremath{\mathit{r}}}$.

We note that, immediately after a call to $ \ensuremath{\mathrm{grow}()}$ or $ \ensuremath{\mathrm{shrink}()}$, the situation is clear. The final block is completely empty, and all other blocks are completely full. Another call to $ \ensuremath{\mathrm{grow}()}$ or $ \ensuremath{\mathrm{shrink}()}$ will not happen until at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}-1$ elements have been added or removed. Therefore, even if $ \ensuremath{\mathrm{grow}()}$ and $ \ensuremath{\mathrm{shrink}()}$ take $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}})$ time, this cost can be amortized over at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}-1$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations, so that the amortized cost of $ \ensuremath{\mathrm{grow}()}$ and $ \ensuremath{\mathrm{shrink}()}$ is $ O(1)$ per operation.


2.6.2 Space Usage

Next, we analyze the amount of extra space used by a RootishArrayStack. In particular, we want to count any space used by a RootishArrayStack that is not an array element currently used to hold a list element. We call all such space wasted space.

The $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operation ensures that a RootishArrayStack never has more than two blocks that are not completely full. The number of blocks, $ \ensuremath{\ensuremath{\mathit{r}}}$, used by a RootishArrayStack that stores $ \ensuremath{\ensuremath{\mathit{n}}}$ elements therefore satisfies

$\displaystyle (\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}-2)(\ensuremath...
...thit{r}}}}-1) \le \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \enspace .
$

Again, using the quadratic equation on this gives

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}} \le (3+\sqrt{1+...
...}})/2 = O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}) \enspace .
$

The last two blocks have sizes $ \ensuremath{\ensuremath{\mathit{r}}}$ and $ \ensuremath{\ensuremath{\mathit{r}}-1}$, so the space wasted by these two blocks is at most $ 2\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}-1 = O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$. If we store the blocks in (for example) an ArrayStack, then the amount of space wasted by the List that stores those $ \ensuremath{\ensuremath{\mathit{r}}}$ blocks is also $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}})=O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$. The other space needed for storing $ \ensuremath{\ensuremath{\mathit{n}}}$ and other accounting information is $ O(1)$. Therefore, the total amount of wasted space in a RootishArrayStack is $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$.

Next, we argue that this space usage is optimal for any data structure that starts out empty and can support the addition of one item at a time. More precisely, we will show that, at some point during the addition of $ \ensuremath{\ensuremath{\mathit{n}}}$ items, the data structure is wasting an amount of space at least in $ \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$ (though it may be only wasted for a moment).

Suppose we start with an empty data structure and we add $ \ensuremath{\ensuremath{\mathit{n}}}$ items one at a time. At the end of this process, all $ \ensuremath{\ensuremath{\mathit{n}}}$ items are stored in the structure and distributed among a collection of $ \ensuremath{\ensuremath{\mathit{r}}}$ memory blocks. If $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}\ge \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$, then the data structure must be using $ \ensuremath{\ensuremath{\mathit{r}}}$ pointers (or references) to keep track of these $ \ensuremath{\ensuremath{\mathit{r}}}$ blocks, and these pointers are wasted space. On the other hand, if $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}} < \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$ then, by the pigeonhole principle, some block must have a size of at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}} > \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$. Consider the moment at which this block was first allocated. Immediately after it was allocated, this block was empty, and was therefore wasting $ \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$ space. Therefore, at some point in time during the insertion of $ \ensuremath{\ensuremath{\mathit{n}}}$ elements, the data structure was wasting $ \sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}}$ space.

2.6.3 Summary

The following theorem summarizes our discussion of the RootishArrayStack data structure:

Theorem 2..5   A RootishArrayStack implements the List interface. Ignoring the cost of calls to $ \ensuremath{\mathrm{grow}()}$ and $ \ensuremath{\mathrm{shrink}()}$, a RootishArrayStack supports the operations
  • $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ in $ O(1)$ time per operation; and
  • $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ in $ O(1+\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}})$ time per operation.
Furthermore, beginning with an empty RootishArrayStack, any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ operations results in a total of $ O(m)$ time spent during all calls to $ \ensuremath{\mathrm{grow}()}$ and $ \ensuremath{\mathrm{shrink}()}$.

The space (measured in words)2.2 used by a RootishArrayStack that stores $ \ensuremath{\ensuremath{\mathit{n}}}$ elements is $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} +O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$.



Footnotes

... words)2.2
Recall Section 1.4 for a discussion of how memory is measured.
opendatastructures.org

11 . 2 Counting Sort and Radix Sort

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Subsections

11.2 Counting Sort and Radix Sort

In this section we study two sorting algorithms that are not comparison-based. Specialized for sorting small integers, these algorithms elude the lower-bounds of Theorem 11.5 by using (parts of) the elements in $ \ensuremath{\ensuremath{\mathit{a}}}$ as indices into an array. Consider a statement of the form

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{c}}[\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}]} = 1 \enspace .
$

This statement executes in constant time, but has $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{c}})}$ possible different outcomes, depending on the value of $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$. This means that the execution of an algorithm that makes such a statement cannot be modelled as a binary tree. Ultimately, this is the reason that the algorithms in this section are able to sort faster than comparison-based algorithms.

11.2.1 Counting Sort

Suppose we have an input array $ \ensuremath{\ensuremath{\mathit{a}}}$ consisting of $ \ensuremath{\ensuremath{\mathit{n}}}$ integers, each in the range $ 0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{k}}}}-1$. The counting-sort algorithm sorts $ \ensuremath{\ensuremath{\mathit{a}}}$ using an auxiliary array $ \ensuremath{\ensuremath{\mathit{c}}}$ of counters. It outputs a sorted version of $ \ensuremath{\ensuremath{\mathit{a}}}$ as an auxiliary array $ \ensuremath{\ensuremath{\mathit{b}}}$.

The idea behind counting-sort is simple: For each $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\in\{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{k}}}}-1\}$, count the number of occurrences of $ \ensuremath{\ensuremath{\mathit{i}}}$ in $ \ensuremath{\ensuremath{\mathit{a}}}$ and store this in $ \ensuremath{\ensuremath{\mathit{c}}[\ensuremath{\mathit{i}}]}$. Now, after sorting, the output will look like $ \ensuremath{\ensuremath{\mathit{c}}[0]}$ occurrences of 0, followed by $ \ensuremath{\ensuremath{\mathit{c}}[1]}$ occurrences of 1, followed by $ \ensuremath{\ensuremath{\mathit{c}}[2]}$ occurrences of 2,..., followed by $ \ensuremath{\ensuremath{\mathit{c}}[\ensuremath{\mathit{k}}-1]}$ occurrences of $ \ensuremath{\ensuremath{\mathit{k}}-1}$. The code that does this is very slick, and its execution is illustrated in Figure 11.7:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{counting\_so...
...bf{return}} \ensuremath{\ensuremath{\mathit{b}}}\\
\end{flushleft}\end{leftbar}

Figure 11.7: The operation of counting sort on an array of length $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=20$ that stores integers $ 0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{k}}}}-1=9$.
\includegraphics[width=\textwidth ]{figs-python/countingsort}

The first $ {\color{black} \textbf{for}}$ loop in this code sets each counter $ \ensuremath{\ensuremath{\mathit{c}}[\ensuremath{\mathit{i}}]}$ so that it counts the number of occurrences of $ \ensuremath{\ensuremath{\mathit{i}}}$ in $ \ensuremath{\ensuremath{\mathit{a}}}$. By using the values of $ \ensuremath{\ensuremath{\mathit{a}}}$ as indices, these counters can all be computed in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time with a single for loop. At this point, we could use $ \ensuremath{\ensuremath{\mathit{c}}}$ to fill in the output array $ \ensuremath{\ensuremath{\mathit{b}}}$ directly. However, this would not work if the elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ have associated data. Therefore we spend a little extra effort to copy the elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ into $ \ensuremath{\ensuremath{\mathit{b}}}$.

The next $ {\color{black} \textbf{for}}$ loop, which takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{k}}}})$ time, computes a running-sum of the counters so that $ \ensuremath{\ensuremath{\mathit{c}}[\ensuremath{\mathit{i}}]}$ becomes the number of elements in $ \ensuremath{\ensuremath{\mathit{a}}}$ that are less than or equal to $ \ensuremath{\ensuremath{\mathit{i}}}$. In particular, for every $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\in\{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{k}}}}-1\}$, the output array, $ \ensuremath{\ensuremath{\mathit{b}}}$, will have

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{b}}[\ensuremath{\math...
...\mathit{i}}]-1}]}=\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}} \enspace .
$

Finally, the algorithm scans $ \ensuremath{\ensuremath{\mathit{a}}}$ backwards to place its elements, in order, into an output array $ \ensuremath{\ensuremath{\mathit{b}}}$. When scanning, the element $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{i}]\gets \ensuremath{j}}$ is placed at location $ \ensuremath{\ensuremath{\mathit{b}}[\ensuremath{\mathit{c}}[\ensuremath{\mathit{j}}]-1}]$ and the value $ \ensuremath{\ensuremath{\mathit{c}}[\ensuremath{\mathit{j}}]}$ is decremented.

Theorem 11..7   The $ \ensuremath{\mathrm{counting\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{k}})}$ method can sort an array $ \ensuremath{\ensuremath{\mathit{a}}}$ containing $ \ensuremath{\ensuremath{\mathit{n}}}$ integers in the set $ \{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{k}}}}-1\}$ in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{k}}}})$ time.

The counting-sort algorithm has the nice property of being stable; it preserves the relative order of equal elements. If two elements $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ and $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{j}}]}$ have the same value, and $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}<\ensuremath{\ensuremath{\ensuremath{\mathit{j}}}}$ then $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ will appear before $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{j}}]}$ in $ \ensuremath{\ensuremath{\mathit{b}}}$. This will be useful in the next section.

11.2.2 Radix-Sort

Counting-sort is very efficient for sorting an array of integers when the length, $ \ensuremath{\ensuremath{\mathit{n}}}$, of the array is not much smaller than the maximum value, $ \ensuremath{\ensuremath{\ensuremath{\mathit{k}}}}-1$, that appears in the array. The radix-sort algorithm, which we now describe, uses several passes of counting-sort to allow for a much greater range of maximum values.

Radix-sort sorts $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers by using $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$ passes of counting-sort to sort these integers $ \ensuremath{\ensuremath{\mathit{d}}}$ bits at a time.11.2 More precisely, radix sort first sorts the integers by their least significant $ \ensuremath{\ensuremath{\mathit{d}}}$ bits, then their next significant $ \ensuremath{\ensuremath{\mathit{d}}}$ bits, and so on until, in the last pass, the integers are sorted by their most significant $ \ensuremath{\ensuremath{\mathit{d}}}$ bits.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{radix\_sort}...
...bf{return}} \ensuremath{\ensuremath{\mathit{b}}}\\
\end{flushleft}\end{leftbar}
(In this code, the expression $ \ensuremath{(\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]\ensuremath{\gg}\...
...remath{\mathit{d}}\cdot \ensuremath{\mathit{p}})} \wedge (\ensuremath{2^{d}-1})$ extracts the integer whose binary representation is given by bits $ (\ensuremath{\ensuremath{\ensuremath{\mathit{p}}}}+1)\ensuremath{\ensuremath{\...
...math{\ensuremath{\mathit{p}}}}\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$ of $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$.) An example of the steps of this algorithm is shown in Figure 11.8.

Figure 11.8: Using radixsort to sort $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}=8$-bit integers by using 4 passes of counting sort on $ \ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}=2$-bit integers.
\includegraphics[width=\textwidth ]{figs-python/radixsort}

This remarkable algorithm sorts correctly because counting-sort is a stable sorting algorithm. If $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}} < \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}$ are two elements of $ \ensuremath{\ensuremath{\mathit{a}}}$, and the most significant bit at which $ \ensuremath{\ensuremath{\mathit{x}}}$ differs from $ \ensuremath{\ensuremath{\mathit{y}}}$ has index $ r$, then $ \ensuremath{\ensuremath{\mathit{x}}}$ will be placed before $ \ensuremath{\ensuremath{\mathit{y}}}$ during pass $ \lfloor r/\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}\rfloor$ and subsequent passes will not change the relative order of $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$.

Radix-sort performs $ \ensuremath{\ensuremath{\mathit{w}}/\ensuremath{\mathit{d}}}$ passes of counting-sort. Each pass requires $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}})$ time. Therefore, the performance of radix-sort is given by the following theorem.

Theorem 11..8   For any integer $ \ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}>0$, the $ \ensuremath{\mathrm{radix\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{k}})}$ method can sort an array $ \ensuremath{\ensuremath{\mathit{a}}}$ containing $ \ensuremath{\ensuremath{\mathit{n}}}$ $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers in $ O((\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}/\ensuremath{\ensuremath{\...
...nsuremath{\mathit{n}}}}+2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}))$ time.

If we think, instead, of the elements of the array being in the range $ \{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}^c-1\}$, and take $ \ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}=\lceil\log\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\rceil$ we obtain the following version of Theorem 11.8.

Corollary 11..1   The $ \ensuremath{\mathrm{radix\_sort}(\ensuremath{\mathit{a}},\ensuremath{\mathit{k}})}$ method can sort an array $ \ensuremath{\ensuremath{\mathit{a}}}$ containing $ \ensuremath{\ensuremath{\mathit{n}}}$ integer values in the range $ \{0,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}^c-1\}$ in $ O(c\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time.



Footnotes

... time.11.2
We assume that $ \ensuremath{\ensuremath{\mathit{d}}}$ divides $ \ensuremath{\ensuremath{\mathit{w}}}$, otherwise we can always increase $ \ensuremath{\ensuremath{\mathit{w}}}$ to $ \ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}\lceil
\ensuremath{\ensuremat...
...nsuremath{\mathit{w}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}\rceil$.
opendatastructures.org

9 . 4 Discussion and Exercises

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

9.4 Discussion and Exercises

Red-black trees were first introduced by Guibas and Sedgewick [38]. Despite their high implementation complexity they are found in some of the most commonly used libraries and applications. Most algorithms and data structures textbooks discuss some variant of red-black trees.

Andersson [6] describes a left-leaning version of balanced trees that is similar to red-black trees but has the additional constraint that any node has at most one red child. This implies that these trees simulate 2-3 trees rather than 2-4 trees. They are significantly simpler, though, than the RedBlackTree structure presented in this chapter.

Sedgewick [64] describes two versions of left-leaning red-black trees. These use recursion along with a simulation of top-down splitting and merging in 2-4 trees. The combination of these two techniques makes for particularly short and elegant code.

A related, and older, data structure is the AVL tree [3]. AVL trees are height-balanced: At each node $ u$, the height of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ and the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ differ by at most one. It follows immediately that, if $ F(h)$ is the minimum number of leaves in a tree of height $ h$, then $ F(h)$ obeys the Fibonacci recurrence

$\displaystyle F(h) = F(h-1) + F(h-2)
$

with base cases $ F(0)=1$ and $ F(1)=1$. This means $ F(h)$ is approximately $ \varphi^h/\sqrt{5}$, where $ \varphi=(1+\sqrt{5})/2\approx1.61803399$ is the golden ratio. (More precisely, $ \vert\varphi^h/\sqrt{5} - F(h)\vert\le 1/2$.) Arguing as in the proof of Lemma 9.1, this implies

$\displaystyle h \le \log_\varphi \ensuremath{\ensuremath{\ensuremath{\mathit{n}...
...x 1.440420088\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \enspace ,
$

so AVL trees have smaller height than red-black trees. The height balancing can be maintained during $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations by walking back up the path to the root and performing a rebalancing operation at each node $ \ensuremath{\ensuremath{\mathit{u}}}$ where the height of $ \ensuremath{\ensuremath{\mathit{u}}}$'s left and right subtrees differ by two. See Figure 9.10.

Figure 9.10: Rebalancing in an AVL tree. At most two rotations are required to convert a node whose subtrees have a height of $ h$ and $ h+2$ into a node whose subtrees each have a height of at most $ h+1$.
\includegraphics[scale=0.90909]{figs-python/avl-rebalance}

Andersson's variant of red-black trees, Sedgewick's variant of red-black trees, and AVL trees are all simpler to implement than the RedBlackTree structure defined here. Unfortunately, none of them can guarantee that the amortized time spent rebalancing is $ O(1)$ per update. In particular, there is no analogue of Theorem 9.2 for those structures.

Figure 9.11: A red-black tree on which to practice.
\includegraphics[scale=0.90909]{figs-python/redblack-example}

Exercise 9..1   Illustrate the 2-4 tree that corresponds to the RedBlackTree in Figure 9.11.

Exercise 9..2   Illustrate the addition of 13, then 3.5, then 3.3 on the RedBlackTree in Figure 9.11.

Exercise 9..3   Illustrate the removal of 11, then 9, then 5 on the RedBlackTree in Figure 9.11.

Exercise 9..4   Show that, for arbitrarily large values of $ \ensuremath{\ensuremath{\mathit{n}}}$, there are red-black trees with $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes that have height $ 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-O(1)$.

Exercise 9..5   Consider the operations $ \ensuremath{\mathrm{push\_black}(\ensuremath{\mathit{u}})}$ and $ \ensuremath{\mathrm{pull\_black}(\ensuremath{\mathit{u}})}$. What do these operations do to the underlying 2-4 tree that is being simulated by the red-black tree?

Exercise 9..6   Show that, for arbitrarily large values of $ \ensuremath{\ensuremath{\mathit{n}}}$, there exist sequences of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations that lead to red-black trees with $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes that have height $ 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-O(1)$.

Exercise 9..7   Why does the method $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ in the RedBlackTree implementation perform the assignment $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{parent}\gets \ensuremath{\ensuremath{\mathit{w}}.parent}}$? Shouldn't this already be done by the call to $ \ensuremath{\mathrm{splice}(\ensuremath{\mathit{w}})}$?

Exercise 9..8   Suppose a 2-4 tree, $ T$, has $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_\ell$ leaves and $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i$ internal nodes.
  1. What is the minimum value of $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i$, as a function of $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_\ell$?
  2. What is the maximum value of $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_i$, as a function of $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_\ell$?
  3. If $ T'$ is a red-black tree that represents $ T$, then how many red nodes does $ T'$ have?

Exercise 9..9   Suppose you are given a binary search tree with $ \ensuremath{\ensuremath{\mathit{n}}}$ nodes and a height of at most $ 2\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-2$. Is it always possible to colour the nodes red and black so that the tree satisfies the black-height and no-red-edge properties? If so, can it also be made to satisfy the left-leaning property?

Exercise 9..10   Suppose you have two red-black trees $ T_1$ and $ T_2$ that have the same black height, $ h$, and such that the largest key in $ T_1$ is smaller than the smallest key in $ T_2$. Show how to merge $ T_1$ and $ T_2$ into a single red-black tree in $ O(h)$ time.

Exercise 9..11   Extend your solution to Exercise 9.10 to the case where the two trees $ T_1$ and $ T_2$ have different black heights, $ h_1\neq h_2$. The running-time should be $ O(\max\{h_1,h_2\})$.

Exercise 9..12   Prove that, during an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation, an AVL tree must perform at most one rebalancing operation (that involves at most two rotations; see Figure 9.10). Give an example of an AVL tree and a $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation on that tree that requires on the order of $ \log
\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ rebalancing operations.

Exercise 9..13   Implement an AVLTree class that implements AVL trees as described above. Compare its performance to that of the RedBlackTree implementation. Which implementation has a faster $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation?

Exercise 9..14   Design and implement a series of experiments that compare the relative performance of $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ for the SSet implemeentations SkiplistSSet, ScapegoatTree, Treap, and RedBlackTree. Be sure to include multiple test scenarios, including cases where the data is random, already sorted, is removed in random order, is removed in sorted order, and so on.

opendatastructures.org

13 . 3 YFastTrie: A Doubly-Logarithmic Time SSet

Assigned source reading · Pat Morin

Pat Morin — Open Data Structures, pseudocode edition 0.1G

Original source · Creative Commons Attribution 2.5 Canada · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.


13.3 YFastTrie: A Doubly-Logarithmic Time SSet

The XFastTrie is a vast--even exponential--improvement over the BinaryTrie in terms of query time, but the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations are still not terribly fast. Furthermore, the space usage, $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\cdot\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$, is higher than the other SSet implementations described in this book, which all use $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ space. These two problems are related; if $ \ensuremath{\ensuremath{\mathit{n}}}$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operations build a structure of size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\cdot\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$, then the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation requires at least on the order of $ \ensuremath{\ensuremath{\mathit{w}}}$ time (and space) per operation.

The YFastTrie, discussed next, simultaneously improves the space and speed of XFastTries. A YFastTrie uses an XFastTrie, $ \ensuremath{\ensuremath{\mathit{xft}}}$, but only stores $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ values in $ \ensuremath{\ensuremath{\mathit{xft}}}$. In this way, the total space used by $ \ensuremath{\ensuremath{\mathit{xft}}}$ is only $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$. Furthermore, only one out of every $ \ensuremath{\ensuremath{\mathit{w}}}$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations in the YFastTrie results in an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ or $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation in $ \ensuremath{\ensuremath{\mathit{xft}}}$. By doing this, the average cost incurred by calls to $ \ensuremath{\ensuremath{\mathit{xft}}}$'s $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations is only constant.

The obvious question becomes: If $ \ensuremath{\ensuremath{\mathit{xft}}}$ only stores $ \ensuremath{\ensuremath{\mathit{n}}}$/ $ \ensuremath{\ensuremath{\mathit{w}}}$ elements, where do the remaining $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}(1-1/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ elements go? These elements move into secondary structures, in this case an extended version of treaps (Section 7.2). There are roughly $ \ensuremath{\ensuremath{\mathit{n}}}$/ $ \ensuremath{\ensuremath{\mathit{w}}}$ of these secondary structures so, on average, each of them stores $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ items. Treaps support logarithmic time SSet operations, so the operations on these treaps will run in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time, as required.

More concretely, a YFastTrie contains an XFastTrie, $ \ensuremath{\ensuremath{\mathit{xft}}}$, that contains a random sample of the data, where each element appears in the sample independently with probability $ 1/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. For convenience, the value $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1$, is always contained in $ \ensuremath{\ensuremath{\mathit{xft}}}$. Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_0<\ensuremath{\ensuremath{\e...
...{\mathit{x}}}}_1<\cdots<\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{k-1}$ denote the elements stored in $ \ensuremath{\ensuremath{\mathit{xft}}}$. Associated with each element, $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i$, is a treap, $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}_i$, that stores all values in the range $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{i-1}+1,\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i$. This is illustrated in Figure 13.7.

Figure 13.7: A YFastTrie containing the values 0, 1, 3, 4, 6, 8, 9, 10, 11, and 13.
\includegraphics[scale=0.90909]{figs-python/yfast}

The $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation in a YFastTrie is fairly easy. We search for $ \ensuremath{\ensuremath{\mathit{x}}}$ in $ \ensuremath{\ensuremath{\mathit{xft}}}$ and find some value $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i$ associated with the treap $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}_i$. We then use the treap $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ method on $ \ensuremath{\ensuremath{\ensuremath{\mathit{t}}}}_i$ to answer the query. The entire method is a one-liner:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{find}(\ensur...
...suremath{\mathrm{find}(\ensuremath{\mathit{x}})}\\
\end{flushleft}\end{leftbar}
The first $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation (on $ \ensuremath{\ensuremath{\mathit{xft}}}$) takes $ O(\log\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time. The second $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation (on a treap) takes $ O(\log r)$ time, where $ r$ is the size of the treap. Later in this section, we will show that the expected size of the treap is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ so that this operation takes $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time.13.1

Adding an element to a YFastTrie is also fairly simple--most of the time. The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ method calls $ \ensuremath{\ensuremath{\mathit{xft}}.\mathrm{find}(\ensuremath{\mathit{x}})}$ to locate the treap, $ \ensuremath{\ensuremath{\mathit{t}}}$, into which $ \ensuremath{\ensuremath{\mathit{x}}}$ should be inserted. It then calls $ \ensuremath{\ensuremath{\mathit{t}}.\mathrm{add}(\ensuremath{\mathit{x}})}$ to add $ \ensuremath{\ensuremath{\mathit{x}}}$ to $ \ensuremath{\ensuremath{\mathit{t}}}$. At this point, it tosses a biased coin that comes up as heads with probability $ 1/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$ and as tails with probability $ 1-1/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. If this coin comes up heads, then $ \ensuremath{\ensuremath{\mathit{x}}}$ will be added to $ \ensuremath{\ensuremath{\mathit{xft}}}$.

This is where things get a little more complicated. When $ \ensuremath{\ensuremath{\mathit{x}}}$ is added to $ \ensuremath{\ensuremath{\mathit{xft}}}$, the treap $ \ensuremath{\ensuremath{\mathit{t}}}$ needs to be split into two treaps, $ \ensuremath{\ensuremath{\mathit{t_1}}}$ and $ \ensuremath{t}'$. The treap $ \ensuremath{\ensuremath{\mathit{t_1}}}$ contains all the values less than or equal to $ \ensuremath{\ensuremath{\mathit{x}}}$; $ \ensuremath{t}'$ is the original treap, $ \ensuremath{\ensuremath{\mathit{t}}}$, with the elements of $ \ensuremath{\ensuremath{\mathit{t_1}}}$ removed. Once this is done, we add the pair $ \ensuremath{(\ensuremath{\mathit{x}},\ensuremath{\mathit{t_1}})}$ to $ \ensuremath{\ensuremath{\mathit{xft}}}$. Figure 13.8 shows an example.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...eturn}} \ensuremath{\ensuremath{\mathit{false}}}\\
\end{flushleft}\end{leftbar}

Figure 13.8: Adding the values 2 and 6 to a YFastTrie. The coin toss for 6 came up heads, so 6 was added to $ \ensuremath{\ensuremath{\mathit{xft}}}$ and the treap containing $ 4,5,6,8,9$ was split.
\includegraphics[scale=0.90909]{figs-python/yfast-add}
Adding $ \ensuremath{\ensuremath{\mathit{x}}}$ to $ \ensuremath{\ensuremath{\mathit{t}}}$ takes $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time. Exercise 7.12 shows that splitting $ \ensuremath{\ensuremath{\mathit{t}}}$ into $ \ensuremath{\ensuremath{\mathit{t_1}}}$ and $ \ensuremath{t}'$ can also be done in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ expected time. Adding the pair ( $ \ensuremath{\ensuremath{\mathit{x}}}$, $ \ensuremath{\ensuremath{\mathit{t_1}}}$) to $ \ensuremath{\ensuremath{\mathit{xft}}}$ takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time, but only happens with probability $ 1/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. Therefore, the expected running time of the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation is

$\displaystyle O(\log\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}) + \frac{...
...{w}}}}) = O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}) \enspace .
$

The $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ method undoes the work performed by $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$. We use $ \ensuremath{\ensuremath{\mathit{xft}}}$ to find the leaf, $ \ensuremath{\ensuremath{\mathit{u}}}$, in $ \ensuremath{\ensuremath{\mathit{xft}}}$ that contains the answer to $ \ensuremath{\ensuremath{\mathit{xft}}.\mathrm{find}(\ensuremath{\mathit{x}})}$. From $ \ensuremath{\ensuremath{\mathit{u}}}$, we get the treap, $ \ensuremath{\ensuremath{\mathit{t}}}$, containing $ \ensuremath{\ensuremath{\mathit{x}}}$ and remove $ \ensuremath{\ensuremath{\mathit{x}}}$ from $ \ensuremath{\ensuremath{\mathit{t}}}$. If $ \ensuremath{\ensuremath{\mathit{x}}}$ was also stored in $ \ensuremath{\ensuremath{\mathit{xft}}}$ (and $ \ensuremath{\ensuremath{\mathit{x}}}$ is not equal to $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1$) then we remove $ \ensuremath{\ensuremath{\mathit{x}}}$ from $ \ensuremath{\ensuremath{\mathit{xft}}}$ and add the elements from $ \ensuremath{\ensuremath{\mathit{x}}}$'s treap to the treap, $ \ensuremath{\ensuremath{\mathit{t_2}}}$, that is stored by $ \ensuremath{\ensuremath{\mathit{u}}}$'s successor in the linked list. This is illustrated in Figure 13.9.
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...{return}} \ensuremath{\ensuremath{\mathit{ret}}}\\
\end{flushleft}\end{leftbar}

Figure 13.9: Removing the values 1 and 9 from a YFastTrie in Figure 13.8.
\includegraphics[scale=0.90909]{figs-python/yfast-remove}
Finding the node $ \ensuremath{\ensuremath{\mathit{u}}}$ in $ \ensuremath{\ensuremath{\mathit{xft}}}$ takes $ O(\log\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ expected time. Removing $ \ensuremath{\ensuremath{\mathit{x}}}$ from $ \ensuremath{\ensuremath{\mathit{t}}}$ takes $ O(\log\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ expected time. Again, Exercise 7.12 shows that merging all the elements of $ \ensuremath{\ensuremath{\mathit{t}}}$ into $ \ensuremath{\ensuremath{\mathit{t_2}}}$ can be done in $ O(\log\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time. If necessary, removing $ \ensuremath{\ensuremath{\mathit{x}}}$ from $ \ensuremath{\ensuremath{\mathit{xft}}}$ takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time, but $ \ensuremath{\ensuremath{\mathit{x}}}$ is only contained in $ \ensuremath{\ensuremath{\mathit{xft}}}$ with probability $ 1/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. Therefore, the expected time to remove an element from a YFastTrie is $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$.

Earlier in the discussion, we delayed arguing about the sizes of treaps in this structure until later. Before finishing this chapter, we prove the result we need.

Lemma 13..1   Let $ \ensuremath{\ensuremath{\mathit{x}}}$ be an integer stored in a YFastTrie and let $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}$ denote the number of elements in the treap, $ \ensuremath{\ensuremath{\mathit{t}}}$, that contains $ \ensuremath{\ensuremath{\mathit{x}}}$. Then $ \mathrm{E}[\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_\ensuremath{\ensu...
...uremath{\mathit{x}}}}] \le 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1$.

Proof. Refer to Figure 13.10. Let $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_1<\ensuremath{\ensuremath{\e...
...ath{\ensuremath{\mathit{x}}}}_\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$ denote the elements stored in the YFastTrie. The treap $ \ensuremath{\ensuremath{\mathit{t}}}$ contains some elements greater than or equal to $ \ensuremath{\ensuremath{\mathit{x}}}$. These are $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_i,\ensuremath{\ensuremath{\e...
...it{x}}}}_{i+1},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{i+j-1}$, where $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{i+j-1}$ is the only one of these elements in which the biased coin toss performed in the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ method turned up as heads. In other words, $ \mathrm{E}[j]$ is equal to the expected number of biased coin tosses required to obtain the first heads.13.2 Each coin toss is independent and turns up as heads with probability $ 1/\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$, so $ \mathrm{E}[j]\le\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. (See Lemma 4.2 for an analysis of this for the case $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}=2$.)

Similarly, the elements of $ \ensuremath{\ensuremath{\mathit{t}}}$ smaller than $ \ensuremath{\ensuremath{\mathit{x}}}$ are $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{i-1},\ldots,\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{i-k}$ where all these $ k$ coin tosses turn up as tails and the coin toss for $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}_{i-k-1}$ turns up as heads. Therefore, $ \mathrm{E}[k]\le\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1$, since this is the same coin tossing experiment considered in the preceding paragraph, but one in which the last toss is not counted. In summary, $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}=j+k$, so

$\displaystyle \mathrm{E}[\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_\ens...
...] \le 2\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1 \enspace . \qedhere $

$ \qedsymbol$

Figure 13.10: The number of elements in the treap $ \ensuremath{\ensuremath{\mathit{t}}}$ containing $ \ensuremath{\ensuremath{\mathit{x}}}$ is determined by two coin tossing experiments.
\includegraphics[width=\textwidth ]{figs-python/yfast-sample}

Lemma 13.1 was the last piece in the proof of the following theorem, which summarizes the performance of the YFastTrie:

Theorem 13..3   A YFastTrie implements the SSet interface for $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers. A YFastTrie supports the operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ expected time per operation. The space used by a YFastTrie that stores $ \ensuremath{\ensuremath{\mathit{n}}}$ values is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$.

The $ \ensuremath{\ensuremath{\mathit{w}}}$ term in the space requirement comes from the fact that $ \ensuremath{\ensuremath{\mathit{xft}}}$ always stores the value $ 2^\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1$. The implementation could be modified (at the expense of adding some extra cases to the code) so that it is unnecessary to store this value. In this case, the space requirement in the theorem becomes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.



Footnotes

... time.13.1
This is an application of Jensen's Inequality: If $ \mathrm{E}[r]=\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$, then $ \mathrm{E}[\log r]
\le \log w$.
... heads.13.2
This analysis ignores the fact that $ j$ never exceeds $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}-i+1$. However, this only decreases $ \mathrm{E}[j]$, so the upper bound still holds.
opendatastructures.org

2.2. Concepts #

Assigned source reading · The PostgreSQL Global Development Group and The Regents of the University of California

Portions Copyright © 1996–2026 The PostgreSQL Global Development Group. Portions Copyright © 1994 The Regents of the University of California.

Original source · PostgreSQL License · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Full license and notices
License
PostgreSQL is released under the
PostgreSQL License
,
a liberal Open Source license, similar to the BSD or MIT licenses.
PostgreSQL Database Management System
(also known as Postgres, formerly as Postgres95)
Portions Copyright © 1996-2026, The PostgreSQL Global Development Group
Portions Copyright © 1994, The Regents of the University of California
Permission to use, copy, modify, and distribute this software and its
  documentation for any purpose, without fee, and without a written agreement
  is hereby granted, provided that the above copyright notice and this
  paragraph and the following two paragraphs appear in all copies.
IN NO EVENT SHALL THE UNIVERSITY OF CALIFORNIA BE LIABLE TO ANY PARTY FOR
  DIRECT, INDIRECT, SPECIAL, INCIDENTAL, OR CONSEQUENTIAL DAMAGES, INCLUDING
  LOST PROFITS, ARISING OUT OF THE USE OF THIS SOFTWARE AND ITS
  DOCUMENTATION, EVEN IF THE UNIVERSITY OF CALIFORNIA HAS BEEN ADVISED OF THE
  POSSIBILITY OF SUCH DAMAGE.
THE UNIVERSITY OF CALIFORNIA SPECIFICALLY DISCLAIMS ANY WARRANTIES,
  INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY
  AND FITNESS FOR A PARTICULAR PURPOSE.  THE SOFTWARE PROVIDED HEREUNDER IS
  ON AN "AS IS" BASIS, AND THE UNIVERSITY OF CALIFORNIA HAS NO OBLIGATIONS TO
  PROVIDE MAINTENANCE, SUPPORT, UPDATES, ENHANCEMENTS, OR MODIFICATIONS.
Will PostgreSQL ever be released under a different license?
The PostgreSQL Global Development Group remains committed to making
  PostgreSQL available as free and open source software in perpetuity. There are
  no plans to change the PostgreSQL License or release PostgreSQL under a
  different license.
If you would like to read more about this topic, then please take a look at
  the
mailing list archives
at one of the many discussions
  on this subject.

2.2. Concepts #

PostgreSQL is a relational database management system (RDBMS). That means it is a system for managing data stored in relations. Relation is essentially a mathematical term for table. The notion of storing data in tables is so commonplace today that it might seem inherently obvious, but there are a number of other ways of organizing databases. Files and directories on Unix-like operating systems form an example of a hierarchical database. A more modern development is the object-oriented database.

Each table is a named collection of rows. Each row of a given table has the same set of named columns, and each column is of a specific data type. Whereas columns have a fixed order in each row, it is important to remember that SQL does not guarantee the order of the rows within the table in any way (although they can be explicitly sorted for display).

Tables are grouped into databases, and a collection of databases managed by a single PostgreSQL server instance constitutes a database cluster.

Client-server overview

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

Original source · Creative Commons Attribution-ShareAlike 2.5 or later · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Client-server overview

Now that you know the purpose and potential benefits of server-side programming, we're going to examine in detail what happens when a server receives a "dynamic request" from a browser. As most website server-side code handles requests and responses in similar ways, this will help you understand what you need to do when writing most of your own code.

Prerequisites: A basic understanding of what a web server is.
Objective: To understand client-server interactions in a dynamic website, and in particular what operations need to be performed by server-side code.

There is no real code in the discussion because we haven't yet chosen a web framework to use to write our code! This discussion is however still very relevant, because the described behavior must be implemented by your server-side code, irrespective of which programming language or web framework you select.

Web servers and HTTP (a primer)

Web browsers communicate with web servers using the HyperText Transfer Protocol (HTTP). When you click a link on a web page, submit a form, or run a search, the browser sends an HTTP Request to the server.

This request includes:

  • A URL identifying the target server and resource (e.g., an HTML file, a particular data point on the server, or a tool to run).

  • A method that defines the required action (for example, to get a file or to save or update some data). The different methods/verbs and their associated actions are listed below:

    • GET: Get a specific resource (e.g., an HTML file containing information about a product, or a list of products).
    • POST: Create a new resource (e.g., add a new article to a wiki, add a new contact to a database).
    • HEAD: Get the metadata information about a specific resource without getting the body like GET would. You might for example use a HEAD request to find out the last time a resource was updated, and then only use the (more "expensive") GET request to download the resource if it has changed.
    • PUT: Update an existing resource (or create a new one if it doesn't exist).
    • DELETE: Delete the specified resource.
    • TRACE, OPTIONS, CONNECT, PATCH: These verbs are for less common/advanced tasks, so we won't cover them here.
  • Additional information can be encoded with the request (for example, HTML form data). Information can be encoded as:

    • URL parameters: GET requests encode data in the URL sent to the server by adding name/value pairs onto the end of it — for example http://example.com?name=Fred&age=11. You always have a question mark (?) separating the rest of the URL from the URL parameters, an equals sign (=) separating each name from its associated value, and an ampersand (&) separating each pair. URL parameters are inherently "insecure" as they can be changed by users and then resubmitted. As a result URL parameters/GET requests are not used for requests that update data on the server.
    • POST data. POST requests add new resources, the data for which is encoded within the request body.
    • Client-side cookies. Cookies contain session data about the client, including keys that the server can use to determine their login status and permissions/accesses to resources.

Web servers wait for client request messages, process them when they arrive, and reply to the web browser with an HTTP response message. The response contains an HTTP Response status code indicating whether or not the request succeeded (e.g., 200 OK for success, 404 Not Found if the resource cannot be found, 403 Forbidden if the user isn't authorized to see the resource, etc.). The body of the response to a successful GET request contains the requested resource.

When an HTML page is returned, it is rendered by the web browser. As part of processing, the browser may discover links to other resources (e.g., an HTML page usually references JavaScript and CSS files), and will send separate HTTP Requests to download these files.

Both static and dynamic websites (discussed in the following sections) use exactly the same communication protocol/patterns.

GET request/response example

You can make a simple GET request by clicking on a link or searching on a site (like a search engine homepage). For example, the HTTP request that is sent when you perform a search on MDN for the term "client-server overview" will look a lot like the text shown below (it will not be identical because parts of the message depend on your browser/setup).

Note: The format of HTTP messages is defined in a "web standard" (RFC9110). You don't need to know this level of detail, but at least now you know where this all came from!

The request

Each line of the request contains information about it. The first part is called the header, and contains useful information about the request, in the same way that an HTML head contains useful information about an HTML document (but not the actual content itself, which is in the body):

http
GET /en-US/search?q=client+server+overview&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=webdev HTTP/1.1
Host: developer.mozilla.org
Connection: keep-alive
Pragma: no-cache
Cache-Control: no-cache
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: https://developer.mozilla.org/en-US/
Accept-Encoding: gzip, deflate, sdch, br
Accept-Language: en-US,en;q=0.8,es;q=0.6
Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; csrftoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT; dwf_section_edit=False; dwf_sg_task_completion=False; _gat=1; _ga=GA1.2.1688886003.1471911953; ffo=true

The first and second lines contain most of the information we talked about above:

  • The type of request (GET).
  • The target resource URL (/en-US/search).
  • The URL parameters (q=client%2Bserver%2Boverview&topic=apps&topic=html&topic=css&topic=js&topic=api&topic=webdev).
  • The target/host website (developer.mozilla.org).
  • The end of the first line also includes a short string identifying the specific protocol version (HTTP/1.1).

The final line contains information about the client-side cookies — you can see in this case the cookie includes an id for managing sessions (Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; …).

The remaining lines contain information about the browser used and the sort of responses it can handle. For example, you can see here that:

  • My browser (User-Agent) is Mozilla Firefox (Mozilla/5.0).
  • It can accept gzip compressed information (Accept-Encoding: gzip).
  • It can accept the specified languages (Accept-Language: en-US,en;q=0.8,es;q=0.6).
  • The Referer line indicates the address of the web page that contained the link to this resource (i.e., the origin of the request, https://developer.mozilla.org/en-US/).

HTTP requests can also have a body, but it is empty in this case.

The response

The first part of the response for this request is shown below. The header contains information like the following:

  • The first line includes the response code 200 OK, which tells us that the request succeeded.
  • We can see that the response is text/html formatted (Content-Type).
  • We can also see that it uses the UTF-8 character set (Content-Type: text/html; charset=utf-8).
  • The head also tells us how big it is (Content-Length: 41823).

At the end of the message we see the body content — which contains the actual HTML returned by the request.

http
HTTP/1.1 200 OK
Server: Apache
X-Backend-Server: developer1.webapp.scl3.mozilla.com
Vary: Accept, Cookie, Accept-Encoding
Content-Type: text/html; charset=utf-8
Date: Wed, 07 Sep 2016 00:11:31 GMT
Keep-Alive: timeout=5, max=999
Connection: Keep-Alive
X-Frame-Options: DENY
Allow: GET
X-Cache-Info: caching
Content-Length: 41823

<!doctype html>
<html lang="en-US" dir="ltr" class="redesign no-js" data-ffo-opensanslight=false data-ffo-opensans=false >
<head prefix="og: http://ogp.me/ns#">
  <meta charset="utf-8">
  <meta http-equiv="X-UA-Compatible" content="IE=Edge">
  <script>(function(d) { d.className = d.className.replace(/\bno-js/, ''); })(document.documentElement);</script>
  …

The remainder of the response header includes information about the response (e.g., when it was generated), the server, and how it expects the browser to handle the page (e.g., the X-Frame-Options: DENY line tells the browser not to allow this page to be embedded in an <iframe> in another site).

POST request/response example

An HTTP POST is made when you submit a form containing information to be saved on the server.

The request

The text below shows the HTTP request made when a user submits new profile details on this site. The format of the request is almost the same as the GET request example shown previously, though the first line identifies this request as a POST.

http
POST /en-US/profiles/hamishwillee/edit HTTP/1.1
Host: developer.mozilla.org
Connection: keep-alive
Content-Length: 432
Pragma: no-cache
Cache-Control: no-cache
Origin: https://developer.mozilla.org
Upgrade-Insecure-Requests: 1
User-Agent: Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/52.0.2743.116 Safari/537.36
Content-Type: application/x-www-form-urlencoded
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8
Referer: https://developer.mozilla.org/en-US/profiles/hamishwillee/edit
Accept-Encoding: gzip, deflate, br
Accept-Language: en-US,en;q=0.8,es;q=0.6
Cookie: sessionid=6ynxs23n521lu21b1t136rhbv7ezngie; _gat=1; csrftoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT; dwf_section_edit=False; dwf_sg_task_completion=False; _ga=GA1.2.1688886003.1471911953; ffo=true

csrfmiddlewaretoken=zIPUJsAZv6pcgCBJSCj1zU6pQZbfMUAT&user-username=hamishwillee&user-fullname=Hamish+Willee&user-title=&user-organization=&user-location=Australia&user-locale=en-US&user-timezone=Australia%2FMelbourne&user-irc_nickname=&user-interests=&user-expertise=&user-twitter_url=&user-stackoverflow_url=&user-linkedin_url=&user-mozillians_url=&user-facebook_url=

The main difference is that the URL doesn't have any parameters. As you can see, the information from the form is encoded in the body of the request (for example, the new user fullname is set using: &user-fullname=Hamish+Willee).

The response

The response from the request is shown below. The status code of 302 Found tells the browser that the post succeeded, and that it must issue a second HTTP request to load the page specified in the Location field. The information is otherwise similar to that for the response to a GET request.

http
HTTP/1.1 302 FOUND
Server: Apache
X-Backend-Server: developer3.webapp.scl3.mozilla.com
Vary: Cookie
Vary: Accept-Encoding
Content-Type: text/html; charset=utf-8
Date: Wed, 07 Sep 2016 00:38:13 GMT
Location: https://developer.mozilla.org/en-US/profiles/hamishwillee
Keep-Alive: timeout=5, max=1000
Connection: Keep-Alive
X-Frame-Options: DENY
X-Cache-Info: not cacheable; request wasn't a GET or HEAD
Content-Length: 0

Note: The HTTP responses and requests shown in these examples were captured using the Fiddler application, but you can get similar information using web sniffers (e.g., WebSniffer) or packet analyzers like Wireshark. You can try this yourself. Use any of the linked tools, and then navigate through a site and edit profile information to see the different requests and responses. Most modern browsers also have tools that monitor network requests (for example, the Network Monitor tool in Firefox).

Static sites

A static site is one that returns the same hardcoded content from the server whenever a particular resource is requested. So for example if you have a page about a product at /static/my-product1.html, this same page will be returned to every user. If you add another similar product to your site you will need to add another page (e.g., my-product2.html) and so on. This can start to get really inefficient — what happens when you get to thousands of product pages? You would repeat a lot of code across each page (the basic page template, structure, etc.), and if you wanted to change anything about the page structure — like add a new "related products" section for example — then you'd have to change every page individually.

Note: Static sites are excellent when you have a small number of pages and you want to send the same content to every user. However they can have a significant cost to maintain as the number of pages becomes larger.

Let's recap on how this works, by looking again at the static site architecture diagram we looked at in the last article.

A simplified diagram of a static web server.

When a user wants to navigate to a page, the browser sends an HTTP GET request specifying the URL of its HTML page. The server retrieves the requested document from its file system and returns an HTTP response containing the document and an HTTP Response status code of 200 OK (indicating success). The server might return a different status code, for example 404 Not Found if the file is not present on the server, or 301 Moved Permanently if the file exists but has been redirected to a different location.

The server for a static site will only ever need to process GET requests, because the server doesn't store any modifiable data. It also doesn't change its responses based on HTTP Request data (e.g., URL parameters or cookies).

Understanding how static sites work is nevertheless useful when learning server-side programming, because dynamic sites handle requests for static files (CSS, JavaScript, static images, etc.) in exactly the same way.

Dynamic sites

A dynamic site is one that can generate and return content based on the specific request URL and data (rather than always returning the same hardcoded file for a particular URL). Using the example of a product site, the server would store product "data" in a database rather than individual HTML files. When receiving an HTTP GET Request for a product, the server determines the product ID, fetches the data from the database, and then constructs the HTML page for the response by inserting the data into an HTML template. This has major advantages over a static site:

Using a database allows the product information to be stored efficiently in an easily extensible, modifiable, and searchable way.

Using HTML templates makes it very easy to change the HTML structure, because this only needs to be done in one place, in a single template, and not across potentially thousands of static pages.

Anatomy of a dynamic request

This section provides a step-by-step overview of the "dynamic" HTTP request and response cycle, building on what we looked at in the last article with much more detail. In order to "keep things real" we'll use the context of a sports-team manager website where a coach can select their team name and team size in an HTML form and get back a suggested "best lineup" for their next game.

The diagram below shows the main elements of the "team coach" website, along with numbered labels for the sequence of operations when the coach accesses their "best team" list. The parts of the site that make it dynamic are the Web Application (this is how we will refer to the server-side code that processes HTTP requests and returns HTTP responses), the Database, which contains information about players, teams, coaches and their relationships, and the HTML Templates.

This is a diagram of a simple web server with step numbers for each of step of the client-server interaction.

After the coach submits the form with the team name and number of players, the sequence of operations is:

  1. The web browser creates an HTTP GET request to the server using the base URL for the resource (/best) and encoding the team and player number either as URL parameters (e.g., /best?team=my_team_name&show=11) or as part of the URL pattern (e.g., /best/my_team_name/11/). A GET request is used because the request is only fetching data (not modifying data).
  2. The Web Server detects that the request is "dynamic" and forwards it to the Web Application for processing (the web server determines how to handle different URLs based on pattern matching rules defined in its configuration).
  3. The Web Application identifies that the intention of the request is to get the "best team list" based on the URL (/best/) and finds out the required team name and number of players from the URL. The Web Application then gets the required information from the database (using additional "internal" parameters to define which players are "best", and possibly also getting the identity of the logged in coach from a client-side cookie).
  4. The Web Application dynamically creates an HTML page by putting the data (from the Database) into placeholders inside an HTML template.
  5. The Web Application returns the generated HTML to the web browser (via the Web Server), along with an HTTP status code of 200 ("success"). If anything prevents the HTML from being returned then the Web Application will return another code — for example "404" to indicate that the team does not exist.
  6. The Web Browser will then start to process the returned HTML, sending separate requests to get any other CSS or JavaScript files that it references (see step 7).
  7. The Web Server loads static files from the file system and returns them to the browser directly (again, correct file handling is based on configuration rules and URL pattern matching).

An operation to update a record in the database would be handled similarly, except that like any database update, the HTTP request from the browser should be encoded as a POST request.

Doing other work

A Web Application's job is to receive HTTP requests and return HTTP responses. While interacting with a database to get or update information are very common tasks, the code may do other things at the same time, or not interact with a database at all.

A good example of an additional task that a Web Application might perform would be sending an email to users to confirm their registration with the site. The site might also perform logging or other operations.

Returning something other than HTML

Server-side website code does not have to return HTML snippets/files in the response. It can instead dynamically create and return other types of files (text, PDF, CSV, etc.) or even data (JSON, XML, etc.).

This is especially relevant for websites that work by fetching content from the server using JavaScript and updating the page dynamically, rather than always loading a new page when new content is to be shown. See Making network requests with JavaScript for more on the motivation for this approach, and what this model looks like from the client's point of view.

Web frameworks simplify server-side web programming

Server-side web frameworks make writing code to handle the operations described above much easier.

One of the most important operations they perform is providing simple mechanisms to map URLs for different resources/pages to specific handler functions. This makes it easier to keep the code associated with each type of resource separate. It also has benefits in terms of maintenance, because you can change the URL used to deliver a particular feature in one place, without having to change the handler function.

For example, consider the following Django (Python) code that maps two URL patterns to two view functions. The first pattern ensures that an HTTP request with a resource URL of /best will be passed to a function named index() in the views module. A request that has the pattern /best/junior, will instead be passed to the junior() view function.

python
# file: best/urls.py
#

from django.conf.urls import url

from . import views

urlpatterns = [
    # example: /best/
    url(r'^$', views.index),
    # example: /best/junior/
    url(r'^junior/$', views.junior),
]

Note: The first parameters in the url() functions may look a bit odd (e.g., r'^junior/$') because they use a pattern matching technique called "regular expressions" (RegEx, or RE). You don't need to know how regular expressions work at this point, other than that they allow us to match patterns in the URL (rather than the hardcoded values above) and use them as parameters in our view functions. As an example, a really simple RegEx might say "match a single uppercase letter, followed by between 4 and 7 lower case letters."

The web framework also makes it easy for a view function to fetch information from the database. The structure of our data is defined in models, which are Python classes that define the fields to be stored in the underlying database. If we have a model named Team with a field of "team_type" then we can use a simple query syntax to get back all teams that have a particular type.

The example below gets a list of all teams that have the exact (case sensitive) team_type of "junior" — note the format: field name (team_type) followed by double underscore, and then the type of match to use (in this case exact). There are many other types of matches and we can daisy chain them. We can also control the order and the number of results returned.

python
#best/views.py

from django.shortcuts import render

from .models import Team

def junior(request):
    list_teams = Team.objects.filter(team_type__exact="junior")
    context = {'list': list_teams}
    return render(request, 'best/index.html', context)

After the junior() function gets the list of junior teams, it calls the render() function, passing the original HttpRequest, an HTML template, and a "context" object defining the information to be included in the template. The render() function is a convenience function that generates HTML using a context and an HTML template, and returns it in an HttpResponse object.

Obviously web frameworks can help you with a lot of other tasks. We discuss a lot more benefits and some popular web framework choices in the next article.

Summary

At this point you should have a good overview of the operations that server-side code has to perform, and know some of the ways in which a server-side web framework can make this easier.

In a following module we'll help you choose the best Web Framework for your first site.

2.6. Probability and Statistics Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

2.6. Probability and Statistics
Open the notebook in SageMaker Studio Lab

One way or another, machine learning is all about uncertainty. In supervised learning, we want to predict something unknown (the target) given something known (the features). Depending on our objective, we might attempt to predict the most likely value of the target. Or we might predict the value with the smallest expected distance from the target. And sometimes we wish not only to predict a specific value but to quantify our uncertainty. For example, given some features describing a patient, we might want to know how likely they are to suffer a heart attack in the next year. In unsupervised learning, we often care about uncertainty. To determine whether a set of measurements are anomalous, it helps to know how likely one is to observe values in a population of interest. Furthermore, in reinforcement learning, we wish to develop agents that act intelligently in various environments. This requires reasoning about how an environment might be expected to change and what rewards one might expect to encounter in response to each of the available actions.

Probability is the mathematical field concerned with reasoning under uncertainty. Given a probabilistic model of some process, we can reason about the likelihood of various events. The use of probabilities to describe the frequencies of repeatable events (like coin tosses) is fairly uncontroversial. In fact, frequentist scholars adhere to an interpretation of probability that applies only to such repeatable events. By contrast Bayesian scholars use the language of probability more broadly to formalize reasoning under uncertainty. Bayesian probability is characterized by two unique features: (i) assigning degrees of belief to non-repeatable events, e.g., what is the probability that a dam will collapse?; and (ii) subjectivity. While Bayesian probability provides unambiguous rules for how one should update their beliefs in light of new evidence, it allows for different individuals to start off with different prior beliefs. Statistics helps us to reason backwards, starting off with collection and organization of data and backing out to what inferences we might draw about the process that generated the data. Whenever we analyze a dataset, hunting for patterns that we hope might characterize a broader population, we are employing statistical thinking. Many courses, majors, theses, careers, departments, companies, and institutions have been devoted to the study of probability and statistics. While this section only scratches the surface, we will provide the foundation that you need to begin building models.

%matplotlib inline
import random
import torch
from torch.distributions.multinomial import Multinomial
from d2l import torch as d2l

2.6.1. A Simple Example: Tossing Coins

Imagine that we plan to toss a coin and want to quantify how likely we are to see heads (vs. tails). If the coin is fair, then both outcomes (heads and tails), are equally likely. Moreover if we plan to toss the coin \(n\) times then the fraction of heads that we expect to see should exactly match the expected fraction of tails. One intuitive way to see this is by symmetry: for every possible outcome with \(n_\textrm{h}\) heads and \(n_\textrm{t} = (n - n_\textrm{h})\) tails, there is an equally likely outcome with \(n_\textrm{t}\) heads and \(n_\textrm{h}\) tails. Note that this is only possible if on average we expect to see \(1/2\) of tosses come up heads and \(1/2\) come up tails. Of course, if you conduct this experiment many times with \(n=1000000\) tosses each, you might never see a trial where \(n_\textrm{h} = n_\textrm{t}\) exactly.

Formally, the quantity \(1/2\) is called a probability and here it captures the certainty with which any given toss will come up heads. Probabilities assign scores between \(0\) and \(1\) to outcomes of interest, called events. Here the event of interest is \(\textrm{heads}\) and we denote the corresponding probability \(P(\textrm{heads})\). A probability of \(1\) indicates absolute certainty (imagine a trick coin where both sides were heads) and a probability of \(0\) indicates impossibility (e.g., if both sides were tails). The frequencies \(n_\textrm{h}/n\) and \(n_\textrm{t}/n\) are not probabilities but rather statistics. Probabilities are theoretical quantities that underly the data generating process. Here, the probability \(1/2\) is a property of the coin itself. By contrast, statistics are empirical quantities that are computed as functions of the observed data. Our interests in probabilistic and statistical quantities are inextricably intertwined. We often design special statistics called estimators that, given a dataset, produce estimates of model parameters such as probabilities. Moreover, when those estimators satisfy a nice property called consistency, our estimates will converge to the corresponding probability. In turn, these inferred probabilities tell about the likely statistical properties of data from the same population that we might encounter in the future.

Suppose that we stumbled upon a real coin for which we did not know the true \(P(\textrm{heads})\). To investigate this quantity with statistical methods, we need to (i) collect some data; and (ii) design an estimator. Data acquisition here is easy; we can toss the coin many times and record all the outcomes. Formally, drawing realizations from some underlying random process is called sampling. As you might have guessed, one natural estimator is the ratio of the number of observed heads to the total number of tosses.

Now, suppose that the coin was in fact fair, i.e., \(P(\textrm{heads}) = 0.5\). To simulate tosses of a fair coin, we can invoke any random number generator. There are some easy ways to draw samples of an event with probability \(0.5\). For example Python’s random.random yields numbers in the interval \([0,1]\) where the probability of lying in any sub-interval \([a, b] \subset [0,1]\) is equal to \(b-a\). Thus we can get out 0 and 1 with probability 0.5 each by testing whether the returned float number is greater than 0.5:

num_tosses = 100
heads = sum([random.random() > 0.5 for _ in range(num_tosses)])
tails = num_tosses - heads
print("heads, tails: ", [heads, tails])
heads, tails:  [44, 56]

More generally, we can simulate multiple draws from any variable with a finite number of possible outcomes (like the toss of a coin or roll of a die) by calling the multinomial function, setting the first argument to the number of draws and the second as a list of probabilities associated with each of the possible outcomes. To simulate ten tosses of a fair coin, we assign probability vector [0.5, 0.5], interpreting index 0 as heads and index 1 as tails. The function returns a vector with length equal to the number of possible outcomes (here, 2), where the first component tells us the number of occurrences of heads and the second component tells us the number of occurrences of tails.

fair_probs = torch.tensor([0.5, 0.5])
Multinomial(100, fair_probs).sample()
tensor([50., 50.])

Each time you run this sampling process, you will receive a new random value that may differ from the previous outcome. Dividing by the number of tosses gives us the frequency of each outcome in our data. Note that these frequencies, just like the probabilities that they are intended to estimate, sum to \(1\).

Multinomial(100, fair_probs).sample() / 100
tensor([0.4800, 0.5200])

Here, even though our simulated coin is fair (we ourselves set the probabilities [0.5, 0.5]), the counts of heads and tails may not be identical. That is because we only drew a relatively small number of samples. If we did not implement the simulation ourselves, and only saw the outcome, how would we know if the coin were slightly unfair or if the possible deviation from \(1/2\) was just an artifact of the small sample size? Let’s see what happens when we simulate 10,000 tosses.

counts = Multinomial(10000, fair_probs).sample()
counts / 10000
tensor([0.4966, 0.5034])

In general, for averages of repeated events (like coin tosses), as the number of repetitions grows, our estimates are guaranteed to converge to the true underlying probabilities. The mathematical formulation of this phenomenon is called the law of large numbers and the central limit theorem tells us that in many situations, as the sample size \(n\) grows, these errors should go down at a rate of \((1/\sqrt{n})\). Let’s get some more intuition by studying how our estimate evolves as we grow the number of tosses from 1 to 10,000.

counts = Multinomial(1, fair_probs).sample((10000,))
cum_counts = counts.cumsum(dim=0)
estimates = cum_counts / cum_counts.sum(dim=1, keepdims=True)
estimates = estimates.numpy()

d2l.set_figsize((4.5, 3.5))
d2l.plt.plot(estimates[:, 0], label=("P(coin=heads)"))
d2l.plt.plot(estimates[:, 1], label=("P(coin=tails)"))
d2l.plt.axhline(y=0.5, color='black', linestyle='dashed')
d2l.plt.gca().set_xlabel('Samples')
d2l.plt.gca().set_ylabel('Estimated probability')
d2l.plt.legend();
../_images/output_probability_245b7d_78_0.svg

Each solid curve corresponds to one of the two values of the coin and gives our estimated probability that the coin turns up that value after each group of experiments. The dashed black line gives the true underlying probability. As we get more data by conducting more experiments, the curves converge towards the true probability. You might already begin to see the shape of some of the more advanced questions that preoccupy statisticians: How quickly does this convergence happen? If we had already tested many coins manufactured at the same plant, how might we incorporate this information?

2.6.2. A More Formal Treatment

We have already gotten pretty far: posing a probabilistic model, generating synthetic data, running a statistical estimator, empirically assessing convergence, and reporting error metrics (checking the deviation). However, to go much further, we will need to be more precise.

When dealing with randomness, we denote the set of possible outcomes \(\mathcal{S}\) and call it the sample space or outcome space. Here, each element is a distinct possible outcome. In the case of rolling a single coin, \(\mathcal{S} = \{\textrm{heads}, \textrm{tails}\}\). For a single die, \(\mathcal{S} = \{1, 2, 3, 4, 5, 6\}\). When flipping two coins, possible outcomes are \(\{(\textrm{heads}, \textrm{heads}), (\textrm{heads}, \textrm{tails}), (\textrm{tails}, \textrm{heads}), (\textrm{tails}, \textrm{tails})\}\). Events are subsets of the sample space. For instance, the event “the first coin toss comes up heads” corresponds to the set \(\{(\textrm{heads}, \textrm{heads}), (\textrm{heads}, \textrm{tails})\}\). Whenever the outcome \(z\) of a random experiment satisfies \(z \in \mathcal{A}\), then event \(\mathcal{A}\) has occurred. For a single roll of a die, we could define the events “seeing a \(5\)” (\(\mathcal{A} = \{5\}\)) and “seeing an odd number” (\(\mathcal{B} = \{1, 3, 5\}\)). In this case, if the die came up \(5\), we would say that both \(\mathcal{A}\) and \(\mathcal{B}\) occurred. On the other hand, if \(z = 3\), then \(\mathcal{A}\) did not occur but \(\mathcal{B}\) did.

A probability function maps events onto real values \({P: \mathcal{A} \subseteq \mathcal{S} \rightarrow [0,1]}\). The probability, denoted \(P(\mathcal{A})\), of an event \(\mathcal{A}\) in the given sample space \(\mathcal{S}\), has the following properties:

  • The probability of any event \(\mathcal{A}\) is a nonnegative real number, i.e., \(P(\mathcal{A}) \geq 0\);

  • The probability of the entire sample space is \(1\), i.e., \(P(\mathcal{S}) = 1\);

  • For any countable sequence of events \(\mathcal{A}_1, \mathcal{A}_2, \ldots\) that are mutually exclusive (i.e., \(\mathcal{A}_i \cap \mathcal{A}_j = \emptyset\) for all \(i \neq j\)), the probability that any of them happens is equal to the sum of their individual probabilities, i.e., \(P(\bigcup_{i=1}^{\infty} \mathcal{A}_i) = \sum_{i=1}^{\infty} P(\mathcal{A}_i)\).

These axioms of probability theory, proposed by Kolmogorov (1933), can be applied to rapidly derive a number of important consequences. For instance, it follows immediately that the probability of any event \(\mathcal{A}\) or its complement \(\mathcal{A}'\) occurring is 1 (because \(\mathcal{A} \cup \mathcal{A}' = \mathcal{S}\)). We can also prove that \(P(\emptyset) = 0\) because \(1 = P(\mathcal{S} \cup \mathcal{S}') = P(\mathcal{S} \cup \emptyset) = P(\mathcal{S}) + P(\emptyset) = 1 + P(\emptyset)\). Consequently, the probability of any event \(\mathcal{A}\) and its complement \(\mathcal{A}'\) occurring simultaneously is \(P(\mathcal{A} \cap \mathcal{A}') = 0\). Informally, this tells us that impossible events have zero probability of occurring.

2.6.3. Random Variables

When we spoke about events like the roll of a die coming up odds or the first coin toss coming up heads, we were invoking the idea of a random variable. Formally, random variables are mappings from an underlying sample space to a set of (possibly many) values. You might wonder how a random variable is different from the sample space, since both are collections of outcomes. Importantly, random variables can be much coarser than the raw sample space. We can define a binary random variable like “greater than 0.5” even when the underlying sample space is infinite, e.g., points on the line segment between \(0\) and \(1\). Additionally, multiple random variables can share the same underlying sample space. For example “whether my home alarm goes off” and “whether my house was burgled” are both binary random variables that share an underlying sample space. Consequently, knowing the value taken by one random variable can tell us something about the likely value of another random variable. Knowing that the alarm went off, we might suspect that the house was likely burgled.

Every value taken by a random variable corresponds to a subset of the underlying sample space. Thus the occurrence where the random variable \(X\) takes value \(v\), denoted by \(X=v\), is an event and \(P(X=v)\) denotes its probability. Sometimes this notation can get clunky, and we can abuse notation when the context is clear. For example, we might use \(P(X)\) to refer broadly to the distribution of \(X\), i.e., the function that tells us the probability that \(X\) takes any given value. Other times we write expressions like \(P(X,Y) = P(X) P(Y)\), as a shorthand to express a statement that is true for all of the values that the random variables \(X\) and \(Y\) can take, i.e., for all \(i,j\) it holds that \(P(X=i \textrm{ and } Y=j) = P(X=i)P(Y=j)\). Other times, we abuse notation by writing \(P(v)\) when the random variable is clear from the context. Since an event in probability theory is a set of outcomes from the sample space, we can specify a range of values for a random variable to take. For example, \(P(1 \leq X \leq 3)\) denotes the probability of the event \(\{1 \leq X \leq 3\}\).

Note that there is a subtle difference between discrete random variables, like flips of a coin or tosses of a die, and continuous ones, like the weight and the height of a person sampled at random from the population. In this case we seldom really care about someone’s exact height. Moreover, if we took precise enough measurements, we would find that no two people on the planet have the exact same height. In fact, with fine enough measurements, you would never have the same height when you wake up and when you go to sleep. There is little point in asking about the exact probability that someone is 1.801392782910287192 meters tall. Instead, we typically care more about being able to say whether someone’s height falls into a given interval, say between 1.79 and 1.81 meters. In these cases we work with probability densities. The height of exactly 1.80 meters has no probability, but nonzero density. To work out the probability assigned to an interval, we must take an integral of the density over that interval.

2.6.4. Multiple Random Variables

You might have noticed that we could not even make it through the previous section without making statements involving interactions among multiple random variables (recall \(P(X,Y) = P(X) P(Y)\)). Most of machine learning is concerned with such relationships. Here, the sample space would be the population of interest, say customers who transact with a business, photographs on the Internet, or proteins known to biologists. Each random variable would represent the (unknown) value of a different attribute. Whenever we sample an individual from the population, we observe a realization of each of the random variables. Because the values taken by random variables correspond to subsets of the sample space that could be overlapping, partially overlapping, or entirely disjoint, knowing the value taken by one random variable can cause us to update our beliefs about which values of another random variable are likely. If a patient walks into a hospital and we observe that they are having trouble breathing and have lost their sense of smell, then we believe that they are more likely to have COVID-19 than we might if they had no trouble breathing and a perfectly ordinary sense of smell.

When working with multiple random variables, we can construct events corresponding to every combination of values that the variables can jointly take. The probability function that assigns probabilities to each of these combinations (e.g. \(A=a\) and \(B=b\)) is called the joint probability function and simply returns the probability assigned to the intersection of the corresponding subsets of the sample space. The joint probability assigned to the event where random variables \(A\) and \(B\) take values \(a\) and \(b\), respectively, is denoted \(P(A = a, B = b)\), where the comma indicates “and”. Note that for any values \(a\) and \(b\), it follows that

(2.6.1)\[P(A=a, B=b) \leq P(A=a) \textrm{ and } P(A=a, B=b) \leq P(B = b),\]

since for \(A=a\) and \(B=b\) to happen, \(A=a\) has to happen and \(B=b\) also has to happen. Interestingly, the joint probability tells us all that we can know about these random variables in a probabilistic sense, and can be used to derive many other useful quantities, including recovering the individual distributions \(P(A)\) and \(P(B)\). To recover \(P(A=a)\) we simply sum up \(P(A=a, B=v)\) over all values \(v\) that the random variable \(B\) can take: \(P(A=a) = \sum_v P(A=a, B=v)\).

The ratio \(\frac{P(A=a, B=b)}{P(A=a)} \leq 1\) turns out to be extremely important. It is called the conditional probability, and is denoted via the “\(\mid\)” symbol:

(2.6.2)\[P(B=b \mid A=a) = P(A=a,B=b)/P(A=a).\]

It tells us the new probability associated with the event \(B=b\), once we condition on the fact \(A=a\) took place. We can think of this conditional probability as restricting attention only to the subset of the sample space associated with \(A=a\) and then renormalizing so that all probabilities sum to 1. Conditional probabilities are in fact just ordinary probabilities and thus respect all of the axioms, as long as we condition all terms on the same event and thus restrict attention to the same sample space. For instance, for disjoint events \(\mathcal{B}\) and \(\mathcal{B}'\), we have that \(P(\mathcal{B} \cup \mathcal{B}' \mid A = a) = P(\mathcal{B} \mid A = a) + P(\mathcal{B}' \mid A = a)\).

Using the definition of conditional probabilities, we can derive the famous result called Bayes’ theorem. By construction, we have that \(P(A, B) = P(B\mid A) P(A)\) and \(P(A, B) = P(A\mid B) P(B)\). Combining both equations yields \(P(B\mid A) P(A) = P(A\mid B) P(B)\) and hence

(2.6.3)\[P(A \mid B) = \frac{P(B\mid A) P(A)}{P(B)}.\]

This simple equation has profound implications because it allows us to reverse the order of conditioning. If we know how to estimate \(P(B\mid A)\), \(P(A)\), and \(P(B)\), then we can estimate \(P(A\mid B)\). We often find it easier to estimate one term directly but not the other and Bayes’ theorem can come to the rescue here. For instance, if we know the prevalence of symptoms for a given disease, and the overall prevalences of the disease and symptoms, respectively, we can determine how likely someone is to have the disease based on their symptoms. In some cases we might not have direct access to \(P(B)\), such as the prevalence of symptoms. In this case a simplified version of Bayes’ theorem comes in handy:

(2.6.4)\[P(A \mid B) \propto P(B \mid A) P(A).\]

Since we know that \(P(A \mid B)\) must be normalized to \(1\), i.e., \(\sum_a P(A=a \mid B) = 1\), we can use it to compute

(2.6.5)\[P(A \mid B) = \frac{P(B \mid A) P(A)}{\sum_a P(B \mid A=a) P(A = a)}.\]

In Bayesian statistics, we think of an observer as possessing some (subjective) prior beliefs about the plausibility of the available hypotheses encoded in the prior \(P(H)\), and a likelihood function that says how likely one is to observe any value of the collected evidence for each of the hypotheses in the class \(P(E \mid H)\). Bayes’ theorem is then interpreted as telling us how to update the initial prior \(P(H)\) in light of the available evidence \(E\) to produce posterior beliefs \(P(H \mid E) = \frac{P(E \mid H) P(H)}{P(E)}\). Informally, this can be stated as “posterior equals prior times likelihood, divided by the evidence”. Now, because the evidence \(P(E)\) is the same for all hypotheses, we can get away with simply normalizing over the hypotheses.

Note that \(\sum_a P(A=a \mid B) = 1\) also allows us to marginalize over random variables. That is, we can drop variables from a joint distribution such as \(P(A, B)\). After all, we have that

(2.6.6)\[\sum_a P(B \mid A=a) P(A=a) = \sum_a P(B, A=a) = P(B).\]

Independence is another fundamentally important concept that forms the backbone of many important ideas in statistics. In short, two variables are independent if conditioning on the value of \(A\) does not cause any change to the probability distribution associated with \(B\) and vice versa. More formally, independence, denoted \(A \perp B\), requires that \(P(A \mid B) = P(A)\) and, consequently, that \(P(A,B) = P(A \mid B) P(B) = P(A) P(B)\). Independence is often an appropriate assumption. For example, if the random variable \(A\) represents the outcome from tossing one fair coin and the random variable \(B\) represents the outcome from tossing another, then knowing whether \(A\) came up heads should not influence the probability of \(B\) coming up heads.

Independence is especially useful when it holds among the successive draws of our data from some underlying distribution (allowing us to make strong statistical conclusions) or when it holds among various variables in our data, allowing us to work with simpler models that encode this independence structure. On the other hand, estimating the dependencies among random variables is often the very aim of learning. We care to estimate the probability of disease given symptoms specifically because we believe that diseases and symptoms are not independent.

Note that because conditional probabilities are proper probabilities, the concepts of independence and dependence also apply to them. Two random variables \(A\) and \(B\) are conditionally independent given a third variable \(C\) if and only if \(P(A, B \mid C) = P(A \mid C)P(B \mid C)\). Interestingly, two variables can be independent in general but become dependent when conditioning on a third. This often occurs when the two random variables \(A\) and \(B\) correspond to causes of some third variable \(C\). For example, broken bones and lung cancer might be independent in the general population but if we condition on being in the hospital then we might find that broken bones are negatively correlated with lung cancer. That is because the broken bone explains away why some person is in the hospital and thus lowers the probability that they are hospitalized because of having lung cancer.

And conversely, two dependent random variables can become independent upon conditioning on a third. This often happens when two otherwise unrelated events have a common cause. Shoe size and reading level are highly correlated among elementary school students, but this correlation disappears if we condition on age.

2.6.5. An Example

Let’s put our skills to the test. Assume that a doctor administers an HIV test to a patient. This test is fairly accurate and fails only with 1% probability if the patient is healthy but reported as diseased, i.e., healthy patients test positive in 1% of cases. Moreover, it never fails to detect HIV if the patient actually has it. We use \(D_1 \in \{0, 1\}\) to indicate the diagnosis (\(0\) if negative and \(1\) if positive) and \(H \in \{0, 1\}\) to denote the HIV status.

Conditional probability

\(H=1\)

\(H=0\)

\(P(D_1 = 1 \mid H)\)

1

0.01

\(P(D_1 = 0 \mid H)\)

0

0.99

Note that the column sums are all 1 (but the row sums do not), since they are conditional probabilities. Let’s compute the probability of the patient having HIV if the test comes back positive, i.e., \(P(H = 1 \mid D_1 = 1)\). Intuitively this is going to depend on how common the disease is, since it affects the number of false alarms. Assume that the population is fairly free of the disease, e.g., \(P(H=1) = 0.0015\). To apply Bayes’ theorem, we need to apply marginalization to determine

(2.6.7)\[\begin{split}\begin{aligned} P(D_1 = 1) =& P(D_1=1, H=0) + P(D_1=1, H=1) \\ =& P(D_1=1 \mid H=0) P(H=0) + P(D_1=1 \mid H=1) P(H=1) \\ =& 0.011485. \end{aligned}\end{split}\]

This leads us to

(2.6.8)\[P(H = 1 \mid D_1 = 1) = \frac{P(D_1=1 \mid H=1) P(H=1)}{P(D_1=1)} = 0.1306.\]

In other words, there is only a 13.06% chance that the patient actually has HIV, despite the test being pretty accurate. As we can see, probability can be counterintuitive. What should a patient do upon receiving such terrifying news? Likely, the patient would ask the physician to administer another test to get clarity. The second test has different characteristics and it is not as good as the first one.

Conditional probability

\(H=1\)

\(H=0\)

\(P(D_2 = 1 \mid H)\)

0.98

0.03

\(P(D_2 = 0 \mid H)\)

0.02

0.97

Unfortunately, the second test comes back positive, too. Let’s calculate the requisite probabilities to invoke Bayes’ theorem by assuming conditional independence:

(2.6.9)\[\begin{split}\begin{aligned} P(D_1 = 1, D_2 = 1 \mid H = 0) & = P(D_1 = 1 \mid H = 0) P(D_2 = 1 \mid H = 0) =& 0.0003, \\ P(D_1 = 1, D_2 = 1 \mid H = 1) & = P(D_1 = 1 \mid H = 1) P(D_2 = 1 \mid H = 1) =& 0.98. \end{aligned}\end{split}\]

Now we can apply marginalization to obtain the probability that both tests come back positive:

(2.6.10)\[\begin{split}\begin{aligned} &P(D_1 = 1, D_2 = 1)\\ &= P(D_1 = 1, D_2 = 1, H = 0) + P(D_1 = 1, D_2 = 1, H = 1) \\ &= P(D_1 = 1, D_2 = 1 \mid H = 0)P(H=0) + P(D_1 = 1, D_2 = 1 \mid H = 1)P(H=1)\\ &= 0.00176955. \end{aligned}\end{split}\]

Finally, the probability of the patient having HIV given that both tests are positive is

(2.6.11)\[P(H = 1 \mid D_1 = 1, D_2 = 1) = \frac{P(D_1 = 1, D_2 = 1 \mid H=1) P(H=1)}{P(D_1 = 1, D_2 = 1)} = 0.8307.\]

That is, the second test allowed us to gain much higher confidence that not all is well. Despite the second test being considerably less accurate than the first one, it still significantly improved our estimate. The assumption of both tests being conditionally independent of each other was crucial for our ability to generate a more accurate estimate. Take the extreme case where we run the same test twice. In this situation we would expect the same outcome both times, hence no additional insight is gained from running the same test again. The astute reader might have noticed that the diagnosis behaved like a classifier hiding in plain sight where our ability to decide whether a patient is healthy increases as we obtain more features (test outcomes).

2.6.6. Expectations

Often, making decisions requires not just looking at the probabilities assigned to individual events but composing them together into useful aggregates that can provide us with guidance. For example, when random variables take continuous scalar values, we often care about knowing what value to expect on average. This quantity is formally called an expectation. If we are making investments, the first quantity of interest might be the return we can expect, averaging over all the possible outcomes (and weighting by the appropriate probabilities). For instance, say that with 50% probability, an investment might fail altogether, with 40% probability it might provide a 2\(\times\) return, and with 10% probability it might provide a 10\(\times\) return 10\(\times\). To calculate the expected return, we sum over all returns, multiplying each by the probability that they will occur. This yields the expectation \(0.5 \cdot 0 + 0.4 \cdot 2 + 0.1 \cdot 10 = 1.8\). Hence the expected return is 1.8\(\times\).

In general, the expectation (or average) of the random variable \(X\) is defined as

(2.6.12)\[E[X] = E_{x \sim P}[x] = \sum_{x} x P(X = x).\]

Likewise, for densities we obtain \(E[X] = \int x \;dp(x)\). Sometimes we are interested in the expected value of some function of \(x\). We can calculate these expectations as

(2.6.13)\[E_{x \sim P}[f(x)] = \sum_x f(x) P(x) \textrm{ and } E_{x \sim P}[f(x)] = \int f(x) p(x) \;dx\]

for discrete probabilities and densities, respectively. Returning to the investment example from above, \(f\) might be the utility (happiness) associated with the return. Behavior economists have long noted that people associate greater disutility with losing money than the utility gained from earning one dollar relative to their baseline. Moreover, the value of money tends to be sub-linear. Possessing 100k dollars versus zero dollars can make the difference between paying the rent, eating well, and enjoying quality healthcare versus suffering through homelessness. On the other hand, the gains due to possessing 200k versus 100k are less dramatic. Reasoning like this motivates the cliché that “the utility of money is logarithmic”.

If the utility associated with a total loss were \(-1\), and the utilities associated with returns of \(1\), \(2\), and \(10\) were \(1\), \(2\) and \(4\), respectively, then the expected happiness of investing would be \(0.5 \cdot (-1) + 0.4 \cdot 2 + 0.1 \cdot 4 = 0.7\) (an expected loss of utility of 30%). If indeed this were your utility function, you might be best off keeping the money in the bank.

For financial decisions, we might also want to measure how risky an investment is. Here, we care not just about the expected value but how much the actual values tend to vary relative to this value. Note that we cannot just take the expectation of the difference between the actual and expected values. This is because the expectation of a difference is the difference of the expectations, i.e., \(E[X - E[X]] = E[X] - E[E[X]] = 0\). However, we can look at the expectation of any non-negative function of this difference. The variance of a random variable is calculated by looking at the expected value of the squared differences:

(2.6.14)\[\textrm{Var}[X] = E\left[(X - E[X])^2\right] = E[X^2] - E[X]^2.\]

Here the equality follows by expanding \((X - E[X])^2 = X^2 - 2 X E[X] + E[X]^2\) and taking expectations for each term. The square root of the variance is another useful quantity called the standard deviation. While this and the variance convey the same information (either can be calculated from the other), the standard deviation has the nice property that it is expressed in the same units as the original quantity represented by the random variable.

Lastly, the variance of a function of a random variable is defined analogously as

(2.6.15)\[\textrm{Var}_{x \sim P}[f(x)] = E_{x \sim P}[f^2(x)] - E_{x \sim P}[f(x)]^2.\]

Returning to our investment example, we can now compute the variance of the investment. It is given by \(0.5 \cdot 0 + 0.4 \cdot 2^2 + 0.1 \cdot 10^2 - 1.8^2 = 8.36\). For all intents and purposes this is a risky investment. Note that by mathematical convention mean and variance are often referenced as \(\mu\) and \(\sigma^2\). This is particularly the case whenever we use it to parametrize a Gaussian distribution.

In the same way as we introduced expectations and variance for scalar random variables, we can do so for vector-valued ones. Expectations are easy, since we can apply them elementwise. For instance, \(\boldsymbol{\mu} \stackrel{\textrm{def}}{=} E_{\mathbf{x} \sim P}[\mathbf{x}]\) has coordinates \(\mu_i = E_{\mathbf{x} \sim P}[x_i]\). Covariances are more complicated. We define them by taking expectations of the outer product of the difference between random variables and their mean:

(2.6.16)\[\boldsymbol{\Sigma} \stackrel{\textrm{def}}{=} \textrm{Cov}_{\mathbf{x} \sim P}[\mathbf{x}] = E_{\mathbf{x} \sim P}\left[(\mathbf{x} - \boldsymbol{\mu}) (\mathbf{x} - \boldsymbol{\mu})^\top\right].\]

This matrix \(\boldsymbol{\Sigma}\) is referred to as the covariance matrix. An easy way to see its effect is to consider some vector \(\mathbf{v}\) of the same size as \(\mathbf{x}\). It follows that

(2.6.17)\[\mathbf{v}^\top \boldsymbol{\Sigma} \mathbf{v} = E_{\mathbf{x} \sim P}\left[\mathbf{v}^\top(\mathbf{x} - \boldsymbol{\mu}) (\mathbf{x} - \boldsymbol{\mu})^\top \mathbf{v}\right] = \textrm{Var}_{x \sim P}[\mathbf{v}^\top \mathbf{x}].\]

As such, \(\boldsymbol{\Sigma}\) allows us to compute the variance for any linear function of \(\mathbf{x}\) by a simple matrix multiplication. The off-diagonal elements tell us how correlated the coordinates are: a value of 0 means no correlation, where a larger positive value means that they are more strongly correlated.

2.6.7. Discussion

In machine learning, there are many things to be uncertain about! We can be uncertain about the value of a label given an input. We can be uncertain about the estimated value of a parameter. We can even be uncertain about whether data arriving at deployment is even from the same distribution as the training data.

By aleatoric uncertainty, we mean uncertainty that is intrinsic to the problem, and due to genuine randomness unaccounted for by the observed variables. By epistemic uncertainty, we mean uncertainty over a model’s parameters, the sort of uncertainty that we can hope to reduce by collecting more data. We might have epistemic uncertainty concerning the probability that a coin turns up heads, but even once we know this probability, we are left with aleatoric uncertainty about the outcome of any future toss. No matter how long we watch someone tossing a fair coin, we will never be more or less than 50% certain that the next toss will come up heads. These terms come from mechanical modeling, (see e.g., Der Kiureghian and Ditlevsen (2009) for a review on this aspect of uncertainty quantification). It is worth noting, however, that these terms constitute a slight abuse of language. The term epistemic refers to anything concerning knowledge and thus, in the philosophical sense, all uncertainty is epistemic.

We saw that sampling data from some unknown probability distribution can provide us with information that can be used to estimate the parameters of the data generating distribution. That said, the rate at which this is possible can be quite slow. In our coin tossing example (and many others) we can do no better than to design estimators that converge at a rate of \(1/\sqrt{n}\), where \(n\) is the sample size (e.g., the number of tosses). This means that by going from 10 to 1000 observations (usually a very achievable task) we see a tenfold reduction of uncertainty, whereas the next 1000 observations help comparatively little, offering only a 1.41 times reduction. This is a persistent feature of machine learning: while there are often easy gains, it takes a very large amount of data, and often with it an enormous amount of computation, to make further gains. For an empirical review of this fact for large scale language models see Revels et al. (2016).

We also sharpened our language and tools for statistical modeling. In the process of that we learned about conditional probabilities and about one of the most important equations in statistics—Bayes’ theorem. It is an effective tool for decoupling information conveyed by data through a likelihood term \(P(B \mid A)\) that addresses how well observations \(B\) match a choice of parameters \(A\), and a prior probability \(P(A)\) which governs how plausible a particular choice of \(A\) was in the first place. In particular, we saw how this rule can be applied to assign probabilities to diagnoses, based on the efficacy of the test and the prevalence of the disease itself (i.e., our prior).

Lastly, we introduced a first set of nontrivial questions about the effect of a specific probability distribution, namely expectations and variances. While there are many more than just linear and quadratic expectations for a probability distribution, these two already provide a good deal of knowledge about the possible behavior of the distribution. For instance, Chebyshev’s inequality states that \(P(|X - \mu| \geq k \sigma) \leq 1/k^2\), where \(\mu\) is the expectation, \(\sigma^2\) is the variance of the distribution, and \(k > 1\) is a confidence parameter of our choosing. It tells us that draws from a distribution lie with at least 50% probability within a \([-\sqrt{2} \sigma, \sqrt{2} \sigma]\) interval centered on the expectation.

2.6.8. Exercises

  1. Give an example where observing more data can reduce the amount of uncertainty about the outcome to an arbitrarily low level.

  2. Give an example where observing more data will only reduce the amount of uncertainty up to a point and then no further. Explain why this is the case and where you expect this point to occur.

  3. We empirically demonstrated convergence to the mean for the toss of a coin. Calculate the variance of the estimate of the probability that we see a head after drawing \(n\) samples.

    1. How does the variance scale with the number of observations?

    2. Use Chebyshev’s inequality to bound the deviation from the expectation.

    3. How does it relate to the central limit theorem?

  4. Assume that we draw \(m\) samples \(x_i\) from a probability distribution with zero mean and unit variance. Compute the averages \(z_m \stackrel{\textrm{def}}{=} m^{-1} \sum_{i=1}^m x_i\). Can we apply Chebyshev’s inequality for every \(z_m\) independently? Why not?

  5. Given two events with probability \(P(\mathcal{A})\) and \(P(\mathcal{B})\), compute upper and lower bounds on \(P(\mathcal{A} \cup \mathcal{B})\) and \(P(\mathcal{A} \cap \mathcal{B})\). Hint: graph the situation using a Venn diagram.

  6. Assume that we have a sequence of random variables, say \(A\), \(B\), and \(C\), where \(B\) only depends on \(A\), and \(C\) only depends on \(B\), can you simplify the joint probability \(P(A, B, C)\)? Hint: this is a Markov chain.

  7. In Section 2.6.5, assume that the outcomes of the two tests are not independent. In particular assume that either test on its own has a false positive rate of 10% and a false negative rate of 1%. That is, assume that \(P(D =1 \mid H=0) = 0.1\) and that \(P(D = 0 \mid H=1) = 0.01\). Moreover, assume that for \(H = 1\) (infected) the test outcomes are conditionally independent, i.e., that \(P(D_1, D_2 \mid H=1) = P(D_1 \mid H=1) P(D_2 \mid H=1)\) but that for healthy patients the outcomes are coupled via \(P(D_1 = D_2 = 1 \mid H=0) = 0.02\).

    1. Work out the joint probability table for \(D_1\) and \(D_2\), given \(H=0\) based on the information you have so far.

    2. Derive the probability that the patient is diseased (\(H=1\)) after one test returns positive. You can assume the same baseline probability \(P(H=1) = 0.0015\) as before.

    3. Derive the probability that the patient is diseased (\(H=1\)) after both tests return positive.

  8. Assume that you are an asset manager for an investment bank and you have a choice of stocks \(s_i\) to invest in. Your portfolio needs to add up to \(1\) with weights \(\alpha_i\) for each stock. The stocks have an average return \(\boldsymbol{\mu} = E_{\mathbf{s} \sim P}[\mathbf{s}]\) and covariance \(\boldsymbol{\Sigma} = \textrm{Cov}_{\mathbf{s} \sim P}[\mathbf{s}]\).

    1. Compute the expected return for a given portfolio \(\boldsymbol{\alpha}\).

    2. If you wanted to maximize the return of the portfolio, how should you choose your investment?

    3. Compute the variance of the portfolio.

    4. Formulate an optimization problem of maximizing the return while keeping the variance constrained to an upper bound. This is the Nobel-Prize winning Markovitz portfolio (Mangram, 2013). To solve it you will need a quadratic programming solver, something way beyond the scope of this book.

3.6. Generalization Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

3.6. Generalization
Open the notebook in SageMaker Studio Lab

Consider two college students diligently preparing for their final exam. Commonly, this preparation will consist of practicing and testing their abilities by taking exams administered in previous years. Nonetheless, doing well on past exams is no guarantee that they will excel when it matters. For instance, imagine a student, Extraordinary Ellie, whose preparation consisted entirely of memorizing the answers to previous years’ exam questions. Even if Ellie were endowed with an extraordinary memory, and thus could perfectly recall the answer to any previously seen question, she might nevertheless freeze when faced with a new (previously unseen) question. By comparison, imagine another student, Inductive Irene, with comparably poor memorization skills, but a knack for picking up patterns. Note that if the exam truly consisted of recycled questions from a previous year, Ellie would handily outperform Irene. Even if Irene’s inferred patterns yielded 90% accurate predictions, they could never compete with Ellie’s 100% recall. However, even if the exam consisted entirely of fresh questions, Irene might maintain her 90% average.

As machine learning scientists, our goal is to discover patterns. But how can we be sure that we have truly discovered a general pattern and not simply memorized our data? Most of the time, our predictions are only useful if our model discovers such a pattern. We do not want to predict yesterday’s stock prices, but tomorrow’s. We do not need to recognize already diagnosed diseases for previously seen patients, but rather previously undiagnosed ailments in previously unseen patients. This problem—how to discover patterns that generalize—is the fundamental problem of machine learning, and arguably of all of statistics. We might cast this problem as just one slice of a far grander question that engulfs all of science: when are we ever justified in making the leap from particular observations to more general statements?

In real life, we must fit our models using a finite collection of data. The typical scales of that data vary wildly across domains. For many important medical problems, we can only access a few thousand data points. When studying rare diseases, we might be lucky to access hundreds. By contrast, the largest public datasets consisting of labeled photographs, e.g., ImageNet (Deng et al., 2009), contain millions of images. And some unlabeled image collections such as the Flickr YFC100M dataset can be even larger, containing over 100 million images (Thomee et al., 2016). However, even at this extreme scale, the number of available data points remains infinitesimally small compared to the space of all possible images at a megapixel resolution. Whenever we work with finite samples, we must keep in mind the risk that we might fit our training data, only to discover that we failed to discover a generalizable pattern.

The phenomenon of fitting closer to our training data than to the underlying distribution is called overfitting, and techniques for combatting overfitting are often called regularization methods. While it is no substitute for a proper introduction to statistical learning theory (see Boucheron et al. (2005), Vapnik (1998)), we will give you just enough intuition to get going. We will revisit generalization in many chapters throughout the book, exploring both what is known about the principles underlying generalization in various models, and also heuristic techniques that have been found (empirically) to yield improved generalization on tasks of practical interest.

3.6.1. Training Error and Generalization Error

In the standard supervised learning setting, we assume that the training data and the test data are drawn independently from identical distributions. This is commonly called the IID assumption. While this assumption is strong, it is worth noting that, absent any such assumption, we would be dead in the water. Why should we believe that training data sampled from distribution \(P(X,Y)\) should tell us how to make predictions on test data generated by a different distribution \(Q(X,Y)\)? Making such leaps turns out to require strong assumptions about how \(P\) and \(Q\) are related. Later on we will discuss some assumptions that allow for shifts in distribution but first we need to understand the IID case, where \(P(\cdot) = Q(\cdot)\).

To begin with, we need to differentiate between the training error \(R_\textrm{emp}\), which is a statistic calculated on the training dataset, and the generalization error \(R\), which is an expectation taken with respect to the underlying distribution. You can think of the generalization error as what you would see if you applied your model to an infinite stream of additional data examples drawn from the same underlying data distribution. Formally the training error is expressed as a sum (with the same notation as Section 3.1):

(3.6.1)\[R_\textrm{emp}[\mathbf{X}, \mathbf{y}, f] = \frac{1}{n} \sum_{i=1}^n l(\mathbf{x}^{(i)}, y^{(i)}, f(\mathbf{x}^{(i)})),\]

while the generalization error is expressed as an integral:

(3.6.2)\[R[p, f] = E_{(\mathbf{x}, y) \sim P} [l(\mathbf{x}, y, f(\mathbf{x}))] = \int \int l(\mathbf{x}, y, f(\mathbf{x})) p(\mathbf{x}, y) \;d\mathbf{x} dy.\]

Problematically, we can never calculate the generalization error \(R\) exactly. Nobody ever tells us the precise form of the density function \(p(\mathbf{x}, y)\). Moreover, we cannot sample an infinite stream of data points. Thus, in practice, we must estimate the generalization error by applying our model to an independent test set constituted of a random selection of examples \(\mathbf{X}'\) and labels \(\mathbf{y}'\) that were withheld from our training set. This consists of applying the same formula that was used for calculating the empirical training error but to a test set \(\mathbf{X}', \mathbf{y}'\).

Crucially, when we evaluate our classifier on the test set, we are working with a fixed classifier (it does not depend on the sample of the test set), and thus estimating its error is simply the problem of mean estimation. However the same cannot be said for the training set. Note that the model we wind up with depends explicitly on the selection of the training set and thus the training error will in general be a biased estimate of the true error on the underlying population. The central question of generalization is then when should we expect our training error to be close to the population error (and thus the generalization error).

3.6.1.1. Model Complexity

In classical theory, when we have simple models and abundant data, the training and generalization errors tend to be close. However, when we work with more complex models and/or fewer examples, we expect the training error to go down but the generalization gap to grow. This should not be surprising. Imagine a model class so expressive that for any dataset of \(n\) examples, we can find a set of parameters that can perfectly fit arbitrary labels, even if randomly assigned. In this case, even if we fit our training data perfectly, how can we conclude anything about the generalization error? For all we know, our generalization error might be no better than random guessing.

In general, absent any restriction on our model class, we cannot conclude, based on fitting the training data alone, that our model has discovered any generalizable pattern (Vapnik et al., 1994). On the other hand, if our model class was not capable of fitting arbitrary labels, then it must have discovered a pattern. Learning-theoretic ideas about model complexity derived some inspiration from the ideas of Karl Popper, an influential philosopher of science, who formalized the criterion of falsifiability. According to Popper, a theory that can explain any and all observations is not a scientific theory at all! After all, what has it told us about the world if it has not ruled out any possibility? In short, what we want is a hypothesis that could not explain any observations we might conceivably make and yet nevertheless happens to be compatible with those observations that we in fact make.

Now what precisely constitutes an appropriate notion of model complexity is a complex matter. Often, models with more parameters are able to fit a greater number of arbitrarily assigned labels. However, this is not necessarily true. For instance, kernel methods operate in spaces with infinite numbers of parameters, yet their complexity is controlled by other means (Schölkopf and Smola, 2002). One notion of complexity that often proves useful is the range of values that the parameters can take. Here, a model whose parameters are permitted to take arbitrary values would be more complex. We will revisit this idea in the next section, when we introduce weight decay, your first practical regularization technique. Notably, it can be difficult to compare complexity among members of substantially different model classes (say, decision trees vs. neural networks).

At this point, we must stress another important point that we will revisit when introducing deep neural networks. When a model is capable of fitting arbitrary labels, low training error does not necessarily imply low generalization error. However, it does not necessarily imply high generalization error either! All we can say with confidence is that low training error alone is not enough to certify low generalization error. Deep neural networks turn out to be just such models: while they generalize well in practice, they are too powerful to allow us to conclude much on the basis of training error alone. In these cases we must rely more heavily on our holdout data to certify generalization after the fact. Error on the holdout data, i.e., validation set, is called the validation error.

3.6.2. Underfitting or Overfitting?

When we compare the training and validation errors, we want to be mindful of two common situations. First, we want to watch out for cases when our training error and validation error are both substantial but there is a little gap between them. If the model is unable to reduce the training error, that could mean that our model is too simple (i.e., insufficiently expressive) to capture the pattern that we are trying to model. Moreover, since the generalization gap (\(R_\textrm{emp} - R\)) between our training and generalization errors is small, we have reason to believe that we could get away with a more complex model. This phenomenon is known as underfitting.

On the other hand, as we discussed above, we want to watch out for the cases when our training error is significantly lower than our validation error, indicating severe overfitting. Note that overfitting is not always a bad thing. In deep learning especially, the best predictive models often perform far better on training data than on holdout data. Ultimately, we usually care about driving the generalization error lower, and only care about the gap insofar as it becomes an obstacle to that end. Note that if the training error is zero, then the generalization gap is precisely equal to the generalization error and we can make progress only by reducing the gap.

3.6.2.1. Polynomial Curve Fitting

To illustrate some classical intuition about overfitting and model complexity, consider the following: given training data consisting of a single feature \(x\) and a corresponding real-valued label \(y\), we try to find the polynomial of degree \(d\)

(3.6.3)\[\hat{y}= \sum_{i=0}^d x^i w_i\]

for estimating the label \(y\). This is just a linear regression problem where our features are given by the powers of \(x\), the model’s weights are given by \(w_i\), and the bias is given by \(w_0\) since \(x^0 = 1\) for all \(x\). Since this is just a linear regression problem, we can use the squared error as our loss function.

A higher-order polynomial function is more complex than a lower-order polynomial function, since the higher-order polynomial has more parameters and the model function’s selection range is wider. Fixing the training dataset, higher-order polynomial functions should always achieve lower (at worst, equal) training error relative to lower-degree polynomials. In fact, whenever each data example has a distinct value of \(x\), a polynomial function with degree equal to the number of data examples can fit the training set perfectly. We compare the relationship between polynomial degree (model complexity) and both underfitting and overfitting in Fig. 3.6.1.

../_images/capacity-vs-error.svg

Fig. 3.6.1 Influence of model complexity on underfitting and overfitting.

3.6.2.2. Dataset Size

As the above bound already indicates, another big consideration to bear in mind is dataset size. Fixing our model, the fewer samples we have in the training dataset, the more likely (and more severely) we are to encounter overfitting. As we increase the amount of training data, the generalization error typically decreases. Moreover, in general, more data never hurts. For a fixed task and data distribution, model complexity should not increase more rapidly than the amount of data. Given more data, we might attempt to fit a more complex model. Absent sufficient data, simpler models may be more difficult to beat. For many tasks, deep learning only outperforms linear models when many thousands of training examples are available. In part, the current success of deep learning owes considerably to the abundance of massive datasets arising from Internet companies, cheap storage, connected devices, and the broad digitization of the economy.

3.6.3. Model Selection

Typically, we select our final model only after evaluating multiple models that differ in various ways (different architectures, training objectives, selected features, data preprocessing, learning rates, etc.). Choosing among many models is aptly called model selection.

In principle, we should not touch our test set until after we have chosen all our hyperparameters. Were we to use the test data in the model selection process, there is a risk that we might overfit the test data. Then we would be in serious trouble. If we overfit our training data, there is always the evaluation on test data to keep us honest. But if we overfit the test data, how would we ever know? See Ong et al. (2005) for an example of how this can lead to absurd results even for models where the complexity can be tightly controlled.

Thus, we should never rely on the test data for model selection. And yet we cannot rely solely on the training data for model selection either because we cannot estimate the generalization error on the very data that we use to train the model.

In practical applications, the picture gets muddier. While ideally we would only touch the test data once, to assess the very best model or to compare a small number of models with each other, real-world test data is seldom discarded after just one use. We can seldom afford a new test set for each round of experiments. In fact, recycling benchmark data for decades can have a significant impact on the development of algorithms, e.g., for image classification and optical character recognition.

The common practice for addressing the problem of training on the test set is to split our data three ways, incorporating a validation set in addition to the training and test datasets. The result is a murky business where the boundaries between validation and test data are worryingly ambiguous. Unless explicitly stated otherwise, in the experiments in this book we are really working with what should rightly be called training data and validation data, with no true test sets. Therefore, the accuracy reported in each experiment of the book is really the validation accuracy and not a true test set accuracy.

3.6.3.1. Cross-Validation

When training data is scarce, we might not even be able to afford to hold out enough data to constitute a proper validation set. One popular solution to this problem is to employ \(K\)-fold cross-validation. Here, the original training data is split into \(K\) non-overlapping subsets. Then model training and validation are executed \(K\) times, each time training on \(K-1\) subsets and validating on a different subset (the one not used for training in that round). Finally, the training and validation errors are estimated by averaging over the results from the \(K\) experiments.

3.6.4. Summary

This section explored some of the underpinnings of generalization in machine learning. Some of these ideas become complicated and counterintuitive when we get to deeper models; here, models are capable of overfitting data badly, and the relevant notions of complexity can be both implicit and counterintuitive (e.g., larger architectures with more parameters generalizing better). We leave you with a few rules of thumb:

  1. Use validation sets (or \(K\)-fold cross-validation) for model selection;

  2. More complex models often require more data;

  3. Relevant notions of complexity include both the number of parameters and the range of values that they are allowed to take;

  4. Keeping all else equal, more data almost always leads to better generalization;

  5. This entire talk of generalization is all predicated on the IID assumption. If we relax this assumption, allowing for distributions to shift between the train and testing periods, then we cannot say anything about generalization absent a further (perhaps milder) assumption.

3.6.5. Exercises

  1. When can you solve the problem of polynomial regression exactly?

  2. Give at least five examples where dependent random variables make treating the problem as IID data inadvisable.

  3. Can you ever expect to see zero training error? Under which circumstances would you see zero generalization error?

  4. Why is \(K\)-fold cross-validation very expensive to compute?

  5. Why is the \(K\)-fold cross-validation error estimate biased?

  6. The VC dimension is defined as the maximum number of points that can be classified with arbitrary labels \(\{\pm 1\}\) by a function of a class of functions. Why might this not be a good idea for measuring how complex the class of functions is? Hint: consider the magnitude of the functions.

  7. Your manager gives you a difficult dataset on which your current algorithm does not perform so well. How would you justify to him that you need more data? Hint: you cannot increase the data but you can decrease it.

11.1. Queries, Keys, and Values Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

11.1. Queries, Keys, and Values
Open the notebook in SageMaker Studio Lab

So far all the networks we have reviewed crucially relied on the input being of a well-defined size. For instance, the images in ImageNet are of size \(224 \times 224\) pixels and CNNs are specifically tuned to this size. Even in natural language processing the input size for RNNs is well defined and fixed. Variable size is addressed by sequentially processing one token at a time, or by specially designed convolution kernels (Kalchbrenner et al., 2014). This approach can lead to significant problems when the input is truly of varying size with varying information content, such as in Section 10.7 in the transformation of text (Sutskever et al., 2014). In particular, for long sequences it becomes quite difficult to keep track of everything that has already been generated or even viewed by the network. Even explicit tracking heuristics such as proposed by Yang et al. (2016) only offer limited benefit.

Compare this to databases. In their simplest form they are collections of keys (\(k\)) and values (\(v\)). For instance, our database \(\mathcal{D}\) might consist of tuples {(“Zhang”, “Aston”), (“Lipton”, “Zachary”), (“Li”, “Mu”), (“Smola”, “Alex”), (“Hu”, “Rachel”), (“Werness”, “Brent”)} with the last name being the key and the first name being the value. We can operate on \(\mathcal{D}\), for instance with the exact query (\(q\)) for “Li” which would return the value “Mu”. If (“Li”, “Mu”) was not a record in \(\mathcal{D}\), there would be no valid answer. If we also allowed for approximate matches, we would retrieve (“Lipton”, “Zachary”) instead. This quite simple and trivial example nonetheless teaches us a number of useful things:

  • We can design queries \(q\) that operate on (\(k\),\(v\)) pairs in such a manner as to be valid regardless of the database size.

  • The same query can receive different answers, according to the contents of the database.

  • The “code” being executed for operating on a large state space (the database) can be quite simple (e.g., exact match, approximate match, top-\(k\)).

  • There is no need to compress or simplify the database to make the operations effective.

Clearly we would not have introduced a simple database here if it wasn’t for the purpose of explaining deep learning. Indeed, this leads to one of the most exciting concepts introduced in deep learning in the past decade: the attention mechanism (Bahdanau et al., 2014). We will cover the specifics of its application to machine translation later. For now, simply consider the following: denote by \(\mathcal{D} \stackrel{\textrm{def}}{=} \{(\mathbf{k}_1, \mathbf{v}_1), \ldots (\mathbf{k}_m, \mathbf{v}_m)\}\) a database of \(m\) tuples of keys and values. Moreover, denote by \(\mathbf{q}\) a query. Then we can define the attention over \(\mathcal{D}\) as

(11.1.1)\[\textrm{Attention}(\mathbf{q}, \mathcal{D}) \stackrel{\textrm{def}}{=} \sum_{i=1}^m \alpha(\mathbf{q}, \mathbf{k}_i) \mathbf{v}_i,\]

where \(\alpha(\mathbf{q}, \mathbf{k}_i) \in \mathbb{R}\) (\(i = 1, \ldots, m\)) are scalar attention weights. The operation itself is typically referred to as attention pooling. The name attention derives from the fact that the operation pays particular attention to the terms for which the weight \(\alpha\) is significant (i.e., large). As such, the attention over \(\mathcal{D}\) generates a linear combination of values contained in the database. In fact, this contains the above example as a special case where all but one weight is zero. We have a number of special cases:

  • The weights \(\alpha(\mathbf{q}, \mathbf{k}_i)\) are nonnegative. In this case the output of the attention mechanism is contained in the convex cone spanned by the values \(\mathbf{v}_i\).

  • The weights \(\alpha(\mathbf{q}, \mathbf{k}_i)\) form a convex combination, i.e., \(\sum_i \alpha(\mathbf{q}, \mathbf{k}_i) = 1\) and \(\alpha(\mathbf{q}, \mathbf{k}_i) \geq 0\) for all \(i\). This is the most common setting in deep learning.

  • Exactly one of the weights \(\alpha(\mathbf{q}, \mathbf{k}_i)\) is \(1\), while all others are \(0\). This is akin to a traditional database query.

  • All weights are equal, i.e., \(\alpha(\mathbf{q}, \mathbf{k}_i) = \frac{1}{m}\) for all \(i\). This amounts to averaging across the entire database, also called average pooling in deep learning.

A common strategy for ensuring that the weights sum up to \(1\) is to normalize them via

(11.1.2)\[\alpha(\mathbf{q}, \mathbf{k}_i) = \frac{\alpha(\mathbf{q}, \mathbf{k}_i)}{{\sum_j} \alpha(\mathbf{q}, \mathbf{k}_j)}.\]

In particular, to ensure that the weights are also nonnegative, one can resort to exponentiation. This means that we can now pick any function \(a(\mathbf{q}, \mathbf{k})\) and then apply the softmax operation used for multinomial models to it via

(11.1.3)\[\alpha(\mathbf{q}, \mathbf{k}_i) = \frac{\exp(a(\mathbf{q}, \mathbf{k}_i))}{\sum_j \exp(a(\mathbf{q}, \mathbf{k}_j))}.\]

This operation is readily available in all deep learning frameworks. It is differentiable and its gradient never vanishes, all of which are desirable properties in a model. Note though, the attention mechanism introduced above is not the only option. For instance, we can design a non-differentiable attention model that can be trained using reinforcement learning methods (Mnih et al., 2014). As one would expect, training such a model is quite complex. Consequently the bulk of modern attention research follows the framework outlined in Fig. 11.1.1. We thus focus our exposition on this family of differentiable mechanisms.

../_images/qkv.svg

Fig. 11.1.1 The attention mechanism computes a linear combination over values \(\mathbf{v}_\mathit{i}\) via attention pooling, where weights are derived according to the compatibility between a query \(\mathbf{q}\) and keys \(\mathbf{k}_\mathit{i}\).

What is quite remarkable is that the actual “code” for executing on the set of keys and values, namely the query, can be quite concise, even though the space to operate on is significant. This is a desirable property for a network layer as it does not require too many parameters to learn. Just as convenient is the fact that attention can operate on arbitrarily large databases without the need to change the way the attention pooling operation is performed.

import torch
from d2l import torch as d2l

11.1.1. Visualization

One of the benefits of the attention mechanism is that it can be quite intuitive, particularly when the weights are nonnegative and sum to \(1\). In this case we might interpret large weights as a way for the model to select components of relevance. While this is a good intuition, it is important to remember that it is just that, an intuition. Regardless, we may want to visualize its effect on the given set of keys when applying a variety of different queries. This function will come in handy later.

We thus define the show_heatmaps function. Note that it does not take a matrix (of attention weights) as its input but rather a tensor with four axes, allowing for an array of different queries and weights. Consequently the input matrices has the shape (number of rows for display, number of columns for display, number of queries, number of keys). This will come in handy later on when we want to visualize the workings that are to design Transformers.

#@save
def show_heatmaps(matrices, xlabel, ylabel, titles=None, figsize=(2.5, 2.5),
                  cmap='Reds'):
    """Show heatmaps of matrices."""
    d2l.use_svg_display()
    num_rows, num_cols, _, _ = matrices.shape
    fig, axes = d2l.plt.subplots(num_rows, num_cols, figsize=figsize,
                                 sharex=True, sharey=True, squeeze=False)
    for i, (row_axes, row_matrices) in enumerate(zip(axes, matrices)):
        for j, (ax, matrix) in enumerate(zip(row_axes, row_matrices)):
            pcm = ax.imshow(matrix.detach().numpy(), cmap=cmap)
            if i == num_rows - 1:
                ax.set_xlabel(xlabel)
            if j == 0:
                ax.set_ylabel(ylabel)
            if titles:
                ax.set_title(titles[j])
    fig.colorbar(pcm, ax=axes, shrink=0.6);

As a quick sanity check let’s visualize the identity matrix, representing a case where the attention weight is \(1\) only when the query and the key are the same.

attention_weights = torch.eye(10).reshape((1, 1, 10, 10))
show_heatmaps(attention_weights, xlabel='Keys', ylabel='Queries')
../_images/output_queries-keys-values_7fe0e8_33_0.svg

11.1.2. Summary

The attention mechanism allows us to aggregate data from many (key, value) pairs. So far our discussion was quite abstract, simply describing a way to pool data. We have not explained yet where those mysterious queries, keys, and values might arise from. Some intuition might help here: for instance, in a regression setting, the query might correspond to the location where the regression should be carried out. The keys are the locations where past data was observed and the values are the (regression) values themselves. This is the so-called Nadaraya–Watson estimator (Nadaraya, 1964, Watson, 1964) that we will be studying in the next section.

By design, the attention mechanism provides a differentiable means of control by which a neural network can select elements from a set and to construct an associated weighted sum over representations.

11.1.3. Exercises

  1. Suppose that you wanted to reimplement approximate (key, query) matches as used in classical databases, which attention function would you pick?

  2. Suppose that the attention function is given by \(a(\mathbf{q}, \mathbf{k}_i) = \mathbf{q}^\top \mathbf{k}_i\) and that \(\mathbf{k}_i = \mathbf{v}_i\) for \(i = 1, \ldots, m\). Denote by \(p(\mathbf{k}_i; \mathbf{q})\) the probability distribution over keys when using the softmax normalization in (11.1.3). Prove that \(\nabla_{\mathbf{q}} \mathop{\textrm{Attention}}(\mathbf{q}, \mathcal{D}) = \textrm{Cov}_{p(\mathbf{k}_i; \mathbf{q})}[\mathbf{k}_i]\).

  3. Design a differentiable search engine using the attention mechanism.

  4. Review the design of the Squeeze and Excitation Networks (Hu et al., 2018) and interpret them through the lens of the attention mechanism.

12.3. Gradient Descent Open the notebook in SageMaker Studio Lab

Assigned source reading · Aston Zhang, Zachary C. Lipton, Mu Li and Alexander J. Smola

Dive into Deep Learning — the authors and contributors; text CC BY-SA 4.0; accompanying code under its separately stated license.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

12.3. Gradient Descent
Open the notebook in SageMaker Studio Lab

In this section we are going to introduce the basic concepts underlying gradient descent. Although it is rarely used directly in deep learning, an understanding of gradient descent is key to understanding stochastic gradient descent algorithms. For instance, the optimization problem might diverge due to an overly large learning rate. This phenomenon can already be seen in gradient descent. Likewise, preconditioning is a common technique in gradient descent and carries over to more advanced algorithms. Let’s start with a simple special case.

12.3.1. One-Dimensional Gradient Descent

Gradient descent in one dimension is an excellent example to explain why the gradient descent algorithm may reduce the value of the objective function. Consider some continuously differentiable real-valued function \(f: \mathbb{R} \rightarrow \mathbb{R}\). Using a Taylor expansion we obtain

(12.3.1)\[f(x + \epsilon) = f(x) + \epsilon f'(x) + \mathcal{O}(\epsilon^2).\]

That is, in first-order approximation \(f(x+\epsilon)\) is given by the function value \(f(x)\) and the first derivative \(f'(x)\) at \(x\). It is not unreasonable to assume that for small \(\epsilon\) moving in the direction of the negative gradient will decrease \(f\). To keep things simple we pick a fixed step size \(\eta > 0\) and choose \(\epsilon = -\eta f'(x)\). Plugging this into the Taylor expansion above we get

(12.3.2)\[f(x - \eta f'(x)) = f(x) - \eta f'^2(x) + \mathcal{O}(\eta^2 f'^2(x)).\]

If the derivative \(f'(x) \neq 0\) does not vanish we make progress since \(\eta f'^2(x)>0\). Moreover, we can always choose \(\eta\) small enough for the higher-order terms to become irrelevant. Hence we arrive at

(12.3.3)\[f(x - \eta f'(x)) \lessapprox f(x).\]

This means that, if we use

(12.3.4)\[x \leftarrow x - \eta f'(x)\]

to iterate \(x\), the value of function \(f(x)\) might decline. Therefore, in gradient descent we first choose an initial value \(x\) and a constant \(\eta > 0\) and then use them to continuously iterate \(x\) until the stop condition is reached, for example, when the magnitude of the gradient \(|f'(x)|\) is small enough or the number of iterations has reached a certain value.

For simplicity we choose the objective function \(f(x)=x^2\) to illustrate how to implement gradient descent. Although we know that \(x=0\) is the solution to minimize \(f(x)\), we still use this simple function to observe how \(x\) changes.

%matplotlib inline
import numpy as np
import torch
from d2l import torch as d2l

def f(x):  # Objective function
    return x ** 2

def f_grad(x):  # Gradient (derivative) of the objective function
    return 2 * x

Next, we use \(x=10\) as the initial value and assume \(\eta=0.2\). Using gradient descent to iterate \(x\) for 10 times we can see that, eventually, the value of \(x\) approaches the optimal solution.

def gd(eta, f_grad):
    x = 10.0
    results = [x]
    for i in range(10):
        x -= eta * f_grad(x)
        results.append(float(x))
    print(f'epoch 10, x: {x:f}')
    return results

results = gd(0.2, f_grad)
epoch 10, x: 0.060466

The progress of optimizing over \(x\) can be plotted as follows.

def show_trace(results, f):
    n = max(abs(min(results)), abs(max(results)))
    f_line = torch.arange(-n, n, 0.01)
    d2l.set_figsize()
    d2l.plot([f_line, results], [[f(x) for x in f_line], [
        f(x) for x in results]], 'x', 'f(x)', fmts=['-', '-o'])

show_trace(results, f)
../_images/output_gd_79c039_27_0.svg

12.3.1.1. Learning Rate

The learning rate \(\eta\) can be set by the algorithm designer. If we use a learning rate that is too small, it will cause \(x\) to update very slowly, requiring more iterations to get a better solution. To show what happens in such a case, consider the progress in the same optimization problem for \(\eta = 0.05\). As we can see, even after 10 steps we are still very far from the optimal solution.

show_trace(gd(0.05, f_grad), f)
epoch 10, x: 3.486784
../_images/output_gd_79c039_39_1.svg

Conversely, if we use an excessively high learning rate, \(\left|\eta f'(x)\right|\) might be too large for the first-order Taylor expansion formula. That is, the term \(\mathcal{O}(\eta^2 f'^2(x))\) in (12.3.2) might become significant. In this case, we cannot guarantee that the iteration of \(x\) will be able to lower the value of \(f(x)\). For example, when we set the learning rate to \(\eta=1.1\), \(x\) overshoots the optimal solution \(x=0\) and gradually diverges.

show_trace(gd(1.1, f_grad), f)
epoch 10, x: 61.917364
../_images/output_gd_79c039_51_1.svg

12.3.1.2. Local Minima

To illustrate what happens for nonconvex functions consider the case of \(f(x) = x \cdot \cos(cx)\) for some constant \(c\). This function has infinitely many local minima. Depending on our choice of the learning rate and depending on how well conditioned the problem is, we may end up with one of many solutions. The example below illustrates how an (unrealistically) high learning rate will lead to a poor local minimum.

c = torch.tensor(0.15 * np.pi)

def f(x):  # Objective function
    return x * torch.cos(c * x)

def f_grad(x):  # Gradient of the objective function
    return torch.cos(c * x) - c * x * torch.sin(c * x)

show_trace(gd(2, f_grad), f)
epoch 10, x: -1.528166
../_images/output_gd_79c039_63_1.svg

12.3.2. Multivariate Gradient Descent

Now that we have a better intuition of the univariate case, let’s consider the situation where \(\mathbf{x} = [x_1, x_2, \ldots, x_d]^\top\). That is, the objective function \(f: \mathbb{R}^d \to \mathbb{R}\) maps vectors into scalars. Correspondingly its gradient is multivariate, too. It is a vector consisting of \(d\) partial derivatives:

(12.3.5)\[\nabla f(\mathbf{x}) = \bigg[\frac{\partial f(\mathbf{x})}{\partial x_1}, \frac{\partial f(\mathbf{x})}{\partial x_2}, \ldots, \frac{\partial f(\mathbf{x})}{\partial x_d}\bigg]^\top.\]

Each partial derivative element \(\partial f(\mathbf{x})/\partial x_i\) in the gradient indicates the rate of change of \(f\) at \(\mathbf{x}\) with respect to the input \(x_i\). As before in the univariate case we can use the corresponding Taylor approximation for multivariate functions to get some idea of what we should do. In particular, we have that

(12.3.6)\[f(\mathbf{x} + \boldsymbol{\epsilon}) = f(\mathbf{x}) + \mathbf{\boldsymbol{\epsilon}}^\top \nabla f(\mathbf{x}) + \mathcal{O}(\|\boldsymbol{\epsilon}\|^2).\]

In other words, up to second-order terms in \(\boldsymbol{\epsilon}\) the direction of steepest descent is given by the negative gradient \(-\nabla f(\mathbf{x})\). Choosing a suitable learning rate \(\eta > 0\) yields the prototypical gradient descent algorithm:

(12.3.7)\[\mathbf{x} \leftarrow \mathbf{x} - \eta \nabla f(\mathbf{x}).\]

To see how the algorithm behaves in practice let’s construct an objective function \(f(\mathbf{x})=x_1^2+2x_2^2\) with a two-dimensional vector \(\mathbf{x} = [x_1, x_2]^\top\) as input and a scalar as output. The gradient is given by \(\nabla f(\mathbf{x}) = [2x_1, 4x_2]^\top\). We will observe the trajectory of \(\mathbf{x}\) by gradient descent from the initial position \([-5, -2]\).

To begin with, we need two more helper functions. The first uses an update function and applies it 20 times to the initial value. The second helper visualizes the trajectory of \(\mathbf{x}\).

def train_2d(trainer, steps=20, f_grad=None):  #@save
    """Optimize a 2D objective function with a customized trainer."""
    # `s1` and `s2` are internal state variables that will be used in Momentum, adagrad, RMSProp
    x1, x2, s1, s2 = -5, -2, 0, 0
    results = [(x1, x2)]
    for i in range(steps):
        if f_grad:
            x1, x2, s1, s2 = trainer(x1, x2, s1, s2, f_grad)
        else:
            x1, x2, s1, s2 = trainer(x1, x2, s1, s2)
        results.append((x1, x2))
    print(f'epoch {i + 1}, x1: {float(x1):f}, x2: {float(x2):f}')
    return results

def show_trace_2d(f, results):  #@save
    """Show the trace of 2D variables during optimization."""
    d2l.set_figsize()
    d2l.plt.plot(*zip(*results), '-o', color='#ff7f0e')
    x1, x2 = torch.meshgrid(torch.arange(-5.5, 1.0, 0.1),
                          torch.arange(-3.0, 1.0, 0.1), indexing='ij')
    d2l.plt.contour(x1, x2, f(x1, x2), colors='#1f77b4')
    d2l.plt.xlabel('x1')
    d2l.plt.ylabel('x2')

Next, we observe the trajectory of the optimization variable \(\mathbf{x}\) for learning rate \(\eta = 0.1\). We can see that after 20 steps the value of \(\mathbf{x}\) approaches its minimum at \([0, 0]\). Progress is fairly well-behaved albeit rather slow.

def f_2d(x1, x2):  # Objective function
    return x1 ** 2 + 2 * x2 ** 2

def f_2d_grad(x1, x2):  # Gradient of the objective function
    return (2 * x1, 4 * x2)

def gd_2d(x1, x2, s1, s2, f_grad):
    g1, g2 = f_grad(x1, x2)
    return (x1 - eta * g1, x2 - eta * g2, 0, 0)

eta = 0.1
show_trace_2d(f_2d, train_2d(gd_2d, f_grad=f_2d_grad))
epoch 20, x1: -0.057646, x2: -0.000073
../_images/output_gd_79c039_87_1.svg

12.3.3. Adaptive Methods

As we could see in Section 12.3.1.1, getting the learning rate \(\eta\) “just right” is tricky. If we pick it too small, we make little progress. If we pick it too large, the solution oscillates and in the worst case it might even diverge. What if we could determine \(\eta\) automatically or get rid of having to select a learning rate at all? Second-order methods that look not only at the value and gradient of the objective function but also at its curvature can help in this case. While these methods cannot be applied to deep learning directly due to the computational cost, they provide useful intuition into how to design advanced optimization algorithms that mimic many of the desirable properties of the algorithms outlined below.

12.3.3.1. Newton’s Method

Reviewing the Taylor expansion of some function \(f: \mathbb{R}^d \rightarrow \mathbb{R}\) there is no need to stop after the first term. In fact, we can write it as

(12.3.8)\[f(\mathbf{x} + \boldsymbol{\epsilon}) = f(\mathbf{x}) + \boldsymbol{\epsilon}^\top \nabla f(\mathbf{x}) + \frac{1}{2} \boldsymbol{\epsilon}^\top \nabla^2 f(\mathbf{x}) \boldsymbol{\epsilon} + \mathcal{O}(\|\boldsymbol{\epsilon}\|^3).\]

To avoid cumbersome notation we define \(\mathbf{H} \stackrel{\textrm{def}}{=} \nabla^2 f(\mathbf{x})\) to be the Hessian of \(f\), which is a \(d \times d\) matrix. For small \(d\) and simple problems \(\mathbf{H}\) is easy to compute. For deep neural networks, on the other hand, \(\mathbf{H}\) may be prohibitively large, due to the cost of storing \(\mathcal{O}(d^2)\) entries. Furthermore it may be too expensive to compute via backpropagation. For now let’s ignore such considerations and look at what algorithm we would get.

After all, the minimum of \(f\) satisfies \(\nabla f = 0\). Following calculus rules in Section 2.4.3, by taking derivatives of (12.3.8) with regard to \(\boldsymbol{\epsilon}\) and ignoring higher-order terms we arrive at

(12.3.9)\[\nabla f(\mathbf{x}) + \mathbf{H} \boldsymbol{\epsilon} = 0 \textrm{ and hence } \boldsymbol{\epsilon} = -\mathbf{H}^{-1} \nabla f(\mathbf{x}).\]

That is, we need to invert the Hessian \(\mathbf{H}\) as part of the optimization problem.

As a simple example, for \(f(x) = \frac{1}{2} x^2\) we have \(\nabla f(x) = x\) and \(\mathbf{H} = 1\). Hence for any \(x\) we obtain \(\epsilon = -x\). In other words, a single step is sufficient to converge perfectly without the need for any adjustment! Alas, we got a bit lucky here: the Taylor expansion was exact since \(f(x+\epsilon)= \frac{1}{2} x^2 + \epsilon x + \frac{1}{2} \epsilon^2\).

Let’s see what happens in other problems. Given a convex hyperbolic cosine function \(f(x) = \cosh(cx)\) for some constant \(c\), we can see that the global minimum at \(x=0\) is reached after a few iterations.

c = torch.tensor(0.5)

def f(x):  # Objective function
    return torch.cosh(c * x)

def f_grad(x):  # Gradient of the objective function
    return c * torch.sinh(c * x)

def f_hess(x):  # Hessian of the objective function
    return c**2 * torch.cosh(c * x)

def newton(eta=1):
    x = 10.0
    results = [x]
    for i in range(10):
        x -= eta * f_grad(x) / f_hess(x)
        results.append(float(x))
    print('epoch 10, x:', x)
    return results

show_trace(newton(), f)
epoch 10, x: tensor(0.)
../_images/output_gd_79c039_99_1.svg

Now let’s consider a nonconvex function, such as \(f(x) = x \cos(c x)\) for some constant \(c\). After all, note that in Newton’s method we end up dividing by the Hessian. This means that if the second derivative is negative we may walk into the direction of increasing the value of \(f\). That is a fatal flaw of the algorithm. Let’s see what happens in practice.

c = torch.tensor(0.15 * np.pi)

def f(x):  # Objective function
    return x * torch.cos(c * x)

def f_grad(x):  # Gradient of the objective function
    return torch.cos(c * x) - c * x * torch.sin(c * x)

def f_hess(x):  # Hessian of the objective function
    return - 2 * c * torch.sin(c * x) - x * c**2 * torch.cos(c * x)

show_trace(newton(), f)
epoch 10, x: tensor(26.8341)
../_images/output_gd_79c039_111_1.svg

This went spectacularly wrong. How can we fix it? One way would be to “fix” the Hessian by taking its absolute value instead. Another strategy is to bring back the learning rate. This seems to defeat the purpose, but not quite. Having second-order information allows us to be cautious whenever the curvature is large and to take longer steps whenever the objective function is flatter. Let’s see how this works with a slightly smaller learning rate, say \(\eta = 0.5\). As we can see, we have quite an efficient algorithm.

show_trace(newton(0.5), f)
epoch 10, x: tensor(7.2699)
../_images/output_gd_79c039_123_1.svg

12.3.3.2. Convergence Analysis

We only analyze the convergence rate of Newton’s method for some convex and three times differentiable objective function \(f\), where the second derivative is nonzero, i.e., \(f'' > 0\). The multivariate proof is a straightforward extension of the one-dimensional argument below and omitted since it does not help us much in terms of intuition.

Denote by \(x^{(k)}\) the value of \(x\) at the \(k^\textrm{th}\) iteration and let \(e^{(k)} \stackrel{\textrm{def}}{=} x^{(k)} - x^*\) be the distance from optimality at the \(k^\textrm{th}\) iteration. By Taylor expansion we have that the condition \(f'(x^*) = 0\) can be written as

(12.3.10)\[0 = f'(x^{(k)} - e^{(k)}) = f'(x^{(k)}) - e^{(k)} f''(x^{(k)}) + \frac{1}{2} (e^{(k)})^2 f'''(\xi^{(k)}),\]

which holds for some \(\xi^{(k)} \in [x^{(k)} - e^{(k)}, x^{(k)}]\). Dividing the above expansion by \(f''(x^{(k)})\) yields

(12.3.11)\[e^{(k)} - \frac{f'(x^{(k)})}{f''(x^{(k)})} = \frac{1}{2} (e^{(k)})^2 \frac{f'''(\xi^{(k)})}{f''(x^{(k)})}.\]

Recall that we have the update \(x^{(k+1)} = x^{(k)} - f'(x^{(k)}) / f''(x^{(k)})\). Plugging in this update equation and taking the absolute value of both sides, we have

(12.3.12)\[\left|e^{(k+1)}\right| = \frac{1}{2}(e^{(k)})^2 \frac{\left|f'''(\xi^{(k)})\right|}{f''(x^{(k)})}.\]

Consequently, whenever we are in a region of bounded \(\left|f'''(\xi^{(k)})\right| / (2f''(x^{(k)})) \leq c\), we have a quadratically decreasing error

(12.3.13)\[\left|e^{(k+1)}\right| \leq c (e^{(k)})^2.\]

As an aside, optimization researchers call this linear convergence, whereas a condition such as \(\left|e^{(k+1)}\right| \leq \alpha \left|e^{(k)}\right|\) would be called a constant rate of convergence. Note that this analysis comes with a number of caveats. First, we do not really have much of a guarantee when we will reach the region of rapid convergence. Instead, we only know that once we reach it, convergence will be very quick. Second, this analysis requires that \(f\) is well-behaved up to higher-order derivatives. It comes down to ensuring that \(f\) does not have any “surprising” properties in terms of how it might change its values.

12.3.3.3. Preconditioning

Quite unsurprisingly computing and storing the full Hessian is very expensive. It is thus desirable to find alternatives. One way to improve matters is preconditioning. It avoids computing the Hessian in its entirety but only computes the diagonal entries. This leads to update algorithms of the form

(12.3.14)\[\mathbf{x} \leftarrow \mathbf{x} - \eta \textrm{diag}(\mathbf{H})^{-1} \nabla f(\mathbf{x}).\]

While this is not quite as good as the full Newton’s method, it is still much better than not using it. To see why this might be a good idea consider a situation where one variable denotes height in millimeters and the other one denotes height in kilometers. Assuming that for both the natural scale is in meters, we have a terrible mismatch in parametrizations. Fortunately, using preconditioning removes this. Effectively preconditioning with gradient descent amounts to selecting a different learning rate for each variable (coordinate of vector \(\mathbf{x}\)). As we will see later, preconditioning drives some of the innovation in stochastic gradient descent optimization algorithms.

12.3.4. Summary

  • Learning rates matter. Too large and we diverge, too small and we do not make progress.

  • Gradient descent can get stuck in local minima.

  • In high dimensions adjusting the learning rate is complicated.

  • Preconditioning can help with scale adjustment.

  • Newton’s method is a lot faster once it has started working properly in convex problems.

  • Beware of using Newton’s method without any adjustments for nonconvex problems.

12.3.5. Exercises

  1. Experiment with different learning rates and objective functions for gradient descent.

  2. Implement line search to minimize a convex function in the interval \([a, b]\).

    1. Do you need derivatives for binary search, i.e., to decide whether to pick \([a, (a+b)/2]\) or \([(a+b)/2, b]\).

    2. How rapid is the rate of convergence for the algorithm?

    3. Implement the algorithm and apply it to minimizing \(\log (\exp(x) + \exp(-2x -3))\).

  3. Design an objective function defined on \(\mathbb{R}^2\) where gradient descent is exceedingly slow. Hint: scale different coordinates differently.

  4. Implement the lightweight version of Newton’s method using preconditioning:

    1. Use diagonal Hessian as preconditioner.

    2. Use the absolute values of that rather than the actual (possibly signed) values.

    3. Apply this to the problem above.

  5. Apply the algorithm above to a number of objective functions (convex or not). What happens if you rotate coordinates by \(45\) degrees?

Discussions

LLM01:2025 Prompt Injection

Assigned source reading · OWASP GenAI Security Project contributors

Copyright © 2025 OWASP Foundation, Inc. and contributors. OWASP trademarks are excluded.

Original source · Creative Commons Attribution-ShareAlike 4.0 · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

LLM01:2025 Prompt Injection

A Prompt Injection Vulnerability occurs when user prompts alter the LLM’s behavior or output in unintended ways. These inputs can affect the model even if they are imperceptible to humans, therefore prompt injections do not need to be human-visible/readable, as long as the content is parsed by the model.

Prompt Injection vulnerabilities exist in how models process prompts, and how input may force the model to incorrectly pass prompt data to other parts of the model, potentially causing them to violate guidelines, generate harmful content, enable unauthorized access, or influence critical decisions. While techniques like Retrieval Augmented Generation (RAG) and fine-tuning aim to make LLM outputs more relevant and accurate, research shows that they do not fully mitigate prompt injection vulnerabilities.

While prompt injection and jailbreaking are related concepts in LLM security, they are often used interchangeably. Prompt injection involves manipulating model responses through specific inputs to alter its behavior, which can include bypassing safety measures. Jailbreaking is a form of prompt injection where the attacker provides inputs that cause the model to disregard its safety protocols entirely. Developers can build safeguards into system prompts and input handling to help mitigate prompt injection attacks, but effective prevention of jailbreaking requires ongoing updates to the model’s training and safety mechanisms.

Types of Prompt Injection Vulnerabilities

 

Direct Prompt Injections

Direct prompt injections occur when a user’s prompt input directly alters the behavior of the model in unintended or unexpected ways. The input can be either intentional (i.e., a malicious actor deliberately crafting a prompt to exploit the model) or unintentional (i.e., a user inadvertently providing input that triggers unexpected behavior).

Indirect Prompt Injections

Indirect prompt injections occur when an LLM accepts input from external sources, such as websites or files. The content may have in the external content data that when interpreted by the model, alters the behavior of the model in unintended or unexpected ways. Like direct injections, indirect injections can be either intentional or unintentional.

The severity and nature of the impact of a successful prompt injection attack can vary greatly and are largely dependent on both the business context the model operates in, and the agency with which the model is architected. Generally, however, prompt injection can lead to unintended outcomes, including but not limited to:

  • Disclosure of sensitive information
  • Revealing sensitive information about AI system infrastructure or system prompts
  • Content manipulation leading to incorrect or biased outputs
  • Providing unauthorized access to functions available to the LLM
  • Executing arbitrary commands in connected systems
  • Manipulating critical decision-making processes

The rise of multimodal AI, which processes multiple data types simultaneously, introduces unique prompt injection risks. Malicious actors could exploit interactions between modalities, such as hiding instructions in images that accompany benign text. The complexity of these systems expands the attack surface. Multimodal models may also be susceptible to novel cross-modal attacks that are difficult to detect and mitigate with current techniques. Robust multimodal-specific defenses are an important area for further research and development.

Prevention and Mitigation Strategies

Prompt injection vulnerabilities are possible due to the nature of generative AI. Given the stochastic influence at the heart of the way models work, it is unclear if there are fool-proof methods of prevention for prompt injection. However, the following measures can mitigate the impact of prompt injections:

1. Constrain model behavior

Provide specific instructions about the model’s role, capabilities, and limitations within the system prompt. Enforce strict context adherence, limit responses to specific tasks or topics, and instruct the model to ignore attempts to modify core instructions.

2. Define and validate expected output formats

Specify clear output formats, request detailed reasoning and source citations, and use deterministic code to validate adherence to these formats.

3. Implement input and output filtering

Define sensitive categories and construct rules for identifying and handling such content. Apply semantic filters and use string-checking to scan for non-allowed content. Evaluate responses using the RAG Triad: Assess context relevance, groundedness, and question/answer relevance to identify potentially malicious outputs.

4. Enforce privilege control and least privilege access

Provide the application with its own API tokens for extensible functionality, and handle these functions in code rather than providing them to the model. Restrict the model’s access privileges to the minimum necessary for its intended operations.

5. Require human approval for high-risk actions

Implement human-in-the-loop controls for privileged operations to prevent unauthorized actions.

6. Segregate and identify external content

Separate and clearly denote untrusted content to limit its influence on user prompts.

7. Conduct adversarial testing and attack simulations\

Perform regular penetration testing and breach simulations, treating the model as an untrusted user to test the effectiveness of trust boundaries and access controls.

Example Attack Scenarios

Scenario #1: Direct Injection

An attacker injects a prompt into a customer support chatbot, instructing it to ignore previous guidelines, query private data stores, and send emails, leading to unauthorized access and privilege escalation.

Scenario #2: Indirect Injection

A user employs an LLM to summarize a webpage containing hidden instructions that cause the LLM to insert an image linking to a URL, leading to exfiltration of the the private conversation.

Scenario #3: Unintentional Injection

A company includes an instruction in a job description to identify AI-generated applications. An applicant, unaware of this instruction, uses an LLM to optimize their resume, inadvertently triggering the AI detection.

Scenario #4: Intentional Model Influence

An attacker modifies a document in a repository used by a Retrieval-Augmented Generation (RAG) application. When a user’s query returns the modified content, the malicious instructions alter the LLM’s output, generating misleading results.

Scenario #5: Code Injection

An attacker exploits a vulnerability (CVE-2024-5184) in an LLM-powered email assistant to inject malicious prompts, allowing access to sensitive information and manipulation of email content.

Scenario #6: Payload Splitting

An attacker uploads a resume with split malicious prompts. When an LLM is used to evaluate the candidate, the combined prompts manipulate the model’s response, resulting in a positive recommendation despite the actual resume contents.

Scenario #7: Multimodal Injection

An attacker embeds a malicious prompt within an image that accompanies benign text. When a multimodal AI processes the image and text concurrently, the hidden prompt alters the model’s behavior, potentially leading to unauthorized actions or disclosure of sensitive information.

Scenario #8: Adversarial Suffix

An attacker appends a seemingly meaningless string of characters to a prompt, which influences the LLM’s output in a malicious way, bypassing safety measures.

Scenario #9: Multilingual/Obfuscated Attack

An attacker uses multiple languages or encodes malicious instructions (e.g., using Base64 or emojis) to evade filters and manipulate the LLM’s behavior.

Reference Links

  1. ChatGPT Plugin Vulnerabilities – Chat with Code Embrace the Red
  2. ChatGPT Cross Plugin Request Forgery and Prompt Injection Embrace the Red
  3. Not what you’ve signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection Arxiv
  4. Defending ChatGPT against Jailbreak Attack via Self-Reminder Research Square
  5. Prompt Injection attack against LLM-integrated Applications Cornell University
  6. Inject My PDF: Prompt Injection for your Resume Kai Greshake
  7. Not what you’ve signed up for: Compromising Real-World LLM-Integrated Applications with Indirect Prompt Injection Cornell University
  8. Threat Modeling LLM Applications AI Village
  9. Reducing The Impact of Prompt Injection Attacks Through Design Kudelski Security
  10. Adversarial Machine Learning: A Taxonomy and Terminology of Attacks and Mitigations (nist.gov)
  11. 2407.07403 A Survey of Attacks on Large Vision-Language Models: Resources, Advances, and Future Trends (arxiv.org)
  12. Exploiting Programmatic Behavior of LLMs: Dual-Use Through Standard Security Attacks
  13. Universal and Transferable Adversarial Attacks on Aligned Language Models (arxiv.org)
  14. From ChatGPT to ThreatGPT: Impact of Generative AI in Cybersecurity and Privacy (arxiv.org)

Related Frameworks and Taxonomies

Refer to this section for comprehensive information, scenarios strategies relating to infrastructure deployment, applied environment controls and other best practices.

LLM Top 10

LLM01:2025 Prompt Injection

A Prompt Injection Vulnerability occurs when user prompts alter the LLM’s behavior or output in unintended ways. These inputs...

LLM02:2025 Sensitive Information Disclosure

Sensitive information can affect both the LLM and its application context. This includes personal identifiable information (PII), financial details,...

LLM03:2025 Supply Chain

LLM supply chains are susceptible to various vulnerabilities, which can affect the integrity of training data, models, and deployment...

LLM04:2025 Data and Model Poisoning

Data poisoning occurs when pre-training, fine-tuning, or embedding data is manipulated to introduce vulnerabilities, backdoors, or biases. This manipulation...

LLM05:2025 Improper Output Handling

Improper Output Handling refers specifically to insufficient validation, sanitization, and handling of the outputs generated by large language models...

LLM06:2025 Excessive Agency

An LLM-based system is often granted a degree of agency by its developer – the ability to call functions...

LLM07:2025 System Prompt Leakage

The system prompt leakage vulnerability in LLMs refers to the risk that the system prompts or instructions used to...

LLM08:2025 Vector and Embedding Weaknesses

Vectors and embeddings vulnerabilities present significant security risks in systems utilizing Retrieval Augmented Generation (RAG) with Large Language Models...

LLM09:2025 Misinformation

Misinformation from LLMs poses a core vulnerability for applications relying on these models. Misinformation occurs when LLMs produce false...

LLM10:2025 Unbounded Consumption

Unbounded Consumption refers to the process where a Large Language Model (LLM) generates outputs based on input queries or...

Django Tutorial Part 3: Using models

Assigned source reading · Mozilla Contributors

MDN Web Docs — Mozilla Contributors

Original source · Creative Commons Attribution-ShareAlike 2.5 or later · Retrieved October 25, 2026.

Changes: site navigation and active scripts removed; relative links made absolute; one default code framework retained where parallel alternatives existed. The instructional text is attributed source material, separate from original Academy teaching. No publisher endorsement is implied.

Django Tutorial Part 3: Using models

This article shows how to define models for the LocalLibrary website. It explains what a model is, how it is declared, and some of the main field types. It also briefly shows a few of the main ways you can access model data.

Prerequisites: Django Tutorial Part 2: Creating a skeleton website.
Objective:

To be able to design and create your own models, choosing fields appropriately.

Overview

Django web applications access and manage data through Python objects referred to as models. Models define the structure of stored data, including the field types and possibly also their maximum size, default values, selection list options, help text for documentation, label text for forms, etc. The definition of the model is independent of the underlying database — you can choose one of several as part of your project settings. Once you've chosen what database you want to use, you don't need to talk to it directly at all — you just write your model structure and other code, and Django handles all the dirty work of communicating with the database for you.

This tutorial shows how to define and access the models for the LocalLibrary website example.

Designing the LocalLibrary models

Before you jump in and start coding the models, it's worth taking a few minutes to think about what data we need to store and the relationships between the different objects.

We know that we need to store information about books (title, summary, author, written language, category, ISBN) and that we might have multiple copies available (with globally unique id, availability status, etc.). We might need to store more information about the author than just their name, and there might be multiple authors with the same or similar names. We want to be able to sort information based on book title, author, written language, and category.

When designing your models, it makes sense to have separate models for every "object" (a group of related information). In this case, the obvious objects are books, book instances, and authors.

You might also want to use models to represent selection-list options (e.g., like a dropdown list of choices), rather than hard coding the choices into the website itself — this is recommended when all the options aren't known up front or may change. Obvious candidates for models, in this case, include the book genre (e.g., Science Fiction, French Poetry, etc.) and language (English, French, Japanese).

Once we've decided on our models and field, we need to think about the relationships. Django allows you to define relationships that are one to one (OneToOneField), one to many (ForeignKey) and many to many (ManyToManyField).

With that in mind, the UML association diagram below shows the models we'll define in this case (as boxes).

LocalLibrary Model UML with fixed Author multiplicity inside the Book class

We've created models for the book (the generic details of the book), book instance (status of specific physical copies of the book available in the system), and author. We have also decided to have a model for the genre so that values can be created/selected through the admin interface. We've decided not to have a model for the BookInstance:status — we've hardcoded the values (LOAN_STATUS) because we don't expect these to change. Within each of the boxes, you can see the model name, the field names, and types, and also the methods and their return types.

The diagram also shows the relationships between the models, including their multiplicities. The multiplicities are the numbers on the diagram showing the numbers (maximum and minimum) of each model that may be present in the relationship. For example, the connecting line between the boxes shows that Book and a Genre are related. The numbers close to the Genre model show that a book must have one or more Genres (as many as you like), while the numbers on the other end of the line next to the Book model show that a Genre can have zero or many associated books.

Note: The next section provides a basic primer explaining how models are defined and used. As you read it, consider how we will construct each of the models in the diagram above.

Model primer

This section provides a brief overview of how a model is defined and some of the more important fields and field arguments.

Model definition

Models are usually defined in an application's models.py file. They are implemented as subclasses of django.db.models.Model, and can include fields, methods and metadata. The code fragment below shows a "typical" model, named MyModelName:

python
from django.db import models
from django.urls import reverse

class MyModelName(models.Model):
    """A typical class defining a model, derived from the Model class."""

    # Fields
    my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')
    # …

    # Metadata
    class Meta:
        ordering = ['-my_field_name']

    # Methods
    def get_absolute_url(self):
        """Returns the URL to access a particular instance of MyModelName."""
        return reverse('model-detail-view', args=[str(self.id)])

    def __str__(self):
        """String for representing the MyModelName object (in Admin site etc.)."""
        return self.my_field_name

In the below sections we'll explore each of the features inside the model in detail:

Fields

A model can have an arbitrary number of fields, of any type — each one represents a column of data that we want to store in one of our database tables. Each database record (row) will consist of one of each field value. Let's look at the example seen below:

python
my_field_name = models.CharField(max_length=20, help_text='Enter field documentation')

Our above example has a single field called my_field_name, of type models.CharField — which means that this field will contain strings of alphanumeric characters. The field types are assigned using specific classes, which determine the type of record that is used to store the data in the database, along with validation criteria to be used when values are received from an HTML form (i.e., what constitutes a valid value). The field types can also take arguments that further specify how the field is stored or can be used. In this case we are giving our field two arguments:

  • max_length=20 — States that the maximum length of a value in this field is 20 characters.
  • help_text='Enter field documentation' — helpful text that may be displayed in a form to help users understand how the field is used.

The field name is used to refer to it in queries and templates. Fields also have a label, which is specified using the verbose_name argument (with a default value of None). If verbose_name is not set, the label is created from the field name by replacing any underscores with a space, and capitalizing the first letter (for example, the field my_field_name would have a default label of My field name when used in forms).

The order that fields are declared will affect their default order if a model is rendered in a form (e.g., in the Admin site), though this may be overridden.

Common field arguments

The following common arguments can be used when declaring many/most of the different field types:

  • help_text: Provides a text label for HTML forms (e.g., in the admin site), as described above.

  • verbose_name: A human-readable name for the field used in field labels. If not specified, Django will infer the default verbose name from the field name.

  • default: The default value for the field. This can be a value or a callable object, in which case the object will be called every time a new record is created.

  • null: If True, Django will store blank values as NULL in the database for fields where this is appropriate (a CharField will instead store an empty string). The default is False.

  • blank: If True, the field is allowed to be blank in your forms. The default is False, which means that Django's form validation will force you to enter a value. This is often used with null=True, because if you're going to allow blank values, you also want the database to be able to represent them appropriately.

  • choices: A group of choices for this field. If this is provided, the default corresponding form widget will be a select box with these choices instead of the standard text field.

  • unique: If True, ensures that the field value is unique across the database. This can be used to prevent duplication of fields that can't have the same values. The default is False.

  • primary_key: If True, sets the current field as the primary key for the model (A primary key is a special database column designated to uniquely identify all the different table records). If no field is specified as the primary key, Django will automatically add a field for this purpose. The type of auto-created primary key fields can be specified for each app in AppConfig.default_auto_field or globally in the DEFAULT_AUTO_FIELD setting.

    Note: Apps created using manage.py set the type of the primary key to a BigAutoField. You can see this in the local library catalog/apps.py file:

    python
    class CatalogConfig(AppConfig):
      default_auto_field = 'django.db.models.BigAutoField'
    

There are many other options — you can view the full list of field options here.

Common field types

The following list describes some of the more commonly used types of fields.

  • CharField is used to define short-to-mid sized fixed-length strings. You must specify the max_length of the data to be stored.
  • TextField is used for large arbitrary-length strings. You may specify a max_length for the field, but this is used only when the field is displayed in forms (it is not enforced at the database level).
  • IntegerField is a field for storing integer (whole number) values, and for validating entered values as integers in forms.
  • DateField and DateTimeField are used for storing/representing dates and date/time information (as Python datetime.date and datetime.datetime objects, respectively). These fields can additionally declare the (mutually exclusive) parameters auto_now=True (to set the field to the current date every time the model is saved), auto_now_add (to only set the date when the model is first created), and default (to set a default date that can be overridden by the user).
  • EmailField is used to store and validate email addresses.
  • FileField and ImageField are used to upload files and images respectively (the ImageField adds additional validation that the uploaded file is an image). These have parameters to define how and where the uploaded files are stored.
  • AutoField is a special type of IntegerField that automatically increments. A primary key of this type is automatically added to your model if you don't explicitly specify one.
  • ForeignKey is used to specify a one-to-many relationship to another database model (e.g., a car has one manufacturer, but a manufacturer can make many cars). The "one" side of the relationship is the model that contains the "key" (models containing a "foreign key" referring to that "key", are on the "many" side of such a relationship).
  • ManyToManyField is used to specify a many-to-many relationship (e.g., a book can have several genres, and each genre can contain several books). In our library app we will use these very similarly to ForeignKeys, but they can be used in more complicated ways to describe the relationships between groups. These have the parameter on_delete to define what happens when the associated record is deleted (e.g., a value of models.SET_NULL would set the value to NULL).

There are many other types of fields, including fields for different types of numbers (big integers, small integers, floats), booleans, URLs, slugs, unique ids, and other "time-related" information (duration, time, etc.). You can view the full list here.

Metadata

You can declare model-level metadata for your Model by declaring class Meta, as shown.

python
class Meta:
    ordering = ['-my_field_name']

One of the most useful features of this metadata is to control the default ordering of records returned when you query the model type. You do this by specifying the match order in a list of field names to the ordering attribute, as shown above. The ordering will depend on the type of field (character fields are sorted alphabetically, while date fields are sorted in chronological order). As shown above, you can prefix the field name with a minus symbol (-) to reverse the sorting order.

So as an example, if we chose to sort books like this by default:

python
ordering = ['title', '-publish_date']

the books would be sorted alphabetically by title, from A-Z, and then by publication date inside each title, from newest to oldest.

Another common attribute is verbose_name, a verbose name for the class in singular and plural form:

python
verbose_name = 'BetterName'

Class metadata can be used to create and apply new "access permissions" for the model (default permissions are applied automatically), allow ordering based on another field, define constraints on possible values of data that can be stored, or to declare that the class is "abstract" (a base class that you cannot create records for, and will instead be derived from to create other models).

Many of the other metadata options control what database must be used for the model and how the data is stored (these are really only useful if you need to map a model to an existing database).

The full list of metadata options are available here: Model metadata options (Django docs).

Methods

A model can also have methods.

Minimally, in every model you should define the standard Python class method __str__() to return a human-readable string for each object. This string is used to represent individual records in the administration site (and anywhere else you need to refer to a model instance). Often this will return a title or name field from the model.

python
def __str__(self):
    return self.my_field_name

Another common method to include in Django models is get_absolute_url(), which returns a URL for displaying individual model records on the website (if you define this method then Django will automatically add a "View on Site" button to the model's record editing screens in the Admin site). A typical pattern for get_absolute_url() is shown below.

python
def get_absolute_url(self):
    """Returns the URL to access a particular instance of the model."""
    return reverse('model-detail-view', args=[str(self.id)])

Note: Assuming you will use URLs like /my-application/my-model-name/2 to display individual records for your model (where "2" is the id for a particular record), you will need to create a URL mapper to pass the response and id to a "model detail view" (which will do the work required to display the record). The reverse() function above is able to "reverse" your URL mapper (in the above case named 'model-detail-view') in order to create a URL of the right format.

Of course to make this work you still have to write the URL mapping, view, and template!

You can also define any other methods you like, and call them from your code or templates (provided that they don't take any parameters).

Model management

Once you've defined your model classes you can use them to create, update, or delete records, and to run queries to get all records or particular subsets of records. We'll show you how to do that in the tutorial when we define our views, but here is a brief summary.

Creating and modifying records

To create a record you can define an instance of the model and then call save().

python
# Create a new record using the model's constructor.
record = MyModelName(my_field_name="Instance #1")

# Save the object into the database.
record.save()

Note: If you haven't declared any field as a primary_key, the new record will be given one automatically, with the field name id. You could query this field after saving the above record, and it would have a value of 1.

You can access the fields in this new record using the dot syntax, and change the values. You have to call save() to store modified values to the database.

python
# Access model field values using Python attributes.
print(record.id) # should return 1 for the first record.
print(record.my_field_name) # should print 'Instance #1'

# Change record by modifying the fields, then calling save().
record.my_field_name = "New Instance Name"
record.save()

Searching for records

You can search for records that match certain criteria using the model's objects attribute (provided by the base class).

Note: Explaining how to search for records using "abstract" model and field names can be a little confusing. In the discussion below, we'll refer to a Book model with title and genre fields, where genre is also a model with a single field name.

We can get all records for a model as a QuerySet, using objects.all(). The QuerySet is an iterable object, meaning that it contains a number of objects that we can iterate/loop through.

python
all_books = Book.objects.all()

Django's filter() method allows us to filter the returned QuerySet to match a specified text or numeric field against particular criteria. For example, to filter for books that contain "wild" in the title and then count them, we could do the following:

python
wild_books = Book.objects.filter(title__contains='wild')
number_wild_books = wild_books.count()

The fields to match and the type of match are defined in the filter parameter name, using the format: field_name__match_type (note the double underscore between title and contains above). Above we're filtering title with a case-sensitive match. There are many other types of matches you can do: icontains (case insensitive), iexact (case-insensitive exact match), exact (case-sensitive exact match) and in, gt (greater than), startswith, etc. The full list is here.

In some cases, you'll need to filter on a field that defines a one-to-many relationship to another model (e.g., a ForeignKey). In this case, you can "index" to fields within the related model with additional double underscores. So for example to filter for books with a specific genre pattern, you will have to index to the name through the genre field, as shown below:

python
# Will match on: Fiction, Science fiction, non-fiction etc.
books_containing_genre = Book.objects.filter(genre__name__icontains='fiction')

Note: You can use underscores (__) to navigate as many levels of relationships (ForeignKey/ManyToManyField) as you like. For example, a Book that had different types, defined using a further "cover" relationship might have a parameter name: type__cover__name__exact='hard'.

There is a lot more you can do with queries, including backwards searches from related models, chaining filters, returning a smaller set of values, etc. For more information, see Making queries (Django Docs).

Defining the LocalLibrary Models

In this section we will start defining the models for the library. Open models.py (in /django-locallibrary-tutorial/catalog/). The boilerplate at the top of the page imports the models module, which contains the model base class models.Model that our models will inherit from.

python
from django.db import models

# Create your models here.

Genre model

Copy the Genre model code shown below and paste it into the bottom of your models.py file. This model is used to store information about the book category — for example whether it is fiction or non-fiction, romance or military history, etc. As mentioned above, we've created the genre as a model rather than as free text or a selection list so that the possible values can be managed through the database rather than being hard coded.

python
from django.urls import reverse # Used in get_absolute_url() to get URL for specified ID

from django.db.models import UniqueConstraint # Constrains fields to unique values
from django.db.models.functions import Lower # Returns lower cased value of field

class Genre(models.Model):
    """Model representing a book genre."""
    name = models.CharField(
        max_length=200,
        unique=True,
        help_text="Enter a book genre (e.g. Science Fiction, French Poetry etc.)"
    )

    def __str__(self):
        """String for representing the Model object."""
        return self.name

    def get_absolute_url(self):
        """Returns the url to access a particular genre instance."""
        return reverse('genre-detail', args=[str(self.id)])

    class Meta:
        constraints = [
            UniqueConstraint(
                Lower('name'),
                name='genre_name_case_insensitive_unique',
                violation_error_message = "Genre already exists (case-insensitive match)"
            ),
        ]

The model has a single CharField field (name), which is used to describe the genre (this is limited to 200 characters and has some help_text). We've set this field to be unique (unique=True) because there should only be one record for each genre.

After the field, we declare a __str__() method, which returns the name of the genre defined by a particular record. No verbose name has been defined, so the field label will be Name when it is used in forms. Then we declare the get_absolute_url() method, which returns a URL that can be used to access a detail record for this model (for this to work, we will have to define a URL mapping that has the name genre-detail, and define an associated view and template).

Setting unique=True on the field above prevents genres being created with exactly the same name, but not variations such as "fantasy", "Fantasy", or even "FaNtAsY". The last part of the model definition uses a constraints option on the model's metadata to specify that the lower case of the value in the name field must be unique in the database, and display the violation_error_message string if it isn't. Here we don't need to do anything else, but you can define multiple constraints against a field or fields. For more information see the Constraints reference, including UniqueConstraint() (and Lower()).

Book model

Copy the Book model below and again paste it into the bottom of your file. The Book model represents all information about an available book in a general sense, but not a particular physical "instance" or "copy" available for loan.

The model uses a CharField to represent the book's title and isbn. For isbn, note how the first unnamed parameter explicitly sets the label as "ISBN" (otherwise, it would default to "Isbn"). We also set the parameter unique as True to ensure all books have a unique ISBN (the unique parameter makes the field value globally unique in a table). Unlike for the isbn (and the genre name), the title is not set to be unique, because it is possible for different books to have the same name. The model uses TextField for the summary, because this text may need to be quite long.

python
class Book(models.Model):
    """Model representing a book (but not a specific copy of a book)."""
    title = models.CharField(max_length=200)
    author = models.ForeignKey('Author', on_delete=models.RESTRICT, null=True)
    # Foreign Key used because book can only have one author, but authors can have multiple books.
    # Author as a string rather than object because it hasn't been declared yet in file.

    summary = models.TextField(
        max_length=1000, help_text="Enter a brief description of the book")
    isbn = models.CharField('ISBN', max_length=13,
                            unique=True,
                            help_text='13 Character <a href="https://www.isbn-international.org/content/what-isbn'
                                      '">ISBN number</a>')

    # ManyToManyField used because genre can contain many books. Books can cover many genres.
    # Genre class has already been defined so we can specify the object above.
    genre = models.ManyToManyField(
        Genre, help_text="Select a genre for this book")

    def __str__(self):
        """String for representing the Model object."""
        return self.title

    def get_absolute_url(self):
        """Returns the URL to access a detail record for this book."""
        return reverse('book-detail', args=[str(self.id)])

The genre is a ManyToManyField, so that a book can have multiple genres and a genre can have many books. The author is declared as ForeignKey, so each book will only have one author, but an author may have many books (in practice a book might have multiple authors, but not in this implementation!)

In both field types the related model class is declared as the first unnamed parameter using either the model class or a string containing the name of the related model. You must use the name of the model as a string if the associated class has not yet been defined in this file before it is referenced! The other parameters of interest in the author field are null=True, which allows the database to store a Null value if no author is selected, and on_delete=models.RESTRICT, which will prevent the book's associated author being deleted if it is referenced by any book.

Warning: By default on_delete=models.CASCADE, which means that if the author was deleted, this book would be deleted too! We use RESTRICT here, but we could also use PROTECT to prevent the author being deleted while any book uses it or SET_NULL to set the book's author to Null if the record is deleted.

The model also defines __str__(), using the book's title field to represent a Book record. The final method, get_absolute_url() returns a URL that can be used to access a detail record for this model (we will have to define a URL mapping that has the name book-detail, and define an associated view and template).

BookInstance model

Next, copy the BookInstance model (shown below) under the other models. The BookInstance represents a specific copy of a book that someone might borrow, and includes information about whether the copy is available or on what date it is expected back, "imprint" or version details, and a unique id for the book in the library.

Some of the fields and methods will now be familiar. The model uses:

  • ForeignKey to identify the associated Book (each book can have many copies, but a copy can only have one Book). The key specifies on_delete=models.RESTRICT to ensure that the Book cannot be deleted while referenced by a BookInstance.
  • CharField to represent the imprint (specific release) of the book.
python
import uuid # Required for unique book instances

class BookInstance(models.Model):

    """Model representing a specific copy of a book (i.e. that can be borrowed from the library)."""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4,
                          help_text="Unique ID for this particular book across whole library")
    book = models.ForeignKey('Book', on_delete=models.RESTRICT, null=True)
    imprint = models.CharField(max_length=200)
    due_back = models.DateField(null=True, blank=True)

    LOAN_STATUS = (
        ('m', 'Maintenance'),
        ('o', 'On loan'),
        ('a', 'Available'),
        ('r', 'Reserved'),
    )

    status = models.CharField(
        max_length=1,
        choices=LOAN_STATUS,
        blank=True,
        default='m',
        help_text='Book availability',
    )

    class Meta:
        ordering = ['due_back']

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.id} ({self.book.title})'

We additionally declare a few new types of field:

  • UUIDField is used for the id field to set it as the primary_key for this model. This type of field allocates a globally unique value for each instance (one for every book you can find in the library).
  • DateField is used for the due_back date (at which the book is expected to become available after being borrowed or in maintenance). This value can be blank or null (needed for when the book is available). The model metadata (Class Meta) uses this field to order records when they are returned in a query.
  • status is a CharField that defines a choice/selection list. As you can see, we define a tuple containing tuples of key-value pairs and pass it to the choices argument. The value in a key/value pair is a display value that a user can select, while the keys are the values that are actually saved if the option is selected. We've also set a default value of 'm' (maintenance) as books will initially be created unavailable before they are stocked on the shelves.

The method __str__() represents the BookInstance object using a combination of its unique id and the associated Book's title.

Note: A little Python:

  • Starting with Python 3.6, you can use the string interpolation syntax (also known as f-strings): f'{self.id} ({self.book.title})'.
  • In older versions of this tutorial, we were using a formatted string syntax, which is also a valid way of formatting strings in Python (e.g., '{0} ({1})'.format(self.id,self.book.title)).

Author model

Copy the Author model (shown below) underneath the existing code in models.py.

python
class Author(models.Model):
    """Model representing an author."""
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('Died', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']

    def get_absolute_url(self):
        """Returns the URL to access a particular author instance."""
        return reverse('author-detail', args=[str(self.id)])

    def __str__(self):
        """String for representing the Model object."""
        return f'{self.last_name}, {self.first_name}'

All of the fields/methods should now be familiar. The model defines an author as having a first name, last name, and dates of birth and death (both optional). It specifies that by default the __str__() returns the name in last name, first name order. The get_absolute_url() method reverses the author-detail URL mapping to get the URL for displaying an individual author.

Re-run the database migrations

All your models have now been created. Now re-run your database migrations to add them to your database.

bash
python3 manage.py makemigrations
python3 manage.py migrate

Language model — challenge

Imagine a local benefactor donates a number of new books written in another language (say, Farsi). The challenge is to work out how these would be best represented in our library website, and then to add them to the models.

Some things to consider:

  • Should "language" be associated with a Book, BookInstance, or some other object?
  • Should the different languages be represented using model, a free text field, or a hard-coded selection list?

After you've decided, add the field. You can see what we decided for our project on GitHub.

Don't forget that after a change to your model, you should again re-run your database migrations to add the changes.

bash
python3 manage.py makemigrations
python3 manage.py migrate

Summary

In this article we've learned how models are defined, and then used this information to design and implement appropriate models for the LocalLibrary website.

At this point we'll divert briefly from creating the site, and check out the Django Administration site. This site will allow us to add some data to the library, which we can then display using our (yet to be created) views and templates.

See also