Complete Assigned Readings

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

1. Whetting Your Appetite

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.

1. Whetting Your Appetite

If you do much work on computers, eventually you find that there’s some task you’d like to automate. For example, you may wish to perform a search-and-replace over a large number of text files, or rename and rearrange a bunch of photo files in a complicated way. Perhaps you’d like to write a small custom database, or a specialized GUI application, or a simple game.

If you’re a professional software developer, you may have to work with several C/C++/Java libraries but find the usual write/compile/test/re-compile cycle is too slow. Perhaps you’re writing a test suite for such a library and find writing the testing code a tedious task. Or maybe you’ve written a program that could use an extension language, and you don’t want to design and implement a whole new language for your application.

Python is just the language for you.

You could write a Unix shell script or Windows batch files for some of these tasks, but shell scripts are best at moving around files and changing text data, not well-suited for GUI applications or games. You could write a C/C++/Java program, but it can take a lot of development time to get even a first-draft program. Python is simpler to use, available on Windows, macOS, and Unix operating systems, and will help you get the job done more quickly.

Python is simple to use, but it is a real programming language, offering much more structure and support for large programs than shell scripts or batch files can offer. On the other hand, Python also offers much more error checking than C, and, being a very-high-level language, it has high-level data types built in, such as flexible arrays and dictionaries. Because of its more general data types Python is applicable to a much larger problem domain than Awk or even Perl, yet many things are at least as easy in Python as in those languages.

Python allows you to split your program into modules that can be reused in other Python programs. It comes with a large collection of standard modules that you can use as the basis of your programs — or as examples to start learning to program in Python. Some of these modules provide things like file I/O, system calls, sockets, and even interfaces to graphical user interface toolkits like Tk.

Python is an interpreted language, which can save you considerable time during program development because no compilation and linking is necessary. The interpreter can be used interactively, which makes it easy to experiment with features of the language, to write throw-away programs, or to test functions during bottom-up program development. It is also a handy desk calculator.

Python enables programs to be written compactly and readably. Programs written in Python are typically much shorter than equivalent C, C++, or Java programs, for several reasons:

  • the high-level data types allow you to express complex operations in a single statement;

  • statement grouping is done by indentation instead of beginning and ending brackets;

  • no variable or argument declarations are necessary.

Python is extensible: if you know how to program in C it is easy to add a new built-in function or module to the interpreter, either to perform critical operations at maximum speed, or to link Python programs to libraries that may only be available in binary form (such as a vendor-specific graphics library). Once you are really hooked, you can link the Python interpreter into an application written in C and use it as an extension or command language for that application.

By the way, the language is named after the BBC show “Monty Python’s Flying Circus” and has nothing to do with reptiles. Making references to Monty Python skits in documentation is not only allowed, it is encouraged!

Now that you are all excited about Python, you’ll want to examine it in some more detail. Since the best way to learn a language is to use it, the tutorial invites you to play with the Python interpreter as you read.

In the next chapter, the mechanics of using the interpreter are explained. This is rather mundane information, but essential for trying out the examples shown later.

The rest of the tutorial introduces various features of the Python language and system through examples, beginning with simple expressions, statements and data types, through functions and modules, and finally touching upon advanced concepts like exceptions and user-defined classes.

decimal — Decimal fixed-point and floating-point arithmetic

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.

decimal — Decimal fixed-point and floating-point arithmetic

Source code: Lib/decimal.py


The decimal module provides support for fast correctly rounded decimal floating-point arithmetic. It offers several advantages over the float datatype:

  • Decimal “is based on a floating-point model which was designed with people in mind, and necessarily has a paramount guiding principle – computers must provide an arithmetic that works in the same way as the arithmetic that people learn at school.” – excerpt from the decimal arithmetic specification.

  • Decimal numbers can be represented exactly. In contrast, numbers like 1.1 and 2.2 do not have exact representations in binary floating point. End users typically would not expect 1.1 + 2.2 to display as 3.3000000000000003 as it does with binary floating point.

  • The exactness carries over into arithmetic. In decimal floating point, 0.1 + 0.1 + 0.1 - 0.3 is exactly equal to zero. In binary floating point, the result is 5.5511151231257827e-017. While near to zero, the differences prevent reliable equality testing and differences can accumulate. For this reason, decimal is preferred in accounting applications which have strict equality invariants.

  • The decimal module incorporates a notion of significant places so that 1.30 + 1.20 is 2.50. The trailing zero is kept to indicate significance. This is the customary presentation for monetary applications. For multiplication, the “schoolbook” approach uses all the figures in the multiplicands. For instance, 1.3 * 1.2 gives 1.56 while 1.30 * 1.20 gives 1.5600.

  • Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem:

    >>> from decimal import *
    >>> getcontext().prec = 6
    >>> Decimal(1) / Decimal(7)
    Decimal('0.142857')
    >>> getcontext().prec = 28
    >>> Decimal(1) / Decimal(7)
    Decimal('0.1428571428571428571428571429')
    
  • Both binary and decimal floating point are implemented in terms of published standards. While the built-in float type exposes only a modest portion of its capabilities, the decimal module exposes all required parts of the standard. When needed, the programmer has full control over rounding and signal handling. This includes an option to enforce exact arithmetic by using exceptions to block any inexact operations.

  • The decimal module was designed to support “without prejudice, both exact unrounded decimal arithmetic (sometimes called fixed-point arithmetic) and rounded floating-point arithmetic.” – excerpt from the decimal arithmetic specification.

The module design is centered around three concepts: the decimal number, the context for arithmetic, and signals.

A decimal number is immutable. It has a sign, coefficient digits, and an exponent. To preserve significance, the coefficient digits do not truncate trailing zeros. Decimals also include special values such as Infinity, -Infinity, and NaN. The standard also differentiates -0 from +0.

The context for arithmetic is an environment specifying precision, rounding rules, limits on exponents, flags indicating the results of operations, and trap enablers which determine whether signals are treated as exceptions. Rounding options include ROUND_CEILING, ROUND_DOWN, ROUND_FLOOR, ROUND_HALF_DOWN, ROUND_HALF_EVEN, ROUND_HALF_UP, ROUND_UP, and ROUND_05UP.

Signals are groups of exceptional conditions arising during the course of computation. Depending on the needs of the application, signals may be ignored, considered as informational, or treated as exceptions. The signals in the decimal module are: Clamped, InvalidOperation, DivisionByZero, Inexact, Rounded, Subnormal, Overflow, Underflow and FloatOperation.

For each signal there is a flag and a trap enabler. When a signal is encountered, its flag is set to one, then, if the trap enabler is set to one, an exception is raised. Flags are sticky, so the user needs to reset them before monitoring a calculation.

See also

Quick-start tutorial

The usual start to using decimals is importing the module, viewing the current context with getcontext() and, if necessary, setting new values for precision, rounding, or enabled traps:

>>> from decimal import *
>>> getcontext()
Context(prec=28, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[Overflow, DivisionByZero,
        InvalidOperation])

>>> getcontext().prec = 7       # Set a new precision

Decimal instances can be constructed from integers, strings, floats, or tuples. Construction from an integer or a float performs an exact conversion of the value of that integer or float. Decimal numbers include special values such as NaN which stands for “Not a number”, positive and negative Infinity, and -0:

>>> getcontext().prec = 28
>>> Decimal(10)
Decimal('10')
>>> Decimal('3.14')
Decimal('3.14')
>>> Decimal(3.14)
Decimal('3.140000000000000124344978758017532527446746826171875')
>>> Decimal((0, (3, 1, 4), -2))
Decimal('3.14')
>>> Decimal(str(2.0 ** 0.5))
Decimal('1.4142135623730951')
>>> Decimal(2) ** Decimal('0.5')
Decimal('1.414213562373095048801688724')
>>> Decimal('NaN')
Decimal('NaN')
>>> Decimal('-Infinity')
Decimal('-Infinity')

If the FloatOperation signal is trapped, accidental mixing of decimals and floats in constructors or ordering comparisons raises an exception:

>>> c = getcontext()
>>> c.traps[FloatOperation] = True
>>> Decimal(3.14)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') < 3.7
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.FloatOperation: [<class 'decimal.FloatOperation'>]
>>> Decimal('3.5') == 3.5
True

Added in version 3.3.

The significance of a new Decimal is determined solely by the number of digits input. Context precision and rounding only come into play during arithmetic operations.

>>> getcontext().prec = 6
>>> Decimal('3.0')
Decimal('3.0')
>>> Decimal('3.1415926535')
Decimal('3.1415926535')
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85987')
>>> getcontext().rounding = ROUND_UP
>>> Decimal('3.1415926535') + Decimal('2.7182818285')
Decimal('5.85988')

If the internal limits of the C version are exceeded, constructing a decimal raises InvalidOperation:

>>> Decimal("1e9999999999999999999")
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
decimal.InvalidOperation: [<class 'decimal.InvalidOperation'>]

Changed in version 3.3.

Decimals interact well with much of the rest of Python. Here is a small decimal floating-point flying circus:

>>> data = list(map(Decimal, '1.34 1.87 3.45 2.35 1.00 0.03 9.25'.split()))
>>> max(data)
Decimal('9.25')
>>> min(data)
Decimal('0.03')
>>> sorted(data)
[Decimal('0.03'), Decimal('1.00'), Decimal('1.34'), Decimal('1.87'),
 Decimal('2.35'), Decimal('3.45'), Decimal('9.25')]
>>> sum(data)
Decimal('19.29')
>>> a,b,c = data[:3]
>>> str(a)
'1.34'
>>> float(a)
1.34
>>> round(a, 1)
Decimal('1.3')
>>> int(a)
1
>>> a * 5
Decimal('6.70')
>>> a * b
Decimal('2.5058')
>>> c % a
Decimal('0.77')

Decimals can be formatted (with format() built-in or f-strings) in fixed-point or scientific notation, using the same formatting syntax (see Format specification mini-language) as builtin float type:

>>> format(Decimal('2.675'), "f")
'2.675'
>>> format(Decimal('2.675'), ".2f")
'2.68'
>>> f"{Decimal('2.675'):.2f}"
'2.68'
>>> format(Decimal('2.675'), ".2e")
'2.68e+0'
>>> with localcontext() as ctx:
...     ctx.rounding = ROUND_DOWN
...     print(format(Decimal('2.675'), ".2f"))
...
2.67

And some mathematical functions are also available to Decimal:

>>> getcontext().prec = 28
>>> Decimal(2).sqrt()
Decimal('1.414213562373095048801688724')
>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal('10').ln()
Decimal('2.302585092994045684017991455')
>>> Decimal('10').log10()
Decimal('1')

The quantize() method rounds a number to a fixed exponent. This method is useful for monetary applications that often round results to a fixed number of places:

>>> Decimal('7.325').quantize(Decimal('.01'), rounding=ROUND_DOWN)
Decimal('7.32')
>>> Decimal('7.325').quantize(Decimal('1.'), rounding=ROUND_UP)
Decimal('8')

As shown above, the getcontext() function accesses the current context and allows the settings to be changed. This approach meets the needs of most applications.

For more advanced work, it may be useful to create alternate contexts using the Context() constructor. To make an alternate active, use the setcontext() function.

In accordance with the standard, the decimal module provides two ready to use standard contexts, BasicContext and ExtendedContext. The former is especially useful for debugging because many of the traps are enabled:

>>> myothercontext = Context(prec=60, rounding=ROUND_HALF_DOWN)
>>> setcontext(myothercontext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857142857142857142857142857142857142857142857142857142857')

>>> ExtendedContext
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[], traps=[])
>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(7)
Decimal('0.142857143')
>>> Decimal(42) / Decimal(0)
Decimal('Infinity')

>>> setcontext(BasicContext)
>>> Decimal(42) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#143>", line 1, in -toplevel-
    Decimal(42) / Decimal(0)
DivisionByZero: x / 0

Contexts also have signal flags for monitoring exceptional conditions encountered during computations. The flags remain set until explicitly cleared, so it is best to clear the flags before each set of monitored computations by using the clear_flags() method.

>>> setcontext(ExtendedContext)
>>> getcontext().clear_flags()
>>> Decimal(355) / Decimal(113)
Decimal('3.14159292')
>>> getcontext()
Context(prec=9, rounding=ROUND_HALF_EVEN, Emin=-999999, Emax=999999,
        capitals=1, clamp=0, flags=[Inexact, Rounded], traps=[])

The flags entry shows that the rational approximation to pi was rounded (digits beyond the context precision were thrown away) and that the result is inexact (some of the discarded digits were non-zero).

Individual traps are set using the dictionary in the traps attribute of a context:

>>> setcontext(ExtendedContext)
>>> Decimal(1) / Decimal(0)
Decimal('Infinity')
>>> getcontext().traps[DivisionByZero] = 1
>>> Decimal(1) / Decimal(0)
Traceback (most recent call last):
  File "<pyshell#112>", line 1, in -toplevel-
    Decimal(1) / Decimal(0)
DivisionByZero: x / 0

Most programs adjust the current context only once, at the beginning of the program. And, in many applications, data is converted to Decimal with a single cast inside a loop. With context set and decimals created, the bulk of the program manipulates the data no differently than with other Python numeric types.

Decimal objects

class decimal.Decimal(value='0', context=None)

Construct a new Decimal object based from value.

value can be an integer, string, tuple, float, or another Decimal object. If no value is given, returns Decimal('0'). If value is a string, it should conform to the decimal numeric string syntax after leading and trailing whitespace characters, as well as underscores throughout, are removed:

sign           ::=  '+' | '-'
digit          ::=  '0' | '1' | '2' | '3' | '4' | '5' | '6' | '7' | '8' | '9'
indicator      ::=  'e' | 'E'
digits         ::=  digit [digit]...
decimal-part   ::=  digits '.' [digits] | ['.'] digits
exponent-part  ::=  indicator [sign] digits
infinity       ::=  'Infinity' | 'Inf'
nan            ::=  'NaN' [digits] | 'sNaN' [digits]
numeric-value  ::=  decimal-part [exponent-part] | infinity
numeric-string ::=  [sign] numeric-value | [sign] nan

Other Unicode decimal digits are also permitted where digit appears above. These include decimal digits from various other alphabets (for example, Arabic-Indic and Devanāgarī digits) along with the fullwidth digits '\uff10' through '\uff19'. Case is not significant, so, for example, inf, Inf, INFINITY, and iNfINity are all acceptable spellings for positive infinity.

If value is a tuple, it should have three components, a sign (0 for positive or 1 for negative), a tuple of digits, and an integer exponent. For example, Decimal((0, (1, 4, 1, 4), -3)) returns Decimal('1.414').

If value is a float, the binary floating-point value is losslessly converted to its exact decimal equivalent. This conversion can often require 53 or more digits of precision. For example, Decimal(float('1.1')) converts to Decimal('1.100000000000000088817841970012523233890533447265625').

The context precision does not affect how many digits are stored. That is determined exclusively by the number of digits in value. For example, Decimal('3.00000') records all five zeros even if the context precision is only three.

The purpose of the context argument is determining what to do if value is a malformed string. If the context traps InvalidOperation, an exception is raised; otherwise, the constructor returns a new Decimal with the value of NaN.

Once constructed, Decimal objects are immutable.

Changed in version 3.2: The argument to the constructor is now permitted to be a float instance.

Changed in version 3.3: float arguments raise an exception if the FloatOperation trap is set. By default the trap is off.

Changed in version 3.6: Underscores are allowed for grouping, as with integral and floating-point literals in code.

Decimal floating-point objects share many properties with the other built-in numeric types such as float and int. All of the usual math operations and special methods apply. Likewise, decimal objects can be copied, pickled, printed, used as dictionary keys, used as set elements, compared, sorted, and coerced to another type (such as float or int).

There are some small differences between arithmetic on Decimal objects and arithmetic on integers and floats. When the remainder operator % is applied to Decimal objects, the sign of the result is the sign of the dividend rather than the sign of the divisor:

>>> (-7) % 4
1
>>> Decimal(-7) % Decimal(4)
Decimal('-3')

The integer division operator // behaves analogously, returning the integer part of the true quotient (truncating towards zero) rather than its floor, so as to preserve the usual identity x == (x // y) * y + x % y:

>>> -7 // 4
-2
>>> Decimal(-7) // Decimal(4)
Decimal('-1')

The % and // operators implement the remainder and divide-integer operations (respectively) as described in the specification.

Decimal objects cannot generally be combined with floats or instances of fractions.Fraction in arithmetic operations: an attempt to add a Decimal to a float, for example, will raise a TypeError. However, it is possible to use Python’s comparison operators to compare a Decimal instance x with another number y. This avoids confusing results when doing equality comparisons between numbers of different types.

Changed in version 3.2: Mixed-type comparisons between Decimal instances and other numeric types are now fully supported.

In addition to the standard numeric properties, decimal floating-point objects also have a number of specialized methods:

adjusted()

Return the adjusted exponent after shifting out the coefficient’s rightmost digits until only the lead digit remains: Decimal('321e+5').adjusted() returns seven. Used for determining the position of the most significant digit with respect to the decimal point.

as_integer_ratio()

Return a pair (n, d) of integers that represent the given Decimal instance as a fraction, in lowest terms and with a positive denominator:

>>> Decimal('-3.14').as_integer_ratio()
(-157, 50)

The conversion is exact. Raise OverflowError on infinities and ValueError on NaNs.

Added in version 3.6.

as_tuple()

Return a named tuple representation of the number: DecimalTuple(sign, digits, exponent).

canonical()

Return the canonical encoding of the argument. Currently, the encoding of a Decimal instance is always canonical, so this operation returns its argument unchanged.

compare(other, context=None)

Compare the values of two Decimal instances. compare() returns a Decimal instance, and if either operand is a NaN then the result is a NaN:

a or b is a NaN  ==> Decimal('NaN')
a < b            ==> Decimal('-1')
a == b           ==> Decimal('0')
a > b            ==> Decimal('1')
compare_signal(other, context=None)

This operation is identical to the compare() method, except that all NaNs signal. That is, if neither operand is a signaling NaN then any quiet NaN operand is treated as though it were a signaling NaN.

compare_total(other, context=None)

Compare two operands using their abstract representation rather than their numerical value. Similar to the compare() method, but the result gives a total ordering on Decimal instances. Two Decimal instances with the same numeric value but different representations compare unequal in this ordering:

>>> Decimal('12.0').compare_total(Decimal('12'))
Decimal('-1')

Quiet and signaling NaNs are also included in the total ordering. The result of this function is Decimal('0') if both operands have the same representation, Decimal('-1') if the first operand is lower in the total order than the second, and Decimal('1') if the first operand is higher in the total order than the second operand. See the specification for details of the total order.

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

compare_total_mag(other, context=None)

Compare two operands using their abstract representation rather than their value as in compare_total(), but ignoring the sign of each operand. x.compare_total_mag(y) is equivalent to x.copy_abs().compare_total(y.copy_abs()).

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

conjugate()

Just returns self, this method is only to comply with the Decimal Specification.

copy_abs()

Return the absolute value of the argument. This operation is unaffected by the context and is quiet: no flags are changed and no rounding is performed.

copy_negate()

Return the negation of the argument. This operation is unaffected by the context and is quiet: no flags are changed and no rounding is performed.

copy_sign(other, context=None)

Return a copy of the first operand with the sign set to be the same as the sign of the second operand. For example:

>>> Decimal('2.3').copy_sign(Decimal('-1.5'))
Decimal('-2.3')

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

exp(context=None)

Return the value of the (natural) exponential function e**x at the given number. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.

>>> Decimal(1).exp()
Decimal('2.718281828459045235360287471')
>>> Decimal(321).exp()
Decimal('2.561702493119680037517373933E+139')
classmethod from_float(f, /)

Alternative constructor that only accepts instances of float or int.

Note Decimal.from_float(0.1) is not the same as Decimal('0.1'). Since 0.1 is not exactly representable in binary floating point, the value is stored as the nearest representable value which is 0x1.999999999999ap-4. That equivalent value in decimal is 0.1000000000000000055511151231257827021181583404541015625.

Note

From Python 3.2 onwards, a Decimal instance can also be constructed directly from a float.

>>> Decimal.from_float(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_float(float('nan'))
Decimal('NaN')
>>> Decimal.from_float(float('inf'))
Decimal('Infinity')
>>> Decimal.from_float(float('-inf'))
Decimal('-Infinity')

Added in version 3.1.

classmethod from_number(number, /)

Alternative constructor that only accepts instances of float, int or Decimal, but not strings or tuples.

>>> Decimal.from_number(314)
Decimal('314')
>>> Decimal.from_number(0.1)
Decimal('0.1000000000000000055511151231257827021181583404541015625')
>>> Decimal.from_number(Decimal('3.14'))
Decimal('3.14')

Added in version 3.14.

fma(other, third, context=None)

Fused multiply-add. Return self*other+third with no rounding of the intermediate product self*other.

>>> Decimal(2).fma(3, 5)
Decimal('11')
is_canonical()

Return True if the argument is canonical and False otherwise. Currently, a Decimal instance is always canonical, so this operation always returns True.

is_finite()

Return True if the argument is a finite number, and False if the argument is an infinity or a NaN.

is_infinite()

Return True if the argument is either positive or negative infinity and False otherwise.

is_nan()

Return True if the argument is a (quiet or signaling) NaN and False otherwise.

is_normal(context=None)

Return True if the argument is a normal finite number. Return False if the argument is zero, subnormal, infinite or a NaN.

is_qnan()

Return True if the argument is a quiet NaN, and False otherwise.

is_signed()

Return True if the argument has a negative sign and False otherwise. Note that zeros and NaNs can both carry signs.

is_snan()

Return True if the argument is a signaling NaN and False otherwise.

is_subnormal(context=None)

Return True if the argument is subnormal, and False otherwise.

is_zero()

Return True if the argument is a (positive or negative) zero and False otherwise.

ln(context=None)

Return the natural (base e) logarithm of the operand. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.

log10(context=None)

Return the base ten logarithm of the operand. The result is correctly rounded using the ROUND_HALF_EVEN rounding mode.

logb(context=None)

For a nonzero number, return the adjusted exponent of its operand as a Decimal instance. If the operand is a zero then Decimal('-Infinity') is returned and the DivisionByZero flag is raised. If the operand is an infinity then Decimal('Infinity') is returned.

logical_and(other, context=None)

logical_and() is a logical operation which takes two logical operands (see Logical operands). The result is the digit-wise and of the two operands.

logical_invert(context=None)

logical_invert() is a logical operation. The result is the digit-wise inversion of the operand.

logical_or(other, context=None)

logical_or() is a logical operation which takes two logical operands (see Logical operands). The result is the digit-wise or of the two operands.

logical_xor(other, context=None)

logical_xor() is a logical operation which takes two logical operands (see Logical operands). The result is the digit-wise exclusive or of the two operands.

max(other, context=None)

Like max(self, other) except that the context rounding rule is applied before returning and that NaN values are either signaled or ignored (depending on the context and whether they are signaling or quiet).

max_mag(other, context=None)

Similar to the max() method, but the comparison is done using the absolute values of the operands.

min(other, context=None)

Like min(self, other) except that the context rounding rule is applied before returning and that NaN values are either signaled or ignored (depending on the context and whether they are signaling or quiet).

min_mag(other, context=None)

Similar to the min() method, but the comparison is done using the absolute values of the operands.

next_minus(context=None)

Return the largest number representable in the given context (or in the current thread’s context if no context is given) that is smaller than the given operand.

next_plus(context=None)

Return the smallest number representable in the given context (or in the current thread’s context if no context is given) that is larger than the given operand.

next_toward(other, context=None)

If the two operands are unequal, return the number closest to the first operand in the direction of the second operand. If both operands are numerically equal, return a copy of the first operand with the sign set to be the same as the sign of the second operand.

normalize(context=None)

Used for producing canonical values of an equivalence class within either the current context or the specified context.

This has the same semantics as the unary plus operation, except that if the final result is finite it is reduced to its simplest form, with all trailing zeros removed and its sign preserved. That is, while the coefficient is non-zero and a multiple of ten the coefficient is divided by ten and the exponent is incremented by 1. Otherwise (the coefficient is zero) the exponent is set to 0. In all cases the sign is unchanged.

For example, Decimal('32.100') and Decimal('0.321000e+2') both normalize to the equivalent value Decimal('32.1').

Note that rounding is applied before reducing to simplest form.

In the latest versions of the specification, this operation is also known as reduce.

number_class(context=None)

Return a string describing the class of the operand. The returned value is one of the following ten strings.

  • "-Infinity", indicating that the operand is negative infinity.

  • "-Normal", indicating that the operand is a negative normal number.

  • "-Subnormal", indicating that the operand is negative and subnormal.

  • "-Zero", indicating that the operand is a negative zero.

  • "+Zero", indicating that the operand is a positive zero.

  • "+Subnormal", indicating that the operand is positive and subnormal.

  • "+Normal", indicating that the operand is a positive normal number.

  • "+Infinity", indicating that the operand is positive infinity.

  • "NaN", indicating that the operand is a quiet NaN (Not a Number).

  • "sNaN", indicating that the operand is a signaling NaN.

quantize(exp, rounding=None, context=None)

Return a value equal to the first operand after rounding and having the exponent of the second operand.

>>> Decimal('1.41421356').quantize(Decimal('1.000'))
Decimal('1.414')

Unlike other operations, if the length of the coefficient after the quantize operation would be greater than precision, then an InvalidOperation is signaled. This guarantees that, unless there is an error condition, the quantized exponent is always equal to that of the right-hand operand.

Also unlike other operations, quantize never signals Underflow, even if the result is subnormal and inexact.

If the exponent of the second operand is larger than that of the first then rounding may be necessary. In this case, the rounding mode is determined by the rounding argument if given, else by the given context argument; if neither argument is given the rounding mode of the current thread’s context is used.

An error is returned whenever the resulting exponent is greater than Emax or less than Etiny().

radix()

Return Decimal(10), the radix (base) in which the Decimal class does all its arithmetic. Included for compatibility with the specification.

remainder_near(other, context=None)

Return the remainder from dividing self by other. This differs from self % other in that the sign of the remainder is chosen so as to minimize its absolute value. More precisely, the return value is self - n * other where n is the integer nearest to the exact value of self / other, and if two integers are equally near then the even one is chosen.

If the result is zero then its sign will be the sign of self.

>>> Decimal(18).remainder_near(Decimal(10))
Decimal('-2')
>>> Decimal(25).remainder_near(Decimal(10))
Decimal('5')
>>> Decimal(35).remainder_near(Decimal(10))
Decimal('-5')
rotate(other, context=None)

Return the result of rotating the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to rotate. If the second operand is positive then rotation is to the left; otherwise rotation is to the right. The coefficient of the first operand is padded on the left with zeros to length precision if necessary. The sign and exponent of the first operand are unchanged.

same_quantum(other, context=None)

Test whether self and other have the same exponent or whether both are NaN.

This operation is unaffected by context and is quiet: no flags are changed and no rounding is performed. As an exception, the C version may raise InvalidOperation if the second operand cannot be converted exactly.

scaleb(other, context=None)

Return the first operand with exponent adjusted by the second. Equivalently, return the first operand multiplied by 10**other. The second operand must be an integer.

shift(other, context=None)

Return the result of shifting the digits of the first operand by an amount specified by the second operand. The second operand must be an integer in the range -precision through precision. The absolute value of the second operand gives the number of places to shift. If the second operand is positive then the shift is to the left; otherwise the shift is to the right. Digits shifted into the coefficient are zeros. The sign and exponent of the first operand are unchanged.

sqrt(context=None)

Return the square root of the argument to full precision.

to_eng_string(context=None)

Convert to a string, using engineering notation if an exponent is needed.

Engineering notation has an exponent which is a multiple of 3. This can leave up to 3 digits to the left of the decimal place and may require the addition of either one or two trailing zeros.

For example, this converts Decimal('123E+1') to Decimal('1.23E+3').

to_integral(rounding=None, context=None)

Identical to the to_integral_value() method. The to_integral name has been kept for compatibility with older versions.

to_integral_exact(rounding=None, context=None)

Round to the nearest integer, signaling Inexact or Rounded as appropriate if rounding occurs. The rounding mode is determined by the rounding parameter if given, else by the given context. If neither parameter is given then the rounding mode of the current context is used.

to_integral_value(rounding=None, context=None)

Round to the nearest integer without signaling Inexact or Rounded. If given, applies rounding; otherwise, uses the rounding method in either the supplied context or the current context.

Decimal numbers can be rounded using the round() function:

round(number)
round(number, ndigits)

If ndigits is not given or None, returns the nearest int to number, rounding ties to even, and ignoring the rounding mode of the Decimal context. Raises OverflowError if number is an infinity or ValueError if it is a (quiet or signaling) NaN.

If ndigits is an int, the context’s rounding mode is respected and a Decimal representing number rounded to the nearest multiple of Decimal('1E-ndigits') is returned; in this case, round(number, ndigits) is equivalent to self.quantize(Decimal('1E-ndigits')). Returns Decimal('NaN') if number is a quiet NaN. Raises InvalidOperation if number is an infinity, a signaling NaN, or if the length of the coefficient after the quantize operation would be greater than the current context’s precision. In other words, for the non-corner cases:

  • if ndigits is positive, return number rounded to ndigits decimal places;

  • if ndigits is zero, return number rounded to the nearest integer;

  • if ndigits is negative, return number rounded to the nearest multiple of 10**abs(ndigits).

For example:

>>> from decimal import Decimal, getcontext, ROUND_DOWN
>>> getcontext().rounding = ROUND_DOWN
>>> round(Decimal('3.75'))     # context rounding ignored
4
>>> round(Decimal('3.5'))      # round-ties-to-even
4
>>> round(Decimal('3.75'), 0)  # uses the context rounding
Decimal('3')
>>> round(Decimal('3.75'), 1)
Decimal('3.7')
>>> round(Decimal('3.75'), -1)
Decimal('0E+1')

Logical operands

The logical_and(), logical_invert(), logical_or(), and logical_xor() methods expect their arguments to be logical operands. A logical operand is a Decimal instance whose exponent and sign are both zero, and whose digits are all either 0 or 1.

Context objects

Contexts are environments for arithmetic operations. They govern precision, set rules for rounding, determine which signals are treated as exceptions, and limit the range for exponents.

Each thread has its own current context which is accessed or changed using the getcontext() and setcontext() functions:

decimal.getcontext()

Return the current context for the active thread.

decimal.setcontext(c, /)

Set the current context for the active thread to c.

You can also use the with statement and the localcontext() function to temporarily change the active context.

decimal.localcontext(ctx=None, **kwargs)

Return a context manager that will set the current context for the active thread to a copy of ctx on entry to the with-statement and restore the previous context when exiting the with-statement. If no context is specified, a copy of the current context is used. The kwargs argument is used to set the attributes of the new context.

For example, the following code sets the current decimal precision to 42 places, performs a calculation, and then automatically restores the previous context:

from decimal import localcontext

with localcontext() as ctx:
    ctx.prec = 42   # Perform a high precision calculation
    s = calculate_something()
s = +s  # Round the final result back to the default precision

Using keyword arguments, the code would be the following:

from decimal import localcontext

with localcontext(prec=42) as ctx:
    s = calculate_something()
s = +s

Raises TypeError if kwargs supplies an attribute that Context doesn’t support. Raises either TypeError or ValueError if kwargs supplies an invalid value for an attribute.

Changed in version 3.11: localcontext() now supports setting context attributes through the use of keyword arguments.

decimal.IEEEContext(bits)

Return a context object initialized to the proper values for one of the IEEE interchange formats. The argument must be a multiple of 32 and less than IEEE_CONTEXT_MAX_BITS.

Added in version 3.14.

New contexts can also be created using the Context constructor described below. In addition, the module provides three pre-made contexts:

decimal.BasicContext

This is a standard context defined by the General Decimal Arithmetic Specification. Precision is set to nine. Rounding is set to ROUND_HALF_UP. All flags are cleared. All traps are enabled (treated as exceptions) except Inexact, Rounded, and Subnormal.

Because many of the traps are enabled, this context is useful for debugging.

decimal.ExtendedContext

This is a standard context defined by the General Decimal Arithmetic Specification. Precision is set to nine. Rounding is set to ROUND_HALF_EVEN. All flags are cleared. No traps are enabled (so that exceptions are not raised during computations).

Because the traps are disabled, this context is useful for applications that prefer to have result value of NaN or Infinity instead of raising exceptions. This allows an application to complete a run in the presence of conditions that would otherwise halt the program.

decimal.DefaultContext

This context is used by the Context constructor as a prototype for new contexts. Changing a field (such a precision) has the effect of changing the default for new contexts created by the Context constructor.

This context is most useful in multi-threaded environments. Changing one of the fields before threads are started has the effect of setting system-wide defaults. Changing the fields after threads have started is not recommended as it would require thread synchronization to prevent race conditions.

In single threaded environments, it is preferable to not use this context at all. Instead, simply create contexts explicitly as described below.

The default values are Context.prec=28, Context.rounding=ROUND_HALF_EVEN, and enabled traps for Overflow, InvalidOperation, and DivisionByZero.

In addition to the three supplied contexts, new contexts can be created with the Context constructor.

class decimal.Context(prec=None, rounding=None, Emin=None, Emax=None, capitals=None, clamp=None, flags=None, traps=None)

Creates a new context. If a field is not specified or is None, the default values are copied from the DefaultContext. If the flags field is not specified or is None, all flags are cleared.

prec

An integer in the range [1, MAX_PREC] that sets the precision for arithmetic operations in the context.

rounding

One of the constants listed in the section Rounding Modes.

traps
flags

Lists of any signals to be set. Generally, new contexts should only set traps and leave the flags clear.

Emin
Emax

Integers specifying the outer limits allowable for exponents. Emin must be in the range [MIN_EMIN, 0], Emax in the range [0, MAX_EMAX].

capitals

Either 0 or 1 (the default). If set to 1, exponents are printed with a capital E; otherwise, a lowercase e is used: Decimal('6.02e+23').

clamp

Either 0 (the default) or 1. If set to 1, the exponent e of a Decimal instance representable in this context is strictly limited to the range Emin - prec + 1 <= e <= Emax - prec + 1. If clamp is 0 then a weaker condition holds: the adjusted exponent of the Decimal instance is at most Emax. When clamp is 1, a large normal number will, where possible, have its exponent reduced and a corresponding number of zeros added to its coefficient, in order to fit the exponent constraints; this preserves the value of the number but loses information about significant trailing zeros. For example:

>>> Context(prec=6, Emax=999, clamp=1).create_decimal('1.23e999')
Decimal('1.23000E+999')

A clamp value of 1 allows compatibility with the fixed-width decimal interchange formats specified in IEEE 754.

The Context class defines several general purpose methods as well as a large number of methods for doing arithmetic directly in a given context. In addition, for each of the Decimal methods described above (with the exception of the adjusted() and as_tuple() methods) there is a corresponding Context method. For example, for a Context instance C and Decimal instance x, C.exp(x) is equivalent to x.exp(context=C). Each Context method accepts a Python integer (an instance of int) anywhere that a Decimal instance is accepted.

clear_flags()

Resets all of the flags to 0.

clear_traps()

Resets all of the traps to 0.

Added in version 3.3.

copy()

Return a duplicate of the context.

copy_decimal(num, /)

Return a copy of the Decimal instance num.

create_decimal(num='0', /)

Creates a new Decimal instance from num but using self as context. Unlike the Decimal constructor, the context precision, rounding method, flags, and traps are applied to the conversion.

This is useful because constants are often given to a greater precision than is needed by the application. Another benefit is that rounding immediately eliminates unintended effects from digits beyond the current precision. In the following example, using unrounded inputs means that adding zero to a sum can change the result:

>>> getcontext().prec = 3
>>> Decimal('3.4445') + Decimal('1.0023')
Decimal('4.45')
>>> Decimal('3.4445') + Decimal(0) + Decimal('1.0023')
Decimal('4.44')

This method implements the to-number operation of the IBM specification. If the argument is a string, no leading or trailing whitespace or underscores are permitted.

create_decimal_from_float(f, /)

Creates a new Decimal instance from a float f but rounding using self as the context. Unlike the Decimal.from_float() class method, the context precision, rounding method, flags, and traps are applied to the conversion.

>>> context = Context(prec=5, rounding=ROUND_DOWN)
>>> context.create_decimal_from_float(math.pi)
Decimal('3.1415')
>>> context = Context(prec=5, traps=[Inexact])
>>> context.create_decimal_from_float(math.pi)
Traceback (most recent call last):
    ...
decimal.Inexact: None

Added in version 3.1.

Etiny()

Returns a value equal to Emin - prec + 1 which is the minimum exponent value for subnormal results. When underflow occurs, the exponent is set to Etiny.

Etop()

Returns a value equal to Emax - prec + 1.

The usual approach to working with decimals is to create Decimal instances and then apply arithmetic operations which take place within the current context for the active thread. An alternative approach is to use context methods for calculating within a specific context. The methods are similar to those for the Decimal class and are only briefly recounted here.

abs(x, /)

Returns the absolute value of x.

add(x, y, /)

Return the sum of x and y.

canonical(x, /)

Returns the same Decimal object x.

compare(x, y, /)

Compares x and y numerically.

compare_signal(x, y, /)

Compares the values of the two operands numerically.

compare_total(x, y, /)

Compares two operands using their abstract representation.

compare_total_mag(x, y, /)

Compares two operands using their abstract representation, ignoring sign.

copy_abs(x, /)

Returns a copy of x with the sign set to 0.

copy_negate(x, /)

Returns a copy of x with the sign inverted.

copy_sign(x, y, /)

Copies the sign from y to x.

divide(x, y, /)

Return x divided by y.

divide_int(x, y, /)

Return x divided by y, truncated to an integer.

divmod(x, y, /)

Divides two numbers and returns the integer part of the result.

exp(x, /)

Returns e ** x.

fma(x, y, z, /)

Returns x multiplied by y, plus z.

is_canonical(x, /)

Returns True if x is canonical; otherwise returns False.

is_finite(x, /)

Returns True if x is finite; otherwise returns False.

is_infinite(x, /)

Returns True if x is infinite; otherwise returns False.

is_nan(x, /)

Returns True if x is a qNaN or sNaN; otherwise returns False.

is_normal(x, /)

Returns True if x is a normal number; otherwise returns False.

is_qnan(x, /)

Returns True if x is a quiet NaN; otherwise returns False.

is_signed(x, /)

Returns True if x is negative; otherwise returns False.

is_snan(x, /)

Returns True if x is a signaling NaN; otherwise returns False.

is_subnormal(x, /)

Returns True if x is subnormal; otherwise returns False.

is_zero(x, /)

Returns True if x is a zero; otherwise returns False.

ln(x, /)

Returns the natural (base e) logarithm of x.

log10(x, /)

Returns the base 10 logarithm of x.

logb(x, /)

Returns the exponent of the magnitude of the operand’s MSD.

logical_and(x, y, /)

Applies the logical operation and between each operand’s digits.

logical_invert(x, /)

Invert all the digits in x.

logical_or(x, y, /)

Applies the logical operation or between each operand’s digits.

logical_xor(x, y, /)

Applies the logical operation xor between each operand’s digits.

max(x, y, /)

Compares two values numerically and returns the maximum.

max_mag(x, y, /)

Compares the values numerically with their sign ignored.

min(x, y, /)

Compares two values numerically and returns the minimum.

min_mag(x, y, /)

Compares the values numerically with their sign ignored.

minus(x, /)

Minus corresponds to the unary prefix minus operator in Python.

multiply(x, y, /)

Return the product of x and y.

next_minus(x, /)

Returns the largest representable number smaller than x.

next_plus(x, /)

Returns the smallest representable number larger than x.

next_toward(x, y, /)

Returns the number closest to x, in direction towards y.

normalize(x, /)

Reduces x to its simplest form.

number_class(x, /)

Returns an indication of the class of x.

plus(x, /)

Plus corresponds to the unary prefix plus operator in Python. This operation applies the context precision and rounding, so it is not an identity operation.

power(x, y, modulo=None)

Return x to the power of y, reduced modulo modulo if given.

With two arguments, compute x**y. If x is negative then y must be integral. The result will be inexact unless y is integral and the result is finite and can be expressed exactly in ‘precision’ digits. The rounding mode of the context is used. Results are always correctly rounded in the Python version.

Decimal(0) ** Decimal(0) results in InvalidOperation, and if InvalidOperation is not trapped, then results in Decimal('NaN').

Changed in version 3.3: The C module computes power() in terms of the correctly rounded exp() and ln() functions. The result is well-defined but only “almost always correctly rounded”.

With three arguments, compute (x**y) % modulo. For the three argument form, the following restrictions on the arguments hold:

  • all three arguments must be integral

  • y must be nonnegative

  • at least one of x or y must be nonzero

  • modulo must be nonzero and have at most ‘precision’ digits

The value resulting from Context.power(x, y, modulo) is equal to the value that would be obtained by computing (x**y) % modulo with unbounded precision, but is computed more efficiently. The exponent of the result is zero, regardless of the exponents of x, y and modulo. The result is always exact.

quantize(x, y, /)

Returns a value equal to x (rounded), having the exponent of y.

radix()

Just returns 10, as this is Decimal, :)

remainder(x, y, /)

Returns the remainder from integer division.

The sign of the result, if non-zero, is the same as that of the original dividend.

remainder_near(x, y, /)

Returns x - y * n, where n is the integer nearest the exact value of x / y (if the result is 0 then its sign will be the sign of x).

rotate(x, y, /)

Returns a rotated copy of x, y times.

same_quantum(x, y, /)

Returns True if the two operands have the same exponent.

scaleb(x, y, /)

Returns the first operand after adding the second value its exp.

shift(x, y, /)

Returns a shifted copy of x, y times.

sqrt(x, /)

Square root of a non-negative number to context precision.

subtract(x, y, /)

Return the difference between x and y.

to_eng_string(x, /)

Convert to a string, using engineering notation if an exponent is needed.

Engineering notation has an exponent which is a multiple of 3. This can leave up to 3 digits to the left of the decimal place and may require the addition of either one or two trailing zeros.

to_integral_exact(x, /)

Rounds to an integer.

to_sci_string(x, /)

Converts a number to a string using scientific notation.

Constants

decimal.SPEC_VERSION

The highest version of the General Decimal Arithmetic Specification that this implementation complies with. See https://speleotrove.com/decimal/decarith.html for the specification.

Added in version 3.15.

The following constants are only relevant for the C module. They are also included in the pure Python version for compatibility.

32-bit

64-bit

decimal.MAX_PREC

425000000

999999999999999999

decimal.MAX_EMAX

425000000

999999999999999999

decimal.MIN_EMIN

-425000000

-999999999999999999

decimal.MIN_ETINY

-849999999

-1999999999999999997

decimal.IEEE_CONTEXT_MAX_BITS

256

512

decimal.HAVE_THREADS

The value is True. Deprecated, because Python now always has threads.

Deprecated since version 3.9.

decimal.HAVE_CONTEXTVAR

The default value is True. If Python is configured using the --without-decimal-contextvar option, the C version uses a thread-local rather than a coroutine-local context and the value is False. This is slightly faster in some nested context scenarios.

Added in version 3.8.3.

Rounding modes

decimal.ROUND_CEILING

Round towards Infinity.

decimal.ROUND_DOWN

Round towards zero.

decimal.ROUND_FLOOR

Round towards -Infinity.

decimal.ROUND_HALF_DOWN

Round to nearest with ties going towards zero.

decimal.ROUND_HALF_EVEN

Round to nearest with ties going to nearest even integer.

decimal.ROUND_HALF_UP

Round to nearest with ties going away from zero.

decimal.ROUND_UP

Round away from zero.

decimal.ROUND_05UP

Round away from zero if last digit after rounding towards zero would have been 0 or 5; otherwise round towards zero.

Signals

Signals represent conditions that arise during computation. Each corresponds to one context flag and one context trap enabler.

The context flag is set whenever the condition is encountered. After the computation, flags may be checked for informational purposes (for instance, to determine whether a computation was exact). After checking the flags, be sure to clear all flags before starting the next computation.

If the context’s trap enabler is set for the signal, then the condition causes a Python exception to be raised. For example, if the DivisionByZero trap is set, then a DivisionByZero exception is raised upon encountering the condition.

class decimal.Clamped

Altered an exponent to fit representation constraints.

Typically, clamping occurs when an exponent falls outside the context’s Emin and Emax limits. If possible, the exponent is reduced to fit by adding zeros to the coefficient.

class decimal.DecimalException

Base class for other signals and a subclass of ArithmeticError.

class decimal.DivisionByZero

Signals the division of a non-infinite number by zero.

Can occur with division, modulo division, or when raising a number to a negative power. If this signal is not trapped, returns Infinity or -Infinity with the sign determined by the inputs to the calculation.

class decimal.Inexact

Indicates that rounding occurred and the result is not exact.

Signals when non-zero digits were discarded during rounding. The rounded result is returned. The signal flag or trap is used to detect when results are inexact.

class decimal.InvalidOperation

An invalid operation was performed.

Indicates that an operation was requested that does not make sense. If not trapped, returns NaN. Possible causes include:

Infinity - Infinity
0 * Infinity
Infinity / Infinity
x % 0
Infinity % x
sqrt(-x) and x > 0
0 ** 0
x ** (non-integer)
x ** Infinity
class decimal.Overflow

Numerical overflow.

Indicates the exponent is larger than Context.Emax after rounding has occurred. If not trapped, the result depends on the rounding mode, either pulling inward to the largest representable finite number or rounding outward to Infinity. In either case, Inexact and Rounded are also signaled.

class decimal.Rounded

Rounding occurred though possibly no information was lost.

Signaled whenever rounding discards digits; even if those digits are zero (such as rounding 5.00 to 5.0). If not trapped, returns the result unchanged. This signal is used to detect loss of significant digits.

class decimal.Subnormal

Exponent was lower than Emin prior to rounding.

Occurs when an operation result is subnormal (the exponent is too small). If not trapped, returns the result unchanged.

class decimal.Underflow

Numerical underflow with result rounded to zero.

Occurs when a subnormal result is pushed to zero by rounding. Inexact and Subnormal are also signaled.

class decimal.FloatOperation

Enable stricter semantics for mixing floats and Decimals.

If the signal is not trapped (default), mixing floats and Decimals is permitted in the Decimal constructor, create_decimal() and all comparison operators. Both conversion and comparisons are exact. Any occurrence of a mixed operation is silently recorded by setting FloatOperation in the context flags. Explicit conversions with from_float() or create_decimal_from_float() do not set the flag.

Otherwise (the signal is trapped), only equality comparisons and explicit conversions are silent. All other mixed operations raise FloatOperation.

The following table summarizes the hierarchy of signals:

exceptions.ArithmeticError(exceptions.Exception)
    DecimalException
        Clamped
        DivisionByZero(DecimalException, exceptions.ZeroDivisionError)
        Inexact
            Overflow(Inexact, Rounded)
            Underflow(Inexact, Rounded, Subnormal)
        InvalidOperation
        Rounded
        Subnormal
        FloatOperation(DecimalException, exceptions.TypeError)

Floating-point notes

Mitigating round-off error with increased precision

The use of decimal floating point eliminates decimal representation error (making it possible to represent 0.1 exactly); however, some operations can still incur round-off error when non-zero digits exceed the fixed precision.

The effects of round-off error can be amplified by the addition or subtraction of nearly offsetting quantities resulting in loss of significance. Knuth provides two instructive examples where rounded floating-point arithmetic with insufficient precision causes the breakdown of the associative and distributive properties of addition:

# Examples from Seminumerical Algorithms, Section 4.2.2.
>>> from decimal import Decimal, getcontext
>>> getcontext().prec = 8

>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.5111111')
>>> u + (v + w)
Decimal('10')

>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.01')
>>> u * (v+w)
Decimal('0.0060000')

The decimal module makes it possible to restore the identities by expanding the precision sufficiently to avoid loss of significance:

>>> getcontext().prec = 20
>>> u, v, w = Decimal(11111113), Decimal(-11111111), Decimal('7.51111111')
>>> (u + v) + w
Decimal('9.51111111')
>>> u + (v + w)
Decimal('9.51111111')
>>>
>>> u, v, w = Decimal(20000), Decimal(-6), Decimal('6.0000003')
>>> (u*v) + (u*w)
Decimal('0.0060000')
>>> u * (v+w)
Decimal('0.0060000')

Special values

The number system for the decimal module provides special values including NaN, sNaN, -Infinity, Infinity, and two zeros, +0 and -0.

Infinities can be constructed directly with: Decimal('Infinity'). Also, they can arise from dividing by zero when the DivisionByZero signal is not trapped. Likewise, when the Overflow signal is not trapped, infinity can result from rounding beyond the limits of the largest representable number.

The infinities are signed (affine) and can be used in arithmetic operations where they get treated as very large, indeterminate numbers. For instance, adding a constant to infinity gives another infinite result.

Some operations are indeterminate and return NaN, or if the InvalidOperation signal is trapped, raise an exception. For example, 0/0 returns NaN which means “not a number”. This variety of NaN is quiet and, once created, will flow through other computations always resulting in another NaN. This behavior can be useful for a series of computations that occasionally have missing inputs — it allows the calculation to proceed while flagging specific results as invalid.

A variant is sNaN which signals rather than remaining quiet after every operation. This is a useful return value when an invalid result needs to interrupt a calculation for special handling.

The behavior of Python’s comparison operators can be a little surprising where a NaN is involved. A test for equality where one of the operands is a quiet or signaling NaN always returns False (even when doing Decimal('NaN')==Decimal('NaN')), while a test for inequality always returns True. An attempt to compare two Decimals using any of the <, <=, > or >= operators will raise the InvalidOperation signal if either operand is a NaN, and return False if this signal is not trapped. Note that the General Decimal Arithmetic specification does not specify the behavior of direct comparisons; these rules for comparisons involving a NaN were taken from the IEEE 854 standard (see Table 3 in section 5.7). To ensure strict standards-compliance, use the compare() and compare_signal() methods instead.

The signed zeros can result from calculations that underflow. They keep the sign that would have resulted if the calculation had been carried out to greater precision. Since their magnitude is zero, both positive and negative zeros are treated as equal and their sign is informational.

In addition to the two signed zeros which are distinct yet equal, there are various representations of zero with differing precisions yet equivalent in value. This takes a bit of getting used to. For an eye accustomed to normalized floating-point representations, it is not immediately obvious that the following calculation returns a value equal to zero:

>>> 1 / Decimal('Infinity')
Decimal('0E-1000026')

Working with threads

The getcontext() function accesses a different Context object for each thread. Having separate thread contexts means that threads may make changes (such as getcontext().prec=10) without interfering with other threads.

Likewise, the setcontext() function automatically assigns its target to the current thread.

If setcontext() has not been called before getcontext(), then getcontext() will automatically create a new context for use in the current thread. New context objects have default values set from the decimal.DefaultContext object.

The sys.flags.thread_inherit_context flag affects the context for new threads. If the flag is false, new threads will start with an empty context. In this case, getcontext() will create a new context object when called and use the default values from DefaultContext. If the flag is true, new threads will start with a copy of context from the caller of threading.Thread.start().

To control the defaults so that each thread will use the same values throughout the application, directly modify the DefaultContext object. This should be done before any threads are started so that there won’t be a race condition between threads calling getcontext(). For example:

# Set applicationwide defaults for all threads about to be launched
DefaultContext.prec = 12
DefaultContext.rounding = ROUND_DOWN
DefaultContext.traps = ExtendedContext.traps.copy()
DefaultContext.traps[InvalidOperation] = 1
setcontext(DefaultContext)

# Afterwards, the threads can be started
t1.start()
t2.start()
t3.start()
 . . .

Recipes

Here are a few recipes that serve as utility functions and that demonstrate ways to work with the Decimal class:

def moneyfmt(value, places=2, curr='', sep=',', dp='.',
             pos='', neg='-', trailneg=''):
    """Convert Decimal to a money formatted string.

    places:  required number of places after the decimal point
    curr:    optional currency symbol before the sign (may be blank)
    sep:     optional grouping separator (comma, period, space, or blank)
    dp:      decimal point indicator (comma or period)
             only specify as blank when places is zero
    pos:     optional sign for positive numbers: '+', space or blank
    neg:     optional sign for negative numbers: '-', '(', space or blank
    trailneg:optional trailing minus indicator:  '-', ')', space or blank

    >>> d = Decimal('-1234567.8901')
    >>> moneyfmt(d, curr='$')
    '-$1,234,567.89'
    >>> moneyfmt(d, places=0, sep='.', dp='', neg='', trailneg='-')
    '1.234.568-'
    >>> moneyfmt(d, curr='$', neg='(', trailneg=')')
    '($1,234,567.89)'
    >>> moneyfmt(Decimal(123456789), sep=' ')
    '123 456 789.00'
    >>> moneyfmt(Decimal('-0.02'), neg='<', trailneg='>')
    '<0.02>'

    """
    q = Decimal(10) ** -places      # 2 places --> '0.01'
    sign, digits, exp = value.quantize(q).as_tuple()
    result = []
    digits = list(map(str, digits))
    build, next = result.append, digits.pop
    if sign:
        build(trailneg)
    for i in range(places):
        build(next() if digits else '0')
    if places:
        build(dp)
    if not digits:
        build('0')
    i = 0
    while digits:
        build(next())
        i += 1
        if i == 3 and digits:
            i = 0
            build(sep)
    build(curr)
    build(neg if sign else pos)
    return ''.join(reversed(result))

def pi():
    """Compute Pi to the current precision.

    >>> print(pi())
    3.141592653589793238462643383

    """
    getcontext().prec += 2  # extra digits for intermediate steps
    three = Decimal(3)      # substitute "three=3.0" for regular floats
    lasts, t, s, n, na, d, da = 0, three, 3, 1, 0, 0, 24
    while s != lasts:
        lasts = s
        n, na = n+na, na+8
        d, da = d+da, da+32
        t = (t * n) / d
        s += t
    getcontext().prec -= 2
    return +s               # unary plus applies the new precision

def exp(x):
    """Return e raised to the power of x.  Result type matches input type.

    >>> print(exp(Decimal(1)))
    2.718281828459045235360287471
    >>> print(exp(Decimal(2)))
    7.389056098930650227230427461
    >>> print(exp(2.0))
    7.38905609893
    >>> print(exp(2+0j))
    (7.38905609893+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num = 0, 0, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 1
        fact *= i
        num *= x
        s += num / fact
    getcontext().prec -= 2
    return +s

def cos(x):
    """Return the cosine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(cos(Decimal('0.5')))
    0.8775825618903727161162815826
    >>> print(cos(0.5))
    0.87758256189
    >>> print(cos(0.5+0j))
    (0.87758256189+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 0, 0, 1, 1, 1, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

def sin(x):
    """Return the sine of x as measured in radians.

    The Taylor series approximation works best for a small value of x.
    For larger values, first compute x = x % (2 * pi).

    >>> print(sin(Decimal('0.5')))
    0.4794255386042030002732879352
    >>> print(sin(0.5))
    0.479425538604
    >>> print(sin(0.5+0j))
    (0.479425538604+0j)

    """
    getcontext().prec += 2
    i, lasts, s, fact, num, sign = 1, 0, x, 1, x, 1
    while s != lasts:
        lasts = s
        i += 2
        fact *= i * (i-1)
        num *= x * x
        sign *= -1
        s += num / fact * sign
    getcontext().prec -= 2
    return +s

Decimal FAQ

Q: It is cumbersome to type decimal.Decimal('1234.5'). Is there a way to minimize typing when using the interactive interpreter?

A: Some users abbreviate the constructor to just a single letter:

>>> D = decimal.Decimal
>>> D('1.23') + D('3.45')
Decimal('4.68')

Q: In a fixed-point application with two decimal places, some inputs have many places and need to be rounded. Others are not supposed to have excess digits and need to be validated. What methods should be used?

A: The quantize() method rounds to a fixed number of decimal places. If the Inexact trap is set, it is also useful for validation:

>>> TWOPLACES = Decimal(10) ** -2       # same as Decimal('0.01')
>>> # Round to two places
>>> Decimal('3.214').quantize(TWOPLACES)
Decimal('3.21')
>>> # Validate that a number does not exceed two places
>>> Decimal('3.21').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Decimal('3.21')
>>> Decimal('3.214').quantize(TWOPLACES, context=Context(traps=[Inexact]))
Traceback (most recent call last):
   ...
Inexact: None

Q: Once I have valid two place inputs, how do I maintain that invariant throughout an application?

A: Some operations like addition, subtraction, and multiplication by an integer will automatically preserve fixed point. Others operations, like division and non-integer multiplication, will change the number of decimal places and need to be followed-up with a quantize() step:

>>> a = Decimal('102.72')           # Initial fixed-point values
>>> b = Decimal('3.17')
>>> a + b                           # Addition preserves fixed-point
Decimal('105.89')
>>> a - b
Decimal('99.55')
>>> a * 42                          # So does integer multiplication
Decimal('4314.24')
>>> (a * b).quantize(TWOPLACES)     # Must quantize non-integer multiplication
Decimal('325.62')
>>> (b / a).quantize(TWOPLACES)     # And quantize division
Decimal('0.03')

In developing fixed-point applications, it is convenient to define functions to handle the quantize() step:

>>> def mul(x, y, fp=TWOPLACES):
...     return (x * y).quantize(fp)
...
>>> def div(x, y, fp=TWOPLACES):
...     return (x / y).quantize(fp)
>>> mul(a, b)                       # Automatically preserve fixed-point
Decimal('325.62')
>>> div(b, a)
Decimal('0.03')

Q: There are many ways to express the same value. The numbers 200, 200.000, 2E2, and .02E+4 all have the same value at various precisions. Is there a way to transform them to a single recognizable canonical value?

A: The normalize() method maps all equivalent values to a single representative:

>>> values = map(Decimal, '200 200.000 2E2 .02E+4'.split())
>>> [v.normalize() for v in values]
[Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2'), Decimal('2E+2')]

Q: When does rounding occur in a computation?

A: It occurs after the computation. The philosophy of the decimal specification is that numbers are considered exact and are created independent of the current context. They can even have greater precision than current context. Computations process with those exact inputs and then rounding (or other context operations) is applied to the result of the computation:

>>> getcontext().prec = 5
>>> pi = Decimal('3.1415926535')   # More than 5 digits
>>> pi                             # All digits are retained
Decimal('3.1415926535')
>>> pi + 0                         # Rounded after an addition
Decimal('3.1416')
>>> pi - Decimal('0.00005')        # Subtract unrounded numbers, then round
Decimal('3.1415')
>>> pi + 0 - Decimal('0.00005').   # Intermediate values are rounded
Decimal('3.1416')

Q: Some decimal values always print with exponential notation. Is there a way to get a non-exponential representation?

A: For some values, exponential notation is the only way to express the number of significant places in the coefficient. For example, expressing 5.0E+3 as 5000 keeps the value constant but cannot show the original’s two-place significance.

If an application does not care about tracking significance, it is easy to remove the exponent and trailing zeroes, losing significance, but keeping the value unchanged:

>>> def remove_exponent(d):
...     return d.quantize(Decimal(1)) if d == d.to_integral() else d.normalize()
>>> remove_exponent(Decimal('5E+3'))
Decimal('5000')

Q: Is there a way to convert a regular float to a Decimal?

A: Yes, any binary floating-point number can be exactly expressed as a Decimal though an exact conversion may take more precision than intuition would suggest:

>>> Decimal(math.pi)
Decimal('3.141592653589793115997963468544185161590576171875')

Q: Within a complex calculation, how can I make sure that I haven’t gotten a spurious result because of insufficient precision or rounding anomalies.

A: The decimal module makes it easy to test results. A best practice is to re-run calculations using greater precision and with various rounding modes. Widely differing results indicate insufficient precision, rounding mode issues, ill-conditioned inputs, or a numerically unstable algorithm.

Q: I noticed that context precision is applied to the results of operations but not to the inputs. Is there anything to watch out for when mixing values of different precisions?

A: Yes. The principle is that all values are considered to be exact and so is the arithmetic on those values. Only the results are rounded. The advantage for inputs is that “what you type is what you get”. A disadvantage is that the results can look odd if you forget that the inputs haven’t been rounded:

>>> getcontext().prec = 3
>>> Decimal('3.104') + Decimal('2.104')
Decimal('5.21')
>>> Decimal('3.104') + Decimal('0.000') + Decimal('2.104')
Decimal('5.20')

The solution is either to increase precision or to force rounding of inputs using the unary plus operation:

>>> getcontext().prec = 3
>>> +Decimal('1.23456789')      # unary plus triggers rounding
Decimal('1.23')

Alternatively, inputs can be rounded upon creation using the Context.create_decimal() method:

>>> Context(prec=5, rounding=ROUND_DOWN).create_decimal('1.2345678')
Decimal('1.2345')

Q: Is the CPython implementation fast for large numbers?

A: Yes. In the CPython and PyPy3 implementations, the C/CFFI versions of the decimal module integrate the high speed libmpdec library for arbitrary precision correctly rounded decimal floating-point arithmetic [1]. libmpdec uses Karatsuba multiplication for medium-sized numbers and the Number Theoretic Transform for very large numbers.

The context must be adapted for exact arbitrary precision arithmetic. Emin and Emax should always be set to the maximum values, clamp should always be 0 (the default). Setting prec requires some care.

The easiest approach for trying out bignum arithmetic is to use the maximum value for prec as well [2]:

>>> setcontext(Context(prec=MAX_PREC, Emax=MAX_EMAX, Emin=MIN_EMIN))
>>> x = Decimal(2) ** 256
>>> x / 128
Decimal('904625697166532776746648320380374280103671755200316906558262375061821325312')

For inexact results, MAX_PREC is far too large on 64-bit platforms and the available memory will be insufficient:

>>> Decimal(1) / 3
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
MemoryError

On systems with overallocation (e.g. Linux), a more sophisticated approach is to adjust prec to the amount of available RAM. Suppose that you have 8GB of RAM and expect 10 simultaneous operands using a maximum of 500MB each:

>>> import sys
>>>
>>> # Maximum number of digits for a single operand using 500MB in 8-byte words
>>> # with 19 digits per word (4-byte and 9 digits for the 32-bit build):
>>> maxdigits = 19 * ((500 * 1024**2) // 8)
>>>
>>> # Check that this works:
>>> c = Context(prec=maxdigits, Emax=MAX_EMAX, Emin=MIN_EMIN)
>>> c.traps[Inexact] = True
>>> setcontext(c)
>>>
>>> # Fill the available precision with nines:
>>> x = Decimal(0).logical_invert() * 9
>>> sys.getsizeof(x)
524288112
>>> x + 2
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  decimal.Inexact: [<class 'decimal.Inexact'>]

In general (and especially on systems without overallocation), it is recommended to estimate even tighter bounds and set the Inexact trap if all calculations are expected to be exact.

2 . 7 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.

2.7 Discussion and Exercises

Most of the data structures described in this chapter are folklore. They can be found in implementations dating back over 30 years. For example, implementations of stacks, queues, and deques, which generalize easily to the ArrayStack, ArrayQueue and ArrayDeque structures described here, are discussed by Knuth [46, Section 2.2.2].

Brodnik et al. [13] seem to have been the first to describe the RootishArrayStack and prove a $ \sqrt{n}$ lower-bound like that in Section 2.6.2. They also present a different structure that uses a more sophisticated choice of block sizes in order to avoid computing square roots in the $ \ensuremath{\mathrm{i2b}(\ensuremath{\mathit{i}})}$ method. Within their scheme, the block containing $ \ensuremath{\ensuremath{\mathit{i}}}$ is block $ \lfloor\log (\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1)\rfloor$, which is simply the index of the leading 1 bit in the binary representation of $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+1$. Some computer architectures provide an instruction for computing the index of the leading 1-bit in an integer.

A structure related to the RootishArrayStack is the two-level tiered-vector of Goodrich and Kloss [35]. This structure supports the $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operations in constant time and $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ in $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$ time. These running times are similar to what can be achieved with the more careful implementation of a RootishArrayStack discussed in Exercise 2.10.

Exercise 2..1   The List method $ \ensuremath{\mathrm{add\_all}(\ensuremath{\mathit{i}},\ensuremath{\mathit{c}})}$ inserts all elements of the Collection $ \ensuremath{\ensuremath{\mathit{c}}}$ into the list at position $ \ensuremath{\ensuremath{\mathit{i}}}$. (The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ method is a special case where $ \ensuremath{\ensuremath{\ensuremath{\mathit{c}}}}=\{\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\}$.) Explain why, for the data structures in this chapter, it is not efficient to implement $ \ensuremath{\mathrm{add\_all}(\ensuremath{\mathit{i}},\ensuremath{\mathit{c}})}$ by repeated calls to $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$. Design and implement a more efficient implementation.

Exercise 2..2   Design and implement a RandomQueue. This is an implementation of the Queue interface in which the $ \ensuremath{\mathrm{remove}()}$ operation removes an element that is chosen uniformly at random among all the elements currently in the queue. (Think of a RandomQueue as a bag in which we can add elements or reach in and blindly remove some random element.) The $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}()}$ operations in a RandomQueue should run in constant time per operation.

Exercise 2..3   Design and implement a Treque (triple-ended queue). This is a List implementation in which $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ run in constant time and $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ run in time

$\displaystyle O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}, \ens...
...{n}}}}/2-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\vert\}) \enspace .
$

In other words, modifications are fast if they are near either end or near the middle of the list.

Exercise 2..4   Implement a method $ \ensuremath{\mathrm{rotate}(\ensuremath{\mathit{a}},\ensuremath{\mathit{r}})}$ that ``rotates'' the array $ \ensuremath{\ensuremath{\mathit{a}}}$ so that $ \ensuremath{\ensuremath{\mathit{a}}[\ensuremath{\mathit{i}}]}$ moves to $ \ensuremath{\ensuremath{\ensuremath{\mathit{a}}}}[(\ensuremath{\ensuremath{\en...
...r}}}})\bmod \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}]$, for all $ \ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\in\{0,\ldots,\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}}\}$.

Exercise 2..5   Implement a method $ \ensuremath{\mathrm{rotate}(\ensuremath{\mathit{r}})}$ that ``rotates'' a List so that list item $ \ensuremath{\ensuremath{\mathit{i}}}$ becomes list item $ (\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}+\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}})\bmod \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$. When run on an ArrayDeque, or a DualArrayDeque, $ \ensuremath{\mathrm{rotate}(\ensuremath{\mathit{r}})}$ should run in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}\})$ time.

Exercise 2..6   This exercise is left out of the pseudocode edition.

Exercise 2..7   Modify the ArrayDeque implementation so that it does not use the $ \bmod $ operator (which is expensive on some systems). Instead, it should make use of the fact that, if $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{a}})}$ is a power of 2, then

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{k}}\bmod \mathrm{leng...
...{\mathit{k}} \wedge (\mathrm{length}(\ensuremath{\mathit{a}})-1)}} \enspace .
$

(Here, $ \wedge $ is the bitwise-and operator.)

Exercise 2..8   Design and implement a variant of ArrayDeque that does not do any modular arithmetic at all. Instead, all the data sits in a consecutive block, in order, inside an array. When the data overruns the beginning or the end of this array, a modified $ \ensuremath{\mathrm{rebuild}()}$ operation is performed. The amortized cost of all operations should be the same as in an ArrayDeque.

Hint: Getting this to work is really all about how you implement the $ \ensuremath{\mathrm{rebuild}()}$ operation. You would like $ \ensuremath{\mathrm{rebuild}()}$ to put the data structure into a state where the data cannot run off either end until at least $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/2$ operations have been performed.

Test the performance of your implementation against the ArrayDeque. Optimize your implementation (by using $ \ensuremath{\mathrm{System}.\mathrm{arraycopy}(\ensuremath{\mathit{a}},\ensure...
...t{i}},\ensuremath{\mathit{b}},\ensuremath{\mathit{i}},\ensuremath{\mathit{n}})}$) and see if you can get it to outperform the ArrayDeque implementation.

Exercise 2..9   Design and implement a version of a RootishArrayStack that has only $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$ wasted space, but that can perform $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operations in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\ensuremath{\ensur...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time.

Exercise 2..10   Design and implement a version of a RootishArrayStack that has only $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$ wasted space, but that can perform $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operations in $ O(1+\min\{\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}},\ensuremath...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time. (For an idea on how to do this, see Section 3.3.)

Exercise 2..11   Design and implement a version of a RootishArrayStack that has only $ O(\sqrt{\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}})$ wasted space, but that can perform $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ operations in $ O(1+\min\{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}},\sqrt {\ensuremath...
...{\ensuremath{\mathit{n}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}\})$ time. (See Section 3.3 for ideas on how to achieve this.)

Exercise 2..12   Design and implement a CubishArrayStack. This three level structure implements the List interface using $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}^{2/3})$ wasted space. In this structure, $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ and $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ take constant time; while $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ take $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}^{1/3})$ amortized time.

opendatastructures.org

5 . 1 ChainedHashTable: Hashing with Chaining

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


5.1 ChainedHashTable: Hashing with Chaining

A ChainedHashTable data structure uses hashing with chaining to store data as an array, $ \ensuremath{\ensuremath{\mathit{t}}}$, of lists. An integer, $ \ensuremath{\ensuremath{\mathit{n}}}$, keeps track of the total number of items in all lists (see Figure 5.1):
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{initialize}(...
...th{\ensuremath{\mathit{n}} \gets \ensuremath{0}}\\
\end{flushleft}\end{leftbar}

Figure 5.1: An example of a ChainedHashTable with $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}=14$ and $ \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}=16$. In this example $ \ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}=6$
\includegraphics[width=\textwidth ]{figs-python/chainedhashtable}
The hash value of a data item $ \ensuremath{\ensuremath{\mathit{x}}}$, denoted $ \ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}$ is a value in the range $ \{0,\ldots,\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}-1\}$. All items with hash value $ \ensuremath{\ensuremath{\mathit{i}}}$ are stored in the list at $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$. To ensure that lists don't get too long, we maintain the invariant

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \le \ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}
$

so that the average number of elements stored in one of these lists is $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}} \le 1$.

To add an element, $ \ensuremath{\ensuremath{\mathit{x}}}$, to the hash table, we first check if the length of $ \ensuremath{\ensuremath{\mathit{t}}}$ needs to be increased and, if so, we grow $ \ensuremath{\ensuremath{\mathit{t}}}$. With this out of the way we hash $ \ensuremath{\ensuremath{\mathit{x}}}$ to get an integer, $ \ensuremath{\ensuremath{\mathit{i}}}$, in the range $ \{0,\ldots,\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}-1\}$, and we append $ \ensuremath{\ensuremath{\mathit{x}}}$ to the list $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{add}(\ensure...
...return}} \ensuremath{\ensuremath{\mathit{true}}}\\
\end{flushleft}\end{leftbar}
Growing the table, if necessary, involves doubling the length of $ \ensuremath{\ensuremath{\mathit{t}}}$ and reinserting all elements into the new table. This strategy is exactly the same as the one used in the implementation of ArrayStack and the same result applies: The cost of growing is only constant when amortized over a sequence of insertions (see Lemma 2.1 on page [*]).

Besides growing, the only other work done when adding a new value $ \ensuremath{\ensuremath{\mathit{x}}}$ to a ChainedHashTable involves appending $ \ensuremath{\ensuremath{\mathit{x}}}$ to the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$. For any of the list implementations described in Chapters 2 or 3, this takes only constant time.

To remove an element, $ \ensuremath{\ensuremath{\mathit{x}}}$, from the hash table, we iterate over the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$ until we find $ \ensuremath{\ensuremath{\mathit{x}}}$ so that we can remove it:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{remove}(\ens...
...\color{black} \textbf{return}} \ensuremath{nil} \\
\end{flushleft}\end{leftbar}
This takes $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}})$ time, where $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{i}}}}}$ denotes the length of the list stored at $ \ensuremath{\ensuremath{\mathit{t}}[\ensuremath{\mathit{i}}]}$.

Searching for the element $ \ensuremath{\ensuremath{\mathit{x}}}$ in a hash table is similar. We perform a linear search on the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$:
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{find}(\ensur...
...{return}} \ensuremath{\ensuremath{\mathit{nil}}}\\
\end{flushleft}\end{leftbar}
Again, this takes time proportional to the length of the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$.

The performance of a hash table depends critically on the choice of the hash function. A good hash function will spread the elements evenly among the $ \ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}$ lists, so that the expected size of the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$ is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}/\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})})} = O(1)$. On the other hand, a bad hash function will hash all values (including $ \ensuremath{\ensuremath{\mathit{x}}}$) to the same table location, in which case the size of the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$ will be $ \ensuremath{\ensuremath{\mathit{n}}}$. In the next section we describe a good hash function.


5.1.1 Multiplicative Hashing

Multiplicative hashing is an efficient method of generating hash values based on modular arithmetic (discussed in Section 2.3) and integer division. It uses the $ \ddiv $ operator, which calculates the integral part of a quotient, while discarding the remainder. Formally, for any integers $ a\ge 0$ and $ b\ge 1$, $ a\ddiv b = \lfloor
a/b\rfloor$.

In multiplicative hashing, we use a hash table of size $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ for some integer $ \ensuremath{\ensuremath{\mathit{d}}}$ (called the dimension). The formula for hashing an integer $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\in\{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$ is

$\displaystyle \ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}} ...
...th{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}} \enspace .
$

Here, $ \ensuremath{\ensuremath{\mathit{z}}}$ is a randomly chosen odd integer in $ \{1,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$. This hash function can be realized very efficiently by observing that, by default, operations on integers are already done modulo $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ where $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$ is the number of bits in an integer.5.1 (See Figure 5.2.) Furthermore, integer division by $ 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ is equivalent to dropping the rightmost $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$ bits in a binary representation (which is implemented by shifting the bits right by $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$ using the $ \ensuremath{\gg}$ operator).
\begin{leftbar}
\begin{flushleft}
\hspace*{1em} \ensuremath{\mathrm{hash}(\ensur...
...ensuremath{\mathit{w}}-\ensuremath{\mathit{d}})}\\
\end{flushleft}\end{leftbar}

Figure 5.2: The operation of the multiplicative hash function with $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}=32$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}=8$.
\begin{figure}\begin{center}
\resizebox{.98\textwidth}{!}{
\setlength{\arrayru...
... \end{tabular}}
\setlength{\arrayrulewidth}{.4pt}
\end{center}
\end{figure}

The following lemma, whose proof is deferred until later in this section, shows that multiplicative hashing does a good job of avoiding collisions:

Lemma 5..1   Let $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{y}}}$ be any two values in $ \{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$ with $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\neq \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}$. Then $ \Pr\{\ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}=\ensurem...
...th{\mathit{y}})}}\} \le 2/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$.

With Lemma 5.1, the performance of $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ are easy to analyze:

Lemma 5..2   For any data value $ \ensuremath{\ensuremath{\mathit{x}}}$, the expected length of the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$ is at most $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}} + 2$, where $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}}$ is the number of occurrences of $ \ensuremath{\ensuremath{\mathit{x}}}$ in the hash table.

Proof. Let $ S$ be the (multi-)set of elements stored in the hash table that are not equal to $ \ensuremath{\ensuremath{\mathit{x}}}$. For an element $ \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}\in S$, define the indicator variable

$\displaystyle I_{\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}} = \left\{\b...
...h}(\ensuremath{\mathit{y}})}}$} \\
0 & \mbox{otherwise}
\end{array}\right.
$

and notice that, by Lemma 5.1, $ \mathrm{E}[I_{\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}}] \le
2/2^{\e...
...hit{d}}}}}=2/\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}$. The expected length of the list $ \ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})]}$ is given by
$\displaystyle \mathrm{E}\left[\ensuremath{\ensuremath{\ensuremath{\mathit{t}}[\mathrm{hash}(\ensuremath{\mathit{x}})].\mathrm{size}()}}\right]$ $\displaystyle =$ $\displaystyle \mathrm{E}\left[\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}...
...mathit{y}}}}\in S} I_{\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}}\right]$  
  $\displaystyle =$ $\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\e...
...{y}}}}\in S} \mathrm{E}[I_{\ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}} ]$  
  $\displaystyle \le$ $\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\e...
...}}}}\in S} 2/\ensuremath{\ensuremath{\mathrm{length}(\ensuremath{\mathit{t}})}}$  
  $\displaystyle \le$ $\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\e...
...uremath{\mathit{y}}}}\in S} 2/\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$  
  $\displaystyle \le$ $\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\e...
...{\ensuremath{\mathit{x}}}}})2/\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}$  
  $\displaystyle \le$ $\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}} + 2 \enspace ,$  

as required. $ \qedsymbol$

Now, we want to prove Lemma 5.1, but first we need a result from number theory. In the following proof, we use the notation $ (b_r,\ldots,b_0)_2$ to denote $ \sum_{i=0}^r b_i2^i$, where each $ b_i$ is a bit, either 0 or 1. In other words, $ (b_r,\ldots,b_0)_2$ is the integer whose binary representation is given by $ b_r,\ldots,b_0$. We use $ \star$ to denote a bit of unknown value.

Lemma 5..3   Let $ S$ be the set of odd integers in $ \{1,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$; let $ q$ and $ i$ be any two elements in $ S$. Then there is exactly one value $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}\in S$ such that $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}q\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} = i$.

Proof. Since the number of choices for $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}$ and $ i$ is the same, it is sufficient to prove that there is at most one value $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}\in S$ that satisfies $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}q\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} = i$.

Suppose, for the sake of contradiction, that there are two such values $ \ensuremath{\ensuremath{\mathit{z}}}$ and $ \ensuremath{z}'$, with $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}>\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}'$. Then

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}q\bmod 2^{\ensur...
...athit{z}}}}'q \bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} = i
$

So

$\displaystyle (\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\e...
...thit{z}}}}')q\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}} = 0
$

But this means that

$\displaystyle (\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\e...
...math{\mathit{z}}}}')q = k 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ (5.1)

for some integer $ k$. Thinking in terms of binary numbers, we have

$\displaystyle (\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\e...
...0,\ldots,0}_{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}})_2 \enspace ,
$

so that the $ \ensuremath{\ensuremath{\mathit{w}}}$ trailing bits in the binary representation of $ (\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}')q$ are all 0's.

Furthermore $ k\neq 0$, since $ q\neq 0$ and $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}'\neq 0$. Since $ q$ is odd, it has no trailing 0's in its binary representation:

$\displaystyle q = (\star,\ldots,\star,1)_2 \enspace .
$

Since $ \vert\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\ensuremath...
...ath{\mathit{z}}}}'\vert < 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$, $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}'$ has fewer than $ \ensuremath{\ensuremath{\mathit{w}}}$ trailing 0's in its binary representation:

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\en...
...\ldots,0}_{<\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}})_2
\enspace .
$

Therefore, the product $ (\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}')q$ has fewer than $ \ensuremath{\ensuremath{\mathit{w}}}$ trailing 0's in its binary representation:

$\displaystyle (\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\e...
...ldots,0}_{<\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}})_2
\enspace .
$

Therefore $ (\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}')q$ cannot satisfy (5.1), yielding a contradiction and completing the proof. $ \qedsymbol$

The utility of Lemma 5.3 comes from the following observation: If $ \ensuremath{\ensuremath{\mathit{z}}}$ is chosen uniformly at random from $ S$, then $ \ensuremath{\ensuremath{\mathit{zt}}}$ is uniformly distributed over $ S$. In the following proof, it helps to think of the binary representation of $ \ensuremath{\ensuremath{\mathit{z}}}$, which consists of $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1$ random bits followed by a 1.

Proof. [Proof of Lemma 5.1] First we note that the condition $ \ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{x}})}}=\ensuremath{\ensuremath{\mathrm{hash}(\ensuremath{\mathit{y}})}}$ is equivalent to the statement ``the highest-order $ \ensuremath{\ensuremath{\mathit{d}}}$ bits of $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}} \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\bmod2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ and the highest-order $ \ensuremath{\ensuremath{\mathit{d}}}$ bits of $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}} \ensuremath{\ensuremath{\ensuremath{\mathit{y}}}}\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ are the same.'' A necessary condition of that statement is that the highest-order $ \ensuremath{\ensuremath{\mathit{d}}}$ bits in the binary representation of $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\ensuremath{\ens...
...emath{\mathit{y}}}})\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ are either all 0's or all 1's. That is,

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\en...
...\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}})_2$ (5.2)

when $ \ensuremath{\ensuremath{\ensuremath{\mathit{zx}}}}\bmod 2^{\ensuremath{\ensure...
...emath{\mathit{zy}}}}\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ or

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\en...
...{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}})_2 \enspace .$ (5.3)

when $ \ensuremath{\ensuremath{\ensuremath{\mathit{zx}}}}\bmod 2^{\ensuremath{\ensure...
...emath{\mathit{zy}}}}\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$. Therefore, we only have to bound the probability that $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\ensuremath{\ens...
...emath{\mathit{y}}}})\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ looks like (5.2) or (5.3).

Let $ q$ be the unique odd integer such that $ (\ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}-\ensuremath{\ensuremath{\en...
...\mathit{y}}}})\bmod
2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}=q2^r$ for some integer $ r\ge 0$. By Lemma 5.3, the binary representation of $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}q\bmod
2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ has $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1$ random bits, followed by a 1:

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}q\bmod 2^{\ensur...
...}-1},\ldots,b_{1}}_{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-1},1)_2
$

Therefore, the binary representation of $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\ensuremath{\ens...
...th{\mathit{z}}}}q2^r\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ has $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-r-1$ random bits, followed by a 1, followed by $ r$ 0's:

$\displaystyle \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\en...
...\ensuremath{\ensuremath{\mathit{w}}}}-r-1},1,\underbrace{0,0,\ldots,0}_{r})_2
$

We can now finish the proof: If $ r > \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$, then the $ \ensuremath{\ensuremath{\mathit{d}}}$ higher order bits of $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\ensuremath{\ens...
...emath{\mathit{y}}}})\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ contain both 0's and 1's, so the probability that $ \ensuremath{\ensuremath{\ensuremath{\mathit{z}}}}(\ensuremath{\ensuremath{\ens...
...emath{\mathit{y}}}})\bmod 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$ looks like (5.2) or (5.3) is 0. If $ \ensuremath{\ensuremath{\ensuremath{\mathit{r}}}}=\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$, then the probability of looking like (5.2) is 0, but the probability of looking like (5.3) is $ 1/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}-1}=2/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ (since we must have $ b_1,\ldots,b_{d-1}=1,\ldots,1$). If $ r < \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}$, then we must have $ b_{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-r-1},\ldots,b_{\ensuremat...
...h{\mathit{w}}}}-r-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}=0,\ldots,0$ or $ b_{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}-r-1},\ldots,b_{\ensuremat...
...h{\mathit{w}}}}-r-\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}=1,\ldots,1$. The probability of each of these cases is $ 1/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$ and they are mutually exclusive, so the probability of either of these cases is $ 2/2^{\ensuremath{\ensuremath{\ensuremath{\mathit{d}}}}}$. This completes the proof. $ \qedsymbol$

5.1.2 Summary

The following theorem summarizes the performance of a ChainedHashTable data structure:

Theorem 5..1   A ChainedHashTable implements the USet interface. Ignoring the cost of calls to $ \ensuremath{\mathrm{grow}()}$, a ChainedHashTable supports the operations $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ in $ O(1)$ expected time per operation.

Furthermore, beginning with an empty ChainedHashTable, any sequence of $ m$ $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations results in a total of $ O(m)$ time spent during all calls to $ \ensuremath{\mathrm{grow}()}$.



Footnotes

... integer.5.1
This is true for most programming languages including C, C#, C++, and Java. Notable exceptions are Python and Ruby, in which the result of a fixed-length $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integer operation that overflows is upgraded to a variable-length representation.
opendatastructures.org

7 . 3 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.

7.3 Discussion and Exercises

Random binary search trees have been studied extensively. Devroye [19] gives a proof of Lemma 7.1 and related results. There are much stronger results in the literature as well, the most impressive of which is due to Reed [62], who shows that the expected height of a random binary search tree is

$\displaystyle \alpha\ln n - \beta\ln\ln n + O(1)
$

where $ \alpha\approx4.31107$ is the unique solution on the interval $ [2,\infty)$ of the equation $ \alpha\ln((2e/\alpha))=1$ and $ \beta=\frac{3}{2\ln(\alpha/2)}$ . Furthermore, the variance of the height is constant.

The name Treap was coined by Seidel and Aragon [65] who discussed Treaps and some of their variants. However, their basic structure was studied much earlier by Vuillemin [74] who called them Cartesian trees.

One possible space-optimization of the Treap data structure is the elimination of the explicit storage of the priority $ \ensuremath{\ensuremath{\mathit{p}}}$ in each node. Instead, the priority of a node, $ \ensuremath{\ensuremath{\mathit{u}}}$, is computed by hashing $ \ensuremath{\ensuremath{\mathit{u}}}$'s address in memory. Although a number of hash functions will probably work well for this in practice, for the important parts of the proof of Lemma 7.1 to remain valid, the hash function should be randomized and have the min-wise independent property: For any distinct values $ x_1,\ldots,x_k$, each of the hash values $ h(x_1),\ldots,h(x_k)$ should be distinct with high probability and, for each $ i\in\{1,\ldots,k\}$,

$\displaystyle \Pr\{h(x_i) = \min\{h(x_1),\ldots,h(x_k)\}\} \le c/k
$

for some constant $ c$. One such class of hash functions that is easy to implement and fairly fast is tabulation hashing (Section 5.2.3).

Another Treap variant that doesn't store priorities at each node is the randomized binary search tree of Martínez and Roura [51]. In this variant, every node, $ \ensuremath{\ensuremath{\mathit{u}}}$, stores the size, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{size}}}$, of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$. Both the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ algorithms are randomized. The algorithm for adding $ \ensuremath{\ensuremath{\mathit{x}}}$ to the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$ does the following:

  1. With probability $ 1/(\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}}+1)$, the value $ \ensuremath{\ensuremath{\mathit{x}}}$ is added the usual way, as a leaf, and rotations are then done to bring $ \ensuremath{\ensuremath{\mathit{x}}}$ up to the root of this subtree.
  2. Otherwise (with probability $ 1-1/(\ensuremath{\ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}}+1)$), the value $ \ensuremath{\ensuremath{\mathit{x}}}$ is recursively added into one of the two subtrees rooted at $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ or $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$, as appropriate.
The first case corresponds to an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation in a Treap where $ \ensuremath{\ensuremath{\mathit{x}}}$'s node receives a random priority that is smaller than any of the $ \ensuremath{\mathrm{size}(\ensuremath{\mathit{u}})}$ priorities in $ \ensuremath{\ensuremath{\mathit{u}}}$'s subtree, and this case occurs with exactly the same probability.

Removing a value $ \ensuremath{\ensuremath{\mathit{x}}}$ from a randomized binary search tree is similar to the process of removing from a Treap. We find the node, $ \ensuremath{\ensuremath{\mathit{u}}}$, that contains $ \ensuremath{\ensuremath{\mathit{x}}}$ and then perform rotations that repeatedly increase the depth of $ \ensuremath{\ensuremath{\mathit{u}}}$ until it becomes a leaf, at which point we can splice it from the tree. The choice of whether to perform a left or right rotation at each step is randomized.

  1. With probability $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}.\ensuremath{\mathit{size}}/(\ensuremath{\mathit{u}}.\ensuremath{\mathit{size}}-1)}$, we perform a right rotation at $ \ensuremath{\ensuremath{\mathit{u}}}$, making $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{left}}}$ the root of the subtree that was formerly rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$.
  2. With probability $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}.\ensuremath{\mathit{size}}/(\ensuremath{\mathit{u}}.\ensuremath{\mathit{size}}-1)}$, we perform a left rotation at $ \ensuremath{\ensuremath{\mathit{u}}}$, making $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{right}}}$ the root of the subtree that was formerly rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$.
Again, we can easily verify that these are exactly the same probabilities that the removal algorithm in a Treap will perform a left or right rotation of $ \ensuremath{\ensuremath{\mathit{u}}}$.

Randomized binary search trees have the disadvantage, compared to treaps, that when adding and removing elements they make many random choices, and they must maintain the sizes of subtrees. One advantage of randomized binary search trees over treaps is that subtree sizes can serve another useful purpose, namely to provide access by rank in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time (see Exercise 7.10). In comparison, the random priorities stored in treap nodes have no use other than keeping the treap balanced.

Exercise 7..1   Illustrate the addition of 4.5 (with priority 7) and then 7.5 (with priority 20) on the Treap in Figure 7.5.

Exercise 7..2   Illustrate the removal of 5 and then 7 on the Treap in Figure 7.5.

Exercise 7..3   Prove the assertion that there are $ 21,964,800$ sequences that generate the tree on the right hand side of Figure 7.1. (Hint: Give a recursive formula for the number of sequences that generate a complete binary tree of height $ h$ and evaluate this formula for $ h=3$.)

Exercise 7..4   Design and implement the $ \ensuremath{\mathrm{permute}(\ensuremath{\mathit{a}})}$ method that takes as input an array, $ \ensuremath{\ensuremath{\mathit{a}}}$, that contains $ \ensuremath{\ensuremath{\mathit{n}}}$ distinct values and randomly permutes $ \ensuremath{\ensuremath{\mathit{a}}}$. The method should run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time and you should prove that each of the $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}!$ possible permutations of $ \ensuremath{\ensuremath{\mathit{a}}}$ is equally probable.

Exercise 7..5   Use both parts of Lemma 7.2 to prove that the expected number of rotations performed by an $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ operation (and hence also a $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operation) is $ O(1)$.

Exercise 7..6   Modify the Treap implementation given here so that it does not explicitly store priorities. Instead, it should simulate them by hashing the $ \ensuremath{\mathrm{hash\_code}()}$ of each node.

Exercise 7..7   Suppose that a binary search tree stores, at each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, the height, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{height}}}$, of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$, and the size, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{size}}}$ of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$.
  1. Show how, if we perform a left or right rotation at $ \ensuremath{\ensuremath{\mathit{u}}}$, then these two quantities can be updated, in constant time, for all nodes affected by the rotation.
  2. Explain why the same result is not possible if we try to also store the depth, $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{depth}}}$, of each node $ \ensuremath{\ensuremath{\mathit{u}}}$.

Exercise 7..8   Design and implement an algorithm that constructs a Treap from a sorted array, $ \ensuremath{\ensuremath{\mathit{a}}}$, of $ \ensuremath{\ensuremath{\mathit{n}}}$ elements. This method should run in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ worst-case time and should construct a Treap that is indistinguishable from one in which the elements of $ \ensuremath{\ensuremath{\mathit{a}}}$ were added one at a time using the $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ method.

Exercise 7..9   This exercise works out the details of how one can efficiently search a Treap given a pointer that is close to the node we are searching for.
  1. Design and implement a Treap implementation in which each node keeps track of the minimum and maximum values in its subtree.
  2. Using this extra information, add a $ \ensuremath{\mathrm{finger\_find}(\ensuremath{\mathit{x}},\ensuremath{\mathit{u}})}$ method that executes the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation with the help of a pointer to the node $ \ensuremath{\ensuremath{\mathit{u}}}$ (which is hopefully not far from the node that contains $ \ensuremath{\ensuremath{\mathit{x}}}$). This operation should start at $ \ensuremath{\ensuremath{\mathit{u}}}$ and walk upwards until it reaches a node $ \ensuremath{\ensuremath{\mathit{w}}}$ such that $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{min}}}}\le...
...\le \ensuremath{\ensuremath{\ensuremath{\mathit{w}}.\ensuremath{\mathit{max}}}}$. From that point onwards, it should perform a standard search for $ \ensuremath{\ensuremath{\mathit{x}}}$ starting from $ \ensuremath{\ensuremath{\mathit{w}}}$. (One can show that $ \ensuremath{\mathrm{finger\_find}(\ensuremath{\mathit{x}},\ensuremath{\mathit{u}})}$ takes $ O(1+\log r)$ time, where $ r$ is the number of elements in the treap whose value is between $ \ensuremath{\ensuremath{\mathit{x}}}$ and $ \ensuremath{\ensuremath{\mathit{u}}.\ensuremath{\mathit{x}}}$.)
  3. Extend your implementation into a version of a treap that starts all its $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operations from the node most recently found by $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$.

Exercise 7..10   Design and implement a version of a Treap that includes a $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$ operation that returns the key with rank $ \ensuremath{\ensuremath{\mathit{i}}}$ in the Treap. (Hint: Have each node, $ \ensuremath{\ensuremath{\mathit{u}}}$, keep track of the size of the subtree rooted at $ \ensuremath{\ensuremath{\mathit{u}}}$.)

Exercise 7..11   Implement a TreapList, an implementation of the List interface as a treap. Each node in the treap should store a list item, and an in-order traversal of the treap finds the items in the same order that they occur in the list. All the List operations $ \ensuremath{\mathrm{get}(\ensuremath{\mathit{i}})}$, $ \ensuremath{\mathrm{set}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{i}},\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{i}})}$ should run in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time.

Exercise 7..12   Design and implement a version of a Treap that supports the $ \ensuremath{\mathrm{split}(\ensuremath{\mathit{x}})}$ operation. This operation removes all values from the Treap that are greater than $ \ensuremath{\ensuremath{\mathit{x}}}$ and returns a second Treap that contains all the removed values.

Example: the code $ \ensuremath{\ensuremath{\mathit{t_2}} \gets \ensuremath{\ensuremath{\mathit{t}}.\mathrm{split}(\ensuremath{\mathit{x}})}}$ removes from $ \ensuremath{\ensuremath{\mathit{t}}}$ all values greater than $ \ensuremath{\ensuremath{\mathit{x}}}$ and returns a new Treap $ \ensuremath{\ensuremath{\mathit{t_2}}}$ containing all these values. The $ \ensuremath{\mathrm{split}(\ensuremath{\mathit{x}})}$ operation should run in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time.

Warning: For this modification to work properly and still allow the $ \ensuremath{\mathrm{size}()}$ method to run in constant time, it is necessary to implement the modifications in Exercise 7.10.

Exercise 7..13   Design and implement a version of a Treap that supports the $ \ensuremath{\mathrm{absorb}(\ensuremath{\mathit{t_2}})}$ operation, which can be thought of as the inverse of the $ \ensuremath{\mathrm{split}(\ensuremath{\mathit{x}})}$ operation. This operation removes all values from the Treap $ \ensuremath{\ensuremath{\mathit{t_2}}}$ and adds them to the receiver. This operation presupposes that the smallest value in $ \ensuremath{\ensuremath{\mathit{t_2}}}$ is greater than the largest value in the receiver. The $ \ensuremath{\mathrm{absorb}(\ensuremath{\mathit{t_2}})}$ operation should run in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ expected time.

Exercise 7..14   Implement Martinez's randomized binary search trees, as discussed in this section. Compare the performance of your implementation with that of the Treap implementation.

opendatastructures.org

13 . Data Structures for Integers

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. Data Structures for Integers

In this chapter, we return to the problem of implementing an SSet. The difference now is that we assume the elements stored in the SSet are $ \ensuremath{\ensuremath{\mathit{w}}}$-bit integers. That is, we want to implement $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$, $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$, and $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ where $ \ensuremath{\ensuremath{\ensuremath{\mathit{x}}}}\in\{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$. It is not too hard to think of plenty of applications where the data--or at least the key that we use for sorting the data--is an integer.

We will discuss three data structures, each building on the ideas of the previous. The first structure, the BinaryTrie performs all three SSet operations in $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time. This is not very impressive, since any subset of $ \{0,\ldots,2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}-1\}$ has size $ \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\le 2^{\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}}$, so that $ \log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}} \le \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$. All the other SSet implementations discussed in this book perform all operations in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$ time so they are all at least as fast as a BinaryTrie.

The second structure, the XFastTrie, speeds up the search in a BinaryTrie by using hashing. With this speedup, the $ \ensuremath{\mathrm{find}(\ensuremath{\mathit{x}})}$ operation runs in $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time. However, $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ operations in an XFastTrie still take $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ time and the space used by an XFastTrie is $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}}\cdot\ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$.

The third data structure, the YFastTrie, uses an XFastTrie to store only a sample of roughly one out of every $ \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}}$ elements and stores the remaining elements in a standard SSet structure. This trick reduces the running time of $ \ensuremath{\mathrm{add}(\ensuremath{\mathit{x}})}$ and $ \ensuremath{\mathrm{remove}(\ensuremath{\mathit{x}})}$ to $ O(\log \ensuremath{\ensuremath{\ensuremath{\mathit{w}}}})$ and decreases the space to $ O(\ensuremath{\ensuremath{\ensuremath{\mathit{n}}}})$.

The implementations used as examples in this chapter can store any type of data, as long as an integer can be associated with it. In the code samples, the variable $ \ensuremath{\ensuremath{\mathit{ix}}}$ is always the integer value associated with $ \ensuremath{\ensuremath{\mathit{x}}}$, and the method $ \ensuremath{\mathrm{int\_value}(\ensuremath{\mathit{x}})}$ converts $ \ensuremath{\ensuremath{\mathit{x}}}$ to its associated integer. In the text, however, we will simply treat $ \ensuremath{\ensuremath{\mathit{x}}}$ as if it is an integer.



Subsections
opendatastructures.org

Cross-site request forgery (CSRF)

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.

Cross-site request forgery (CSRF)

In a cross-site request forgery (CSRF) attack, an attacker tricks the user or the browser into making an HTTP request to the target site from a malicious site. The request includes the user's credentials and causes the server to carry out some harmful action, thinking that the user intended it.

Overview

A website typically performs special actions on a user's behalf — buying a product or making an appointment, for example — by receiving an HTTP request from the user's browser, often with parameters detailing the action to perform. To ensure that the request really comes from the user in question, the server expects the request to include credentials for the user: for example, a cookie containing the user's session ID.

In the example below, the user has previously signed into their bank, and the browser has stored a session cookie for the user. The page contains a <form> element, which enables the user to transfer funds to another person. When the user submits the form, the browser sends a POST request to the server, including the form data. If the user is signed in, the request includes the user's cookie. The server validates the cookie and performs the special action — in this case, transferring money:

Diagram showing a user submitting a browser form, the browser then making a POST request to the server, and the server validating the request.

In this guide, we'll call a request like this, that carries out some special action, a state-changing request.

In a CSRF attack, the attacker creates a website containing a form. The form's action attribute is set to the bank's website, and the form contains hidden input fields mimicking the bank's fields:

html
<form action="https://my-bank.example.org/transfer" method="POST">
  <input type="hidden" name="recipient" value="attacker" />
  <input type="hidden" name="amount" value="1000" />
</form>

The page also contains JavaScript that submits the form on page load:

js
const form = document.querySelector("form");
form.submit();

When the user visits the page, the browser submits the form to the bank's website. Because the user is signed into their bank, the request may include the user's real cookie, so the bank's server successfully validates the request, and transfers the funds:

Diagram showing a CSRF attack in which a decoy page submits a POST request to the website for the user's bank.

There are other ways the attacker could issue a cross-site request forgery. For example, if the website uses a GET request to carry out the action, then the attacker can avoid having to use a form at all, and can execute the attack by sending the user a link to a page that contains markup like this:

html
<img
  src="https://my-bank.example.org/transfer?recipient=attacker&amount=1000" />

When the user loads the page, the browser tries to fetch the image resource, which is really the transaction request.

In general, a CSRF attack is possible if your website:

  • Uses HTTP requests to change some state on the server.
  • Uses only cookies to validate that the request came from an authenticated user.
  • Uses only parameters in the request that an attacker can predict.

Defenses against CSRF

In this section we'll outline three alternative defenses against CSRF and a fourth practice which can be used to provide defense in depth for either of the others.

  • The first primary defense is to use CSRF tokens embedded in the page. This is the most common method if you're issuing state-changing requests from form elements, as in our example above.

  • The second is to use Fetch metadata HTTP headers to check whether or not the state-changing request is being issued cross-site.

  • The third is to ensure that state-changing requests are not simple requests, so that cross-origin requests are blocked by default. This method is appropriate if you're issuing state-changing requests from JavaScript APIs like fetch().

Finally, we'll discuss the SameSite cookie attribute, which can be used to provide defense in depth alongside either of the previous methods.

CSRF tokens

In this defense, when the server serves a page, it embeds an unpredictable value in the page, called the CSRF token. Then when the legitimate page sends the state-changing request to the server, it includes the CSRF token in the HTTP request. The server can then check the token value and carries out the request only if it matches. Because an attacker can't guess the token value, they can't issue a successful forgery. Even if the attacker does discover a token after it has been used, the request can't be replayed if the token changes every time.

For form submissions, the CSRF token is usually included in a hidden form field, so that on form submission it is automatically sent back to the server for checking.

For a JavaScript API like fetch(), the token might be placed in a cookie or embedded in the page, and the JavaScript extracts the value and sends it as an extra header.

Modern web frameworks usually have built-in support for CSRF tokens: for example, Django enables you to protect forms using the csrf_token tag. This generates an additional hidden form field containing the token, which the framework then checks on the server.

To take advantage of this protection you must understand all the places in your website where you are using state-changing HTTP requests, and ensure you're using the defense provided by your chosen framework.

Fetch metadata

Fetch metadata is a collection of HTTP request headers, added by the browser, that provide extra information about the context of an HTTP request. The server can use these headers to decide whether to allow a request or not.

Most relevant for CSRF is the Sec-Fetch-Site header, which tells the server whether this request is same-origin, same-site, cross-site, or initiated directly by the user. The server can use this information to allow cross-origin requests, or block them as potential CSRF attacks.

For example, this Express code allows only same-site and same-origin requests:

js
app.post("/transfer", (req, res) => {
  const secFetchSite = req.headers["sec-fetch-site"];
  if (secFetchSite === "same-origin" || secFetchSite === "same-site") {
    console.log("allowed");
    // Update state
  } else {
    console.log("denied");
    // Don't update state
  }
});

See Fetch metadata request header for the complete list of Fetch metadata headers, and Fetch metadata for a guide to using this feature.

Avoiding simple requests

Web browsers distinguish two sorts of HTTP requests: simple requests and other requests.

Simple requests, which are the sort of request that result from a <form> element submission, can be made cross-origin without being blocked. Since forms have been able to make cross-origin requests since the early days of the web, it's important for compatibility that they should still be able to make cross-origin requests. This is why we need to implement other strategies to defend forms against CSRF, such as using a CSRF token.

However, other parts of the web platform, in particular JavaScript APIs like fetch(), can make different sorts of requests (for example, requests that set custom headers), and these requests are by default not allowed cross-origin, so a CSRF attack would not succeed.

So a website that uses fetch() or XMLHttpRequest can defend against CSRF by ensuring that the state-changing requests that it issues are never simple requests.

For example, setting the request's Content-Type to "application/json" will prevent it from being treated like a simple request:

js
fetch("https://my-bank.example.org/transfer", {
  method: "POST",
  headers: {
    "Content-Type": "application/json",
  },
  body: JSON.stringify({ recipient: "joe", amount: "100" }),
});

Similarly, setting a custom header on the request will prevent it being treated like a simple request:

js
fetch("https://my-bank.example.org/transfer", {
  method: "POST",
  headers: {
    "X-MY-BANK-ANTI-CSRF": 1,
  },
  body: JSON.stringify({ recipient: "joe", amount: "100" }),
});

The header name can be anything, as long as it doesn't conflict with standard headers.

The server can then check for the existence of the header: if it exists, then the server knows that the request was not treated as a simple request.

Non-simple requests and CORS

We've said that non-simple requests are by default not sent cross-origin. The catch is that the Cross-Origin Resource Sharing (CORS) protocol allows a website to relax this restriction.

Specifically, your website will be vulnerable to a CSRF attack from a particular origin if its response to a state-changing request includes:

Defense in depth: SameSite cookies

The SameSite cookie attribute provides some protection against CSRF attacks. It's not a complete defense, and is best considered as an addition to one of the other defenses, providing some degree of defense in depth.

This attribute controls when a browser is allowed to include the cookie in a cross-site request. It has three possible values: None, Lax and Strict.

The Strict value offers the most protection: if this attribute is set, the browser will not include the cookie in any cross-site request. However, this creates a usability issue: if the user is logged into your site, and follows a link to your site from a different site, then your cookies will not be included, and the user will not be recognized when they reach your site.

The Lax value relaxes this restriction: cookies are included in cross-site requests if both the following conditions apply:

  • The request was a navigation of the top-level browsing context.
  • The request used a safe method: notably, GET is safe but POST is not.

However, Lax offers significantly weaker protection than Strict:

  • An attacker can trigger a top-level navigation. For example, at the start of this article we show a CSRF attack in which the attacker submits a form to the target: this is considered a top-level navigation. If the form were submitted using GET, then the request would still include cookies with SameSite=Lax.
  • Even if the server does check that the request was not sent using GET, some web frameworks support "method override": this enables an attacker to send a request using GET but have it appear to the server as if it used POST.

As a general guide, then, you should try to use Strict for some cookies and Lax for others:

  • Lax for cookies that you will use to decide if a logged-in user should be shown a page
  • Strict for cookies that you will use for state-changing requests that you don't want to allow cross-site.

Another problem with the SameSite attribute is that it protects you from requests from a different site, not a different origin. This is a looser protection, because (for example) https://foo.example.org and https://bar.example.org are considered the same site, although they are different origins. Effectively, if you rely on same-site protection, you have to trust all your site's subdomains.

See Bypassing SameSite cookie restrictions for more details on the limitations of SameSite.

Defense summary checklist

  • Understand where in your website you are implementing state-changing requests that use session cookies to check which user issued the request.
  • Implement at least one of the primary defenses described in this document:
    • If you are using <form> elements to issue these requests, ensure you are using a web framework with support for CSRF tokens, and use it.
    • If you are using JavaScript APIs like fetch() or XMLHttpRequest to issue state-changing requests, ensure that they are not simple requests.
    • Whichever mechanism you use to issue requests, consider using Fetch metadata to disallow cross-site requests.
  • Avoid using the GET method to issue state-changing requests.
  • Set the SameSite attribute for session cookies to Strict if you can, or Lax if you have to.

See also

7.3. Select Lists #

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.

7.3. Select Lists #

As shown in the previous section, the table expression in the SELECT command constructs an intermediate virtual table by possibly combining tables, views, eliminating rows, grouping, etc. This table is finally passed on to processing by the select list. The select list determines which columns of the intermediate table are actually output.

7.3.1. Select-List Items #

The simplest kind of select list is * which emits all columns that the table expression produces. Otherwise, a select list is a comma-separated list of value expressions (as defined in Section 4.2). For instance, it could be a list of column names:

SELECT a, b, c FROM ...

The columns names a, b, and c are either the actual names of the columns of tables referenced in the FROM clause, or the aliases given to them as explained in Section 7.2.1.2. The name space available in the select list is the same as in the WHERE clause, unless grouping is used, in which case it is the same as in the HAVING clause.

If more than one table has a column of the same name, the table name must also be given, as in:

SELECT tbl1.a, tbl2.a, tbl1.b FROM ...

When working with multiple tables, it can also be useful to ask for all the columns of a particular table:

SELECT tbl1.*, tbl2.a FROM ...

See Section 8.16.5 for more about the table_name.* notation.

If an arbitrary value expression is used in the select list, it conceptually adds a new virtual column to the returned table. The value expression is evaluated once for each result row, with the row's values substituted for any column references. But the expressions in the select list do not have to reference any columns in the table expression of the FROM clause; they can be constant arithmetic expressions, for instance.

7.3.2. Column Labels #

The entries in the select list can be assigned names for subsequent processing, such as for use in an ORDER BY clause or for display by the client application. For example:

SELECT a AS value, b + c AS sum FROM ...

If no output column name is specified using AS, the system assigns a default column name. For simple column references, this is the name of the referenced column. For function calls, this is the name of the function. For complex expressions, the system will generate a generic name.

The AS key word is usually optional, but in some cases where the desired column name matches a PostgreSQL key word, you must write AS or double-quote the column name in order to avoid ambiguity. (Appendix C shows which key words require AS to be used as a column label.) For example, FROM is one such key word, so this does not work:

SELECT a from, b + c AS sum FROM ...

but either of these do:

SELECT a AS from, b + c AS sum FROM ...
SELECT a "from", b + c AS sum FROM ...

For greatest safety against possible future key word additions, it is recommended that you always either write AS or double-quote the output column name.

Note

The naming of output columns here is different from that done in the FROM clause (see Section 7.2.1.2). It is possible to rename the same column twice, but the name assigned in the select list is the one that will be passed on.

7.3.3. DISTINCT #

After the select list has been processed, the result table can optionally be subject to the elimination of duplicate rows. The DISTINCT key word is written directly after SELECT to specify this:

SELECT DISTINCT select_list ...

(Instead of DISTINCT the key word ALL can be used to specify the default behavior of retaining all rows.)

Obviously, two rows are considered distinct if they differ in at least one column value. Null values are considered equal in this comparison.

Alternatively, an arbitrary expression can determine what rows are to be considered distinct:

SELECT DISTINCT ON (expression [, expression ...]) select_list ...

Here expression is an arbitrary value expression that is evaluated for all rows. A set of rows for which all the expressions are equal are considered duplicates, and only the first row of the set is kept in the output. Note that the “first row” of a set is unpredictable unless the query is sorted on enough columns to guarantee a unique ordering of the rows arriving at the DISTINCT filter. (DISTINCT ON processing occurs after ORDER BY sorting.)

The DISTINCT ON clause is not part of the SQL standard and is sometimes considered bad style because of the potentially indeterminate nature of its results. With judicious use of GROUP BY and subqueries in FROM, this construct can be avoided, but it is often the most convenient alternative.

Dive into Deep Learning

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.

Dive into Deep Learning

Dive into Deep Learning

Interactive deep learning book with code, math, and discussions

Implemented with PyTorch, NumPy/MXNet, JAX, and TensorFlow

Adopted at 500 universities from 70 countries

Star

Authors

Aston Zhang

Amazon

Zack C. Lipton

CMU and Amazon

Mu Li

Amazon

Alex J. Smola

Amazon

Vol.2 Chapter Authors

Framework Adaptation Authors

Anirudh Dagar

Amazon
PyTorch Adaptation
JAX Adaptation

Yuan Tang

Akuity
TensorFlow Adaptation

We thank all the community contributors
for making this open source book better for everyone.

Contribute to the book

Each section is an executable Jupyter notebook

You can modify the code and tune hyperparameters to get instant feedback to accumulate practical experiences in deep learning.

Mathematics + Figures + Code

We offer an interactive learning experience with mathematics, figures, code, text, and discussions, where concepts and techniques are illustrated and implemented with experiments on real data sets.

Active community support

You can discuss and learn with thousands of peers in the community through the link provided in each section.

D2L as a textbook or a reference book

Abasyn University, Islamabad Campus
Alexandria University
Amirkabir University of Technology
Amity University
Amrita Vishwa Vidyapeetham University
Anna University
Anna University Regional Campus Madurai
Ateneo de Naga University
Australian National University
Bar-Ilan University
Barnard College
Beijing Foresty University
Birla Institute of Technology and Science, Hyderabad
Birla Institute of Technology and Science, Pilani
BML Munjal University
Boston College
Boston University
Brac University
Brandeis University
Brown University
Brunel University London
Cairo University
California State University, Northridge
Cankaya University
Carnegie Mellon University
Center for Research and Advanced Studies of the National Polytechnic Institute
Chalmers University of Technology
Chennai Mathematical Institute
Chouaib Doukkali University
Chulalongkorn University
City College of New York
City University of Hong Kong
City University of Science and Information Technology
College of Engineering Pune
Columbia University
Cornell University
Cyprus Institute
Deakin University
Diponegoro University
Dresden University of Technology
Duke University
Durban University of Technology
Eastern Mediterranean University
Ecole Nationale Supérieure d'Informatique
Ecole Nationale Supérieure de Cognitique
École Nationale Supérieure de Techniques Avancées
Eindhoven University of Technology
Emory University
Eötvös Loránd University
Escuela Politécnica Nacional
Escuela Superior Politecnica del Litoral
Federal University Lokoja
Feng Chia University
Fisk University
Florida Atlantic University
FPT University
Fudan University
Ganpat University
Gayatri Vidya Parishad College of Engineering (Autonomous)
Gazi Üniversitesi
Gdańsk University of Technology
George Mason University
Georgetown University
Georgia Institute of Technology
Gheorghe Asachi Technical University of Iaşi
Golden Gate University
Great Lakes Institute of Management
Gwangju Institute of Science and Technology
Habib University
Hamad Bin Khalifa University
Hangzhou Dianzi University
Hangzhou Dianzi University
Hankuk University of Foreign Studies
Harare Institute of Technology
Harbin Institute of Technology
Harvard University
Hasso-Plattner-Institut
Hebrew University of Jerusalem
Heinrich-Heine-Universität Düsseldorf
Henan Institute of Technology
Hertie School
Higher Institute of Applied Science and Technology of Sousse
Hiroshima University
Ho Chi Minh City University of Foreign Languages and Information Technology
Hochschule Bremen
Hochschule für Technik und Wirtschaft
Hochschule Hamm-Lippstadt
Hong Kong University of Science and Technology
Houston Community College
Huazhong University of Science and Technology
Humboldt-Universität zu Berlin
İbn Haldun Üniversitesi
Icahn School of Medicine at Mount Sinai
Imperial College London
IMT Mines Alès
Indian Institute of Technology Bombay
Indian Institute of Technology Hyderabad
Indian Institute of Technology Jodhpur
Indian Institute of Technology Kanpur
Indian Institute of Technology Kharagpur
Indian Institute of Technology Mandi
Indian Institute of Technology Ropar
Indian School of Business
Indira Gandhi National Open University
Indraprastha Institute of Information Technology, Delhi
Institut catholique d'arts et métiers (ICAM)
Institut de recherche en informatique de Toulouse
Institut Supérieur d'Informatique et des Techniques de Communication
Institut Supérieur De L'electronique Et Du Numérique
Institut Teknologi Bandung
Instituto Federal de Educação, Ciência e Tecnologia de São Paulo, Campus Salto
Instituto Politécnico Nacional
Instituto Tecnológico Autónomo de México
Instituto Tecnológico de Buenos Aires
Islamic University of Medina
İstanbul Teknik Üniversitesi
IT-Universitetet i København
Ivan Franko National University of Lviv
Jeonbuk National Univerity
Johns Hopkins University
Julius-Maximilians-Universität Würzburg
Keio University
King Abdullah University of Science and Technology
King Fahd University of Petroleum and Minerals
King Faisal University
Kongu Engineering College
Korea Aerospace University
KPR Institute of Engineering and Technology
Kyungpook National University
Lancaster University
Leading Unviersity
Leibniz Universität Hannover
Leuphana University of Lüneburg
London School of Economics & Political Science
M.S.Ramaiah University of Applied Sciences
Make School
Masaryk University
Massachusetts Institute of Technology
Maynooth University
McGill University
Menoufia University
Milwaukee School of Engineering
Minia University
Mississippi State University
Missouri University of Science and Technology
Mohammad Ali Jinnah University
Mohammed V University in Rabat
Monash University
Multimedia University
Murdoch University
Nanjing University
Nanchang Hangkong University
Nanjing Medical University
Nanjing University
National Chung Hsing University
National Institute of Technical Teachers Training & Research
National Institute of Technology Trichy
National Institute of Technology, Warangal
National Sun Yat-sen University
National Taichung University of Science and Technology
National Taiwan University
National Technical University of Athens
National Technical University of Ukraine
National United University
National University of Sciences and Technology
National University of Singapore
Nazarbayev University
New Jersey Institute of Technology
New Mexico Institute of Mining and Technology
New Mexico State University
New York University
Newman University
North Ossetian State University
NorthCap University
Northeastern University
Northwestern Polytechnical University
Northwestern University
Ohio University
Pakuan University
Peking University
Pennsylvania State University
Pohang University of Science and Technology
Politechnika Białostocka
Politecnico di Milano
Politeknik Negeri Semarang
Pomona College
Pontificia Universidad Católica de Chile
Pontificia Universidad Católica del Perú
Portland State University
Punjabi University
Purdue University
Purdue University Northwest
Quaid-e-Azam University
Queen Mary University of London
Queen's University
Radboud Universiteit
Radboud University
Rajiv Gandhi Institute of Petroleum Technology
Rensselaer Polytechnic Institute
Rowan University
Rutgers, The State University of New Jersey
RVS Institute of Management Studies and Research
RWTH Aachen University
Sant Longowal Institute of Engineering Technology
Santa Clara University
Sapienza Università di Roma
Seoul National University
Seoul National University of Science and Technology
Shanghai Jiao Tong University
Shanghai University of Electric Power
Shanghai University of Finance and Economics
Shantilal Shah Engineering College
Sharif University of Technology
Shenzhen University
Shivaji University, Kolhapur
Simon Fraser University
Singapore University of Technology and Design
Sogang University
Sookmyung Women's University
Southern Connecticut State University
Southern New Hampshire University
St. Pölten University of Applied Sciences
Stanford University
State University of New York at Albany
State University of New York at Binghamton
State University of New York at Fredonia
Stellenbosch University
Stevens Institute of Technology
Sungkyunkwan University
Technion - Israel Institute of Technology
Technische Universität Berlin
Technische Universität München
Technische Universiteit Delft
Tecnológico de Monterrey, Campus Guadalajara
Tekirdağ Namık Kemal Üniversitesi
Télécom Paris
Telkom University
Texas A&M University
Thapar Institute of Engineering and Technology
Tsinghua University
Tufts University
Umeå University
Universidad Carlos III de Madrid
Universidad de Ibagué
Universidad de Ingeniería y Tecnología - UTEC
Universidad de Salamanca
Universidad de Zaragoza
Universidad del Norte, Colombia
Universidad Icesi
Universidad Militar Nueva Granada
Universidad Nacional Agraria La Molina
Universidad Nacional Autónoma de México
Universidad Nacional de Colombia Sede Manizales
Universidad Nacional de Tierra del Fuego
Universidad Politécnica de Chiapas
Universidad Politécnica de Valencia
Universidad Politécnica Salesiana, Cuenca
Universidad Rafael Landivar
Universidad Rey Juan Carlos
Universidad San Francisco de Quito
Universidad Tecnológica de Pereira
Universidad Tecnológica Nacional
Universidade Católica de Brasília
Universidade Estadual de Campinas
Universidade Federal de Goiás
Universidade Federal de Minas Gerais
Universidade Federal de Ouro Preto
Universidade Federal de Pernambuco
Universidade Federal de São Carlos
Universidade Federal de Viçosa
Universidade Federal do Pampa
Universidade Federal do Rio Grande
Universidade NOVA de Lisboa
Universidade Presbiteriana Mackenzie
Universidade Tecnológica Federal do Paraná
Università Cattolica del Sacro Cuore
Università degli Studi di Bari Aldo Moro
Università degli Studi di Brescia
Università degli Studi di Catania
Università degli Studi di Padova
Universitas Andalas, Padang
Universitas Indonesia
Universitas Negeri Yogyakarta
Universitas Udayana
Universität Bremen
Universitat de Barcelona
Universitat de València
Universität Heidelberg
Universität Leipzig
Universitat Politècnica de Catalunya
Universitatea Babeș-Bolyai
Universitatea de Vest din Timișoara
Université Abderrahmane Mira de Béjaïa
Université Clermont Auvergne
Université Côte d'Azur
Université de Caen Normandie
Université de Rouen Normandie
Université de technologie de Compiègne
Université Paris-Saclay
Université Toulouse 1 Capitole
University of Akron
University of Alabama in Huntsville
University of Allahabad
University of Applied Sciences Würzburg-Schweinfurt
University of Arkansas
University of Augsburg
University of Baghdad
University of Bath
University of Bordj Bou Arreridj
University of British Columbia
University of California, Berkeley
University of California, Irvine
University of California, Los Angeles
University of California, San Diego
University of California, Santa Barbara
University of California, Santa Cruz
University of Cambridge
University of Canberra
University of Catania
University of Cincinnati
University of Colorado Boulder
University of Connecticut
University of Copenhagen
University of Derby
University of Florida
University of Genoa
University of Ghana
University of Groningen
University of Hamburg
University of Houston
University of Hull
University of Iceland
University of Idaho
University of Illinois at Urbana-Champaign
University of International Business and Economics
University of Klagenfurt
University of Liège
University of Louisiana at Lafayette
University of Maryland
University of Maryland Baltimore County
University of Massachusetts Lowell
University of Michigan
University of Michigan Dearborn
University of Milano-Bicocca
University of Minnesota, Twin Cities
University of Moratuwa
University of Nebraska Omaha
University of New Hampshire
University of Newcastle
University of North Carolina at Chapel Hill
University of North Texas
University of Northern Philippines
University of Nottingham
University of Oslo
University of Pennsylvania
University of Pittsburgh
University of Rostock
University of São Paulo
University of Science and Technology of China
University of Southern California
University of Southern Maine
University of St Andrews
University of St. Thomas
University of Suffolk
University of Sydney
University of Szeged
University of Technology Sydney
University of Tehran
University of Texas at Austin
University of Texas at Dallas
University of Texas Rio Grande Valley
University of Udine
University of Warsaw
University of Washington
University of Waterloo
University of Wisconsin Madison
Univerzita Komenského v Bratislave
Uniwersytet Jagielloński
Vardhaman College of Engineering
Vardhman Mahaveer Open University
Vietnamese-German University
Vignana Jyothi Institute Of Management
Vilnius University
Wageningen University
West Virginia University
Western University
Wichita State University
Xavier University Bhubaneswar
Xi'an Jiaotong Liverpool University
Xiamen University
Xianning Vocational Technical College
Yale University
Yeshiva University
Yıldız Teknik Üniversitesi
Yonsei University
Yunnan University
Zhejiang University

BibTeX entry for citing the book


@book{zhang2023dive,
    title={Dive into Deep Learning},
    author={Zhang, Aston and Lipton, Zachary C. and Li, Mu and Smola, Alexander J.},
    publisher={Cambridge University Press},
    note={\url{https://D2L.ai}},
    year={2023}
}

Table of contents

22.11. Information Theory 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.

22.11. Information Theory
Open the notebook in SageMaker Studio Lab

The universe is overflowing with information. Information provides a common language across disciplinary rifts: from Shakespeare’s Sonnet to researchers’ paper on Cornell ArXiv, from Van Gogh’s printing Starry Night to Beethoven’s music Symphony No. 5, from the first programming language Plankalkül to the state-of-the-art machine learning algorithms. Everything must follow the rules of information theory, no matter the format. With information theory, we can measure and compare how much information is present in different signals. In this section, we will investigate the fundamental concepts of information theory and applications of information theory in machine learning.

Before we get started, let’s outline the relationship between machine learning and information theory. Machine learning aims to extract interesting signals from data and make critical predictions. On the other hand, information theory studies encoding, decoding, transmitting, and manipulating information. As a result, information theory provides fundamental language for discussing the information processing in machine learned systems. For example, many machine learning applications use the cross-entropy loss as described in Section 4.1. This loss can be directly derived from information theoretic considerations.

22.11.1. Information

Let’s start with the “soul” of information theory: information. Information can be encoded in anything with a particular sequence of one or more encoding formats. Suppose that we task ourselves with trying to define a notion of information. What could be our starting point?

Consider the following thought experiment. We have a friend with a deck of cards. They will shuffle the deck, flip over some cards, and tell us statements about the cards. We will try to assess the information content of each statement.

First, they flip over a card and tell us, “I see a card.” This provides us with no information at all. We were already certain that this was the case so we hope the information should be zero.

Next, they flip over a card and say, “I see a heart.” This provides us some information, but in reality there are only \(4\) different suits that were possible, each equally likely, so we are not surprised by this outcome. We hope that whatever the measure of information, this event should have low information content.

Next, they flip over a card and say, “This is the \(3\) of spades.” This is more information. Indeed there were \(52\) equally likely possible outcomes, and our friend told us which one it was. This should be a medium amount of information.

Let’s take this to the logical extreme. Suppose that finally they flip over every card from the deck and read off the entire sequence of the shuffled deck. There are \(52!\) different orders to the deck, again all equally likely, so we need a lot of information to know which one it is.

Any notion of information we develop must conform to this intuition. Indeed, in the next sections we will learn how to compute that these events have \(0\textrm{ bits}\), \(2\textrm{ bits}\), \(~5.7\textrm{ bits}\), and \(~225.6\textrm{ bits}\) of information respectively.

If we read through these thought experiments, we see a natural idea. As a starting point, rather than caring about the knowledge, we may build off the idea that information represents the degree of surprise or the abstract possibility of the event. For example, if we want to describe an unusual event, we need a lot information. For a common event, we may not need much information.

In 1948, Claude E. Shannon published A Mathematical Theory of Communication (Shannon, 1948) establishing the theory of information. In his article, Shannon introduced the concept of information entropy for the first time. We will begin our journey here.

22.11.1.1. Self-information

Since information embodies the abstract possibility of an event, how do we map the possibility to the number of bits? Shannon introduced the terminology bit as the unit of information, which was originally created by John Tukey. So what is a “bit” and why do we use it to measure information? Historically, an antique transmitter can only send or receive two types of code: \(0\) and \(1\). Indeed, binary encoding is still in common use on all modern digital computers. In this way, any information is encoded by a series of \(0\) and \(1\). And hence, a series of binary digits of length \(n\) contains \(n\) bits of information.

Now, suppose that for any series of codes, each \(0\) or \(1\) occurs with a probability of \(\frac{1}{2}\). Hence, an event \(X\) with a series of codes of length \(n\), occurs with a probability of \(\frac{1}{2^n}\). At the same time, as we mentioned before, this series contains \(n\) bits of information. So, can we generalize to a mathematical function which can transfer the probability \(p\) to the number of bits? Shannon gave the answer by defining self-information

(22.11.1)\[I(X) = - \log_2 (p),\]

as the bits of information we have received for this event \(X\). Note that we will always use base-2 logarithms in this section. For the sake of simplicity, the rest of this section will omit the subscript 2 in the logarithm notation, i.e., \(\log(.)\) always refers to \(\log_2(.)\). For example, the code “0010” has a self-information

(22.11.2)\[I(\textrm{"0010"}) = - \log (p(\textrm{"0010"})) = - \log \left( \frac{1}{2^4} \right) = 4 \textrm{ bits}.\]

We can calculate self information as shown below. Before that, let’s first import all the necessary packages in this section.

import torch
from torch.nn import NLLLoss


def nansum(x):
    # Define nansum, as pytorch does not offer it inbuilt.
    return x[~torch.isnan(x)].sum()

def self_information(p):
    return -torch.log2(torch.tensor(p)).item()

self_information(1 / 64)
6.0

22.11.2. Entropy

As self-information only measures the information of a single discrete event, we need a more generalized measure for any random variable of either discrete or continuous distribution.

22.11.2.1. Motivating Entropy

Let’s try to get specific about what we want. This will be an informal statement of what are known as the axioms of Shannon entropy. It will turn out that the following collection of common-sense statements force us to a unique definition of information. A formal version of these axioms, along with several others may be found in Csiszár (2008).

  1. The information we gain by observing a random variable does not depend on what we call the elements, or the presence of additional elements which have probability zero.

  2. The information we gain by observing two random variables is no more than the sum of the information we gain by observing them separately. If they are independent, then it is exactly the sum.

  3. The information gained when observing (nearly) certain events is (nearly) zero.

While proving this fact is beyond the scope of our text, it is important to know that this uniquely determines the form that entropy must take. The only ambiguity that these allow is in the choice of fundamental units, which is most often normalized by making the choice we saw before that the information provided by a single fair coin flip is one bit.

22.11.2.2. Definition

For any random variable \(X\) that follows a probability distribution \(P\) with a probability density function (p.d.f.) or a probability mass function (p.m.f.) \(p(x)\), we measure the expected amount of information through entropy (or Shannon entropy)

(22.11.3)\[H(X) = - E_{x \sim P} [\log p(x)].\]

To be specific, if \(X\) is discrete,

(22.11.4)\[H(X) = - \sum_i p_i \log p_i \textrm{, where } p_i = P(X_i).\]

Otherwise, if \(X\) is continuous, we also refer entropy as differential entropy

(22.11.5)\[H(X) = - \int_x p(x) \log p(x) \; dx.\]

We can define entropy as below.

def entropy(p):
    entropy = - p * torch.log2(p)
    # Operator `nansum` will sum up the non-nan number
    out = nansum(entropy)
    return out

entropy(torch.tensor([0.1, 0.5, 0.1, 0.3]))
tensor(1.6855)

22.11.2.3. Interpretations

You may be curious: in the entropy definition (22.11.3), why do we use an expectation of a negative logarithm? Here are some intuitions.

First, why do we use a logarithm function \(\log\)? Suppose that \(p(x) = f_1(x) f_2(x) \ldots, f_n(x)\), where each component function \(f_i(x)\) is independent from each other. This means that each \(f_i(x)\) contributes independently to the total information obtained from \(p(x)\). As discussed above, we want the entropy formula to be additive over independent random variables. Luckily, \(\log\) can naturally turn a product of probability distributions to a summation of the individual terms.

Next, why do we use a negative \(\log\)? Intuitively, more frequent events should contain less information than less common events, since we often gain more information from an unusual case than from an ordinary one. However, \(\log\) is monotonically increasing with the probabilities, and indeed negative for all values in \([0, 1]\). We need to construct a monotonically decreasing relationship between the probability of events and their entropy, which will ideally be always positive (for nothing we observe should force us to forget what we have known). Hence, we add a negative sign in front of \(\log\) function.

Last, where does the expectation function come from? Consider a random variable \(X\). We can interpret the self-information (\(-\log(p)\)) as the amount of surprise we have at seeing a particular outcome. Indeed, as the probability approaches zero, the surprise becomes infinite. Similarly, we can interpret the entropy as the average amount of surprise from observing \(X\). For example, imagine that a slot machine system emits statistical independently symbols \({s_1, \ldots, s_k}\) with probabilities \({p_1, \ldots, p_k}\) respectively. Then the entropy of this system equals to the average self-information from observing each output, i.e.,

(22.11.6)\[H(S) = \sum_i {p_i \cdot I(s_i)} = - \sum_i {p_i \cdot \log p_i}.\]

22.11.2.4. Properties of Entropy

By the above examples and interpretations, we can derive the following properties of entropy (22.11.3). Here, we refer to \(X\) as an event and \(P\) as the probability distribution of \(X\).

  • \(H(X) \geq 0\) for all discrete \(X\) (entropy can be negative for continuous \(X\)).

  • If \(X \sim P\) with a p.d.f. or a p.m.f. \(p(x)\), and we try to estimate \(P\) by a new probability distribution \(Q\) with a p.d.f. or a p.m.f. \(q(x)\), then

    (22.11.7)\[H(X) = - E_{x \sim P} [\log p(x)] \leq - E_{x \sim P} [\log q(x)], \textrm{ with equality if and only if } P = Q.\]

    Alternatively, \(H(X)\) gives a lower bound of the average number of bits needed to encode symbols drawn from \(P\).

  • If \(X \sim P\), then \(x\) conveys the maximum amount of information if it spreads evenly among all possible outcomes. Specifically, if the probability distribution \(P\) is discrete with \(k\)-class \(\{p_1, \ldots, p_k \}\), then

    (22.11.8)\[H(X) \leq \log(k), \textrm{ with equality if and only if } p_i = \frac{1}{k}, \forall i.\]

    If \(P\) is a continuous random variable, then the story becomes much more complicated. However, if we additionally impose that \(P\) is supported on a finite interval (with all values between \(0\) and \(1\)), then \(P\) has the highest entropy if it is the uniform distribution on that interval.

22.11.3. Mutual Information

Previously we defined entropy of a single random variable \(X\), how about the entropy of a pair random variables \((X, Y)\)? We can think of these techniques as trying to answer the following type of question, “What information is contained in \(X\) and \(Y\) together compared to each separately? Is there redundant information, or is it all unique?”

For the following discussion, we always use \((X, Y)\) as a pair of random variables that follows a joint probability distribution \(P\) with a p.d.f. or a p.m.f. \(p_{X, Y}(x, y)\), while \(X\) and \(Y\) follow probability distribution \(p_X(x)\) and \(p_Y(y)\), respectively.

22.11.3.1. Joint Entropy

Similar to entropy of a single random variable (22.11.3), we define the joint entropy \(H(X, Y)\) of a pair random variables \((X, Y)\) as

(22.11.9)\[H(X, Y) = -E_{(x, y) \sim P} [\log p_{X, Y}(x, y)].\]

Precisely, on the one hand, if \((X, Y)\) is a pair of discrete random variables, then

(22.11.10)\[H(X, Y) = - \sum_{x} \sum_{y} p_{X, Y}(x, y) \log p_{X, Y}(x, y).\]

On the other hand, if \((X, Y)\) is a pair of continuous random variables, then we define the differential joint entropy as

(22.11.11)\[H(X, Y) = - \int_{x, y} p_{X, Y}(x, y) \ \log p_{X, Y}(x, y) \;dx \;dy.\]

We can think of (22.11.9) as telling us the total randomness in the pair of random variables. As a pair of extremes, if \(X = Y\) are two identical random variables, then the information in the pair is exactly the information in one and we have \(H(X, Y) = H(X) = H(Y)\). On the other extreme, if \(X\) and \(Y\) are independent then \(H(X, Y) = H(X) + H(Y)\). Indeed we will always have that the information contained in a pair of random variables is no smaller than the entropy of either random variable and no more than the sum of both.

(22.11.12)\[H(X), H(Y) \le H(X, Y) \le H(X) + H(Y).\]

Let’s implement joint entropy from scratch.

def joint_entropy(p_xy):
    joint_ent = -p_xy * torch.log2(p_xy)
    # Operator `nansum` will sum up the non-nan number
    out = nansum(joint_ent)
    return out

joint_entropy(torch.tensor([[0.1, 0.5], [0.1, 0.3]]))
tensor(1.6855)

Notice that this is the same code as before, but now we interpret it differently as working on the joint distribution of the two random variables.

22.11.3.2. Conditional Entropy

The joint entropy defined above the amount of information contained in a pair of random variables. This is useful, but oftentimes it is not what we care about. Consider the setting of machine learning. Let’s take \(X\) to be the random variable (or vector of random variables) that describes the pixel values of an image, and \(Y\) to be the random variable which is the class label. \(X\) should contain substantial information—a natural image is a complex thing. However, the information contained in \(Y\) once the image has been show should be low. Indeed, the image of a digit should already contain the information about what digit it is unless the digit is illegible. Thus, to continue to extend our vocabulary of information theory, we need to be able to reason about the information content in a random variable conditional on another.

In the probability theory, we saw the definition of the conditional probability to measure the relationship between variables. We now want to analogously define the conditional entropy \(H(Y \mid X)\). We can write this as

(22.11.13)\[H(Y \mid X) = - E_{(x, y) \sim P} [\log p(y \mid x)],\]

where \(p(y \mid x) = \frac{p_{X, Y}(x, y)}{p_X(x)}\) is the conditional probability. Specifically, if \((X, Y)\) is a pair of discrete random variables, then

(22.11.14)\[H(Y \mid X) = - \sum_{x} \sum_{y} p(x, y) \log p(y \mid x).\]

If \((X, Y)\) is a pair of continuous random variables, then the differential conditional entropy is similarly defined as

(22.11.15)\[H(Y \mid X) = - \int_x \int_y p(x, y) \ \log p(y \mid x) \;dx \;dy.\]

It is now natural to ask, how does the conditional entropy \(H(Y \mid X)\) relate to the entropy \(H(X)\) and the joint entropy \(H(X, Y)\)? Using the definitions above, we can express this cleanly:

(22.11.16)\[H(Y \mid X) = H(X, Y) - H(X).\]

This has an intuitive interpretation: the information in \(Y\) given \(X\) (\(H(Y \mid X)\)) is the same as the information in both \(X\) and \(Y\) together (\(H(X, Y)\)) minus the information already contained in \(X\). This gives us the information in \(Y\) which is not also represented in \(X\).

Now, let’s implement conditional entropy (22.11.13) from scratch.

def conditional_entropy(p_xy, p_x):
    p_y_given_x = p_xy/p_x
    cond_ent = -p_xy * torch.log2(p_y_given_x)
    # Operator `nansum` will sum up the non-nan number
    out = nansum(cond_ent)
    return out

conditional_entropy(torch.tensor([[0.1, 0.5], [0.2, 0.3]]),
                    torch.tensor([0.2, 0.8]))
tensor(0.8635)

22.11.3.3. Mutual Information

Given the previous setting of random variables \((X, Y)\), you may wonder: “Now that we know how much information is contained in \(Y\) but not in \(X\), can we similarly ask how much information is shared between \(X\) and \(Y\)?” The answer will be the mutual information of \((X, Y)\), which we will write as \(I(X, Y)\).

Rather than diving straight into the formal definition, let’s practice our intuition by first trying to derive an expression for the mutual information entirely based on terms we have constructed before. We wish to find the information shared between two random variables. One way we could try to do this is to start with all the information contained in both \(X\) and \(Y\) together, and then we take off the parts that are not shared. The information contained in both \(X\) and \(Y\) together is written as \(H(X, Y)\). We want to subtract from this the information contained in \(X\) but not in \(Y\), and the information contained in \(Y\) but not in \(X\). As we saw in the previous section, this is given by \(H(X \mid Y)\) and \(H(Y \mid X)\) respectively. Thus, we have that the mutual information should be

(22.11.17)\[I(X, Y) = H(X, Y) - H(Y \mid X) - H(X \mid Y).\]

Indeed, this is a valid definition for the mutual information. If we expand out the definitions of these terms and combine them, a little algebra shows that this is the same as

(22.11.18)\[I(X, Y) = E_{x} E_{y} \left\{ p_{X, Y}(x, y) \log\frac{p_{X, Y}(x, y)}{p_X(x) p_Y(y)} \right\}.\]

We can summarize all of these relationships in image Fig. 22.11.1. It is an excellent test of intuition to see why the following statements are all also equivalent to \(I(X, Y)\).

  • \(H(X) - H(X \mid Y)\)

  • \(H(Y) - H(Y \mid X)\)

  • \(H(X) + H(Y) - H(X, Y)\)

../_images/mutual-information.svg

Fig. 22.11.1 Mutual information’s relationship with joint entropy and conditional entropy.

In many ways we can think of the mutual information (22.11.18) as principled extension of correlation coefficient we saw in Section 22.6. This allows us to ask not only for linear relationships between variables, but for the maximum information shared between the two random variables of any kind.

Now, let’s implement mutual information from scratch.

def mutual_information(p_xy, p_x, p_y):
    p = p_xy / (p_x * p_y)
    mutual = p_xy * torch.log2(p)
    # Operator `nansum` will sum up the non-nan number
    out = nansum(mutual)
    return out

mutual_information(torch.tensor([[0.1, 0.5], [0.1, 0.3]]),
                   torch.tensor([0.2, 0.8]), torch.tensor([[0.75, 0.25]]))
tensor(0.7195)

22.11.3.4. Properties of Mutual Information

Rather than memorizing the definition of mutual information (22.11.18), you only need to keep in mind its notable properties:

  • Mutual information is symmetric, i.e., \(I(X, Y) = I(Y, X)\).

  • Mutual information is non-negative, i.e., \(I(X, Y) \geq 0\).

  • \(I(X, Y) = 0\) if and only if \(X\) and \(Y\) are independent. For example, if \(X\) and \(Y\) are independent, then knowing \(Y\) does not give any information about \(X\) and vice versa, so their mutual information is zero.

  • Alternatively, if \(X\) is an invertible function of \(Y\), then \(Y\) and \(X\) share all information and

    (22.11.19)\[I(X, Y) = H(Y) = H(X).\]

22.11.3.5. Pointwise Mutual Information

When we worked with entropy at the beginning of this chapter, we were able to provide an interpretation of \(-\log(p_X(x))\) as how surprised we were with the particular outcome. We may give a similar interpretation to the logarithmic term in the mutual information, which is often referred to as the pointwise mutual information:

(22.11.20)\[\textrm{pmi}(x, y) = \log\frac{p_{X, Y}(x, y)}{p_X(x) p_Y(y)}.\]

We can think of (22.11.20) as measuring how much more or less likely the specific combination of outcomes \(x\) and \(y\) are compared to what we would expect for independent random outcomes. If it is large and positive, then these two specific outcomes occur much more frequently than they would compared to random chance (note: the denominator is \(p_X(x) p_Y(y)\) which is the probability of the two outcomes were independent), whereas if it is large and negative it represents the two outcomes happening far less than we would expect by random chance.

This allows us to interpret the mutual information (22.11.18) as the average amount that we were surprised to see two outcomes occurring together compared to what we would expect if they were independent.

22.11.3.6. Applications of Mutual Information

Mutual information may be a little abstract in it pure definition, so how does it related to machine learning? In natural language processing, one of the most difficult problems is the ambiguity resolution, or the issue of the meaning of a word being unclear from context. For example, recently a headline in the news reported that “Amazon is on fire”. You may wonder whether the company Amazon has a building on fire, or the Amazon rain forest is on fire.

In this case, mutual information can help us resolve this ambiguity. We first find the group of words that each has a relatively large mutual information with the company Amazon, such as e-commerce, technology, and online. Second, we find another group of words that each has a relatively large mutual information with the Amazon rain forest, such as rain, forest, and tropical. When we need to disambiguate “Amazon”, we can compare which group has more occurrence in the context of the word Amazon. In this case the article would go on to describe the forest, and make the context clear.

22.11.4. Kullback–Leibler Divergence

As what we have discussed in Section 2.3, we can use norms to measure distance between two points in space of any dimensionality. We would like to be able to do a similar task with probability distributions. There are many ways to go about this, but information theory provides one of the nicest. We now explore the Kullback–Leibler (KL) divergence, which provides a way to measure if two distributions are close together or not.

22.11.4.1. Definition

Given a random variable \(X\) that follows the probability distribution \(P\) with a p.d.f. or a p.m.f. \(p(x)\), and we estimate \(P\) by another probability distribution \(Q\) with a p.d.f. or a p.m.f. \(q(x)\). Then the Kullback–Leibler (KL) divergence (or relative entropy) between \(P\) and \(Q\) is

(22.11.21)\[D_{\textrm{KL}}(P\|Q) = E_{x \sim P} \left[ \log \frac{p(x)}{q(x)} \right].\]

As with the pointwise mutual information (22.11.20), we can again provide an interpretation of the logarithmic term: \(-\log \frac{q(x)}{p(x)} = -\log(q(x)) - (-\log(p(x)))\) will be large and positive if we see \(x\) far more often under \(P\) than we would expect for \(Q\), and large and negative if we see the outcome far less than expected. In this way, we can interpret it as our relative surprise at observing the outcome compared to how surprised we would be observing it from our reference distribution.

Let’s implement the KL divergence from Scratch.

def kl_divergence(p, q):
    kl = p * torch.log2(p / q)
    out = nansum(kl)
    return out.abs().item()

22.11.4.2. KL Divergence Properties

Let’s take a look at some properties of the KL divergence (22.11.21).

  • KL divergence is non-symmetric, i.e., there are \(P,Q\) such that

    (22.11.22)\[D_{\textrm{KL}}(P\|Q) \neq D_{\textrm{KL}}(Q\|P).\]
  • KL divergence is non-negative, i.e.,

    (22.11.23)\[D_{\textrm{KL}}(P\|Q) \geq 0.\]

    Note that the equality holds only when \(P = Q\).

  • If there exists an \(x\) such that \(p(x) > 0\) and \(q(x) = 0\), then \(D_{\textrm{KL}}(P\|Q) = \infty\).

  • There is a close relationship between KL divergence and mutual information. Besides the relationship shown in Fig. 22.11.1, \(I(X, Y)\) is also numerically equivalent with the following terms:

    1. \(D_{\textrm{KL}}(P(X, Y) \ \| \ P(X)P(Y))\);

    2. \(E_Y \{ D_{\textrm{KL}}(P(X \mid Y) \ \| \ P(X)) \}\);

    3. \(E_X \{ D_{\textrm{KL}}(P(Y \mid X) \ \| \ P(Y)) \}\).

    For the first term, we interpret mutual information as the KL divergence between \(P(X, Y)\) and the product of \(P(X)\) and \(P(Y)\), and thus is a measure of how different the joint distribution is from the distribution if they were independent. For the second term, mutual information tells us the average reduction in uncertainty about \(Y\) that results from learning the value of the \(X\)’s distribution. Similarly to the third term.

22.11.4.3. Example

Let’s go through a toy example to see the non-symmetry explicitly.

First, let’s generate and sort three tensors of length \(10,000\): an objective tensor \(p\) which follows a normal distribution \(N(0, 1)\), and two candidate tensors \(q_1\) and \(q_2\) which follow normal distributions \(N(-1, 1)\) and \(N(1, 1)\) respectively.

torch.manual_seed(1)

tensor_len = 10000
p = torch.normal(0, 1, (tensor_len, ))
q1 = torch.normal(-1, 1, (tensor_len, ))
q2 = torch.normal(1, 1, (tensor_len, ))

p = torch.sort(p)[0]
q1 = torch.sort(q1)[0]
q2 = torch.sort(q2)[0]

Since \(q_1\) and \(q_2\) are symmetric with respect to the y-axis (i.e., \(x=0\)), we expect a similar value of KL divergence between \(D_{\textrm{KL}}(p\|q_1)\) and \(D_{\textrm{KL}}(p\|q_2)\). As you can see below, there is only a less than 3% off between \(D_{\textrm{KL}}(p\|q_1)\) and \(D_{\textrm{KL}}(p\|q_2)\).

kl_pq1 = kl_divergence(p, q1)
kl_pq2 = kl_divergence(p, q2)
similar_percentage = abs(kl_pq1 - kl_pq2) / ((kl_pq1 + kl_pq2) / 2) * 100

kl_pq1, kl_pq2, similar_percentage
(8582.0341796875, 8828.3095703125, 2.8290698237936858)

In contrast, you may find that \(D_{\textrm{KL}}(q_2 \|p)\) and \(D_{\textrm{KL}}(p \| q_2)\) are off a lot, with around 40% off as shown below.

kl_q2p = kl_divergence(q2, p)
differ_percentage = abs(kl_q2p - kl_pq2) / ((kl_q2p + kl_pq2) / 2) * 100

kl_q2p, differ_percentage
(14130.125, 46.18621024399691)

22.11.5. Cross-Entropy

If you are curious about applications of information theory in deep learning, here is a quick example. We define the true distribution \(P\) with probability distribution \(p(x)\), and the estimated distribution \(Q\) with probability distribution \(q(x)\), and we will use them in the rest of this section.

Say we need to solve a binary classification problem based on given \(n\) data examples {\(x_1, \ldots, x_n\)}. Assume that we encode \(1\) and \(0\) as the positive and negative class label \(y_i\) respectively, and our neural network is parametrized by \(\theta\). If we aim to find a best \(\theta\) so that \(\hat{y}_i= p_{\theta}(y_i \mid x_i)\), it is natural to apply the maximum log-likelihood approach as was seen in Section 22.7. To be specific, for true labels \(y_i\) and predictions \(\hat{y}_i= p_{\theta}(y_i \mid x_i)\), the probability to be classified as positive is \(\pi_i= p_{\theta}(y_i = 1 \mid x_i)\). Hence, the log-likelihood function would be

(22.11.24)\[\begin{split}\begin{aligned} l(\theta) &= \log L(\theta) \\ &= \log \prod_{i=1}^n \pi_i^{y_i} (1 - \pi_i)^{1 - y_i} \\ &= \sum_{i=1}^n y_i \log(\pi_i) + (1 - y_i) \log (1 - \pi_i). \\ \end{aligned}\end{split}\]

Maximizing the log-likelihood function \(l(\theta)\) is identical to minimizing \(- l(\theta)\), and hence we can find the best \(\theta\) from here. To generalize the above loss to any distributions, we also called \(-l(\theta)\) the cross-entropy loss \(\textrm{CE}(y, \hat{y})\), where \(y\) follows the true distribution \(P\) and \(\hat{y}\) follows the estimated distribution \(Q\).

This was all derived by working from the maximum likelihood point of view. However, if we look closely we can see that terms like \(\log(\pi_i)\) have entered into our computation which is a solid indication that we can understand the expression from an information theoretic point of view.

22.11.5.1. Formal Definition

Like KL divergence, for a random variable \(X\), we can also measure the divergence between the estimating distribution \(Q\) and the true distribution \(P\) via cross-entropy,

(22.11.25)\[\textrm{CE}(P, Q) = - E_{x \sim P} [\log(q(x))].\]

By using properties of entropy discussed above, we can also interpret it as the summation of the entropy \(H(P)\) and the KL divergence between \(P\) and \(Q\), i.e.,

(22.11.26)\[\textrm{CE} (P, Q) = H(P) + D_{\textrm{KL}}(P\|Q).\]

We can implement the cross-entropy loss as below.

def cross_entropy(y_hat, y):
    ce = -torch.log(y_hat[range(len(y_hat)), y])
    return ce.mean()

Now define two tensors for the labels and predictions, and calculate the cross-entropy loss of them.

labels = torch.tensor([0, 2])
preds = torch.tensor([[0.3, 0.6, 0.1], [0.2, 0.3, 0.5]])

cross_entropy(preds, labels)
tensor(0.9486)

22.11.5.2. Properties

As alluded in the beginning of this section, cross-entropy (22.11.25) can be used to define a loss function in the optimization problem. It turns out that the following are equivalent:

  1. Maximizing predictive probability of \(Q\) for distribution \(P\), (i.e., \(E_{x \sim P} [\log (q(x))]\));

  2. Minimizing cross-entropy \(\textrm{CE} (P, Q)\);

  3. Minimizing the KL divergence \(D_{\textrm{KL}}(P\|Q)\).

The definition of cross-entropy indirectly proves the equivalent relationship between objective 2 and objective 3, as long as the entropy of true data \(H(P)\) is constant.

22.11.5.3. Cross-Entropy as An Objective Function of Multi-class Classification

If we dive deep into the classification objective function with cross-entropy loss \(\textrm{CE}\), we will find minimizing \(\textrm{CE}\) is equivalent to maximizing the log-likelihood function \(L\).

To begin with, suppose that we are given a dataset with \(n\) examples, and it can be classified into \(k\)-classes. For each data example \(i\), we represent any \(k\)-class label \(\mathbf{y}_i = (y_{i1}, \ldots, y_{ik})\) by one-hot encoding. To be specific, if the example \(i\) belongs to class \(j\), then we set the \(j\)-th entry to \(1\), and all other components to \(0\), i.e.,

(22.11.27)\[\begin{split}y_{ij} = \begin{cases}1 & j \in J; \\ 0 &\textrm{otherwise.}\end{cases}\end{split}\]

For instance, if a multi-class classification problem contains three classes \(A\), \(B\), and \(C\), then the labels \(\mathbf{y}_i\) can be encoded in {\(A: (1, 0, 0); B: (0, 1, 0); C: (0, 0, 1)\)}.

Assume that our neural network is parametrized by \(\theta\). For true label vectors \(\mathbf{y}_i\) and predictions

(22.11.28)\[\hat{\mathbf{y}}_i= p_{\theta}(\mathbf{y}_i \mid \mathbf{x}_i) = \sum_{j=1}^k y_{ij} p_{\theta} (y_{ij} \mid \mathbf{x}_i).\]

Hence, the cross-entropy loss would be

(22.11.29)\[\begin{split}\textrm{CE}(\mathbf{y}, \hat{\mathbf{y}}) = - \sum_{i=1}^n \mathbf{y}_i \log \hat{\mathbf{y}}_i = - \sum_{i=1}^n \sum_{j=1}^k y_{ij} \log{p_{\theta} (y_{ij} \mid \mathbf{x}_i)}.\\\end{split}\]

On the other side, we can also approach the problem through maximum likelihood estimation. To begin with, let’s quickly introduce a \(k\)-class multinoulli distribution. It is an extension of the Bernoulli distribution from binary class to multi-class. If a random variable \(\mathbf{z} = (z_{1}, \ldots, z_{k})\) follows a \(k\)-class multinoulli distribution with probabilities \(\mathbf{p} =\) (\(p_{1}, \ldots, p_{k}\)), i.e.,

(22.11.30)\[p(\mathbf{z}) = p(z_1, \ldots, z_k) = \textrm{Multi} (p_1, \ldots, p_k), \textrm{ where } \sum_{i=1}^k p_i = 1,\]

then the joint probability mass function(p.m.f.) of \(\mathbf{z}\) is

(22.11.31)\[\mathbf{p}^\mathbf{z} = \prod_{j=1}^k p_{j}^{z_{j}}.\]

It can be seen that the label of each data example, \(\mathbf{y}_i\), is following a \(k\)-class multinoulli distribution with probabilities \(\boldsymbol{\pi} =\) (\(\pi_{1}, \ldots, \pi_{k}\)). Therefore, the joint p.m.f. of each data example \(\mathbf{y}_i\) is \(\mathbf{\pi}^{\mathbf{y}_i} = \prod_{j=1}^k \pi_{j}^{y_{ij}}.\) Hence, the log-likelihood function would be

(22.11.32)\[\begin{split}\begin{aligned} l(\theta) = \log L(\theta) = \log \prod_{i=1}^n \boldsymbol{\pi}^{\mathbf{y}_i} = \log \prod_{i=1}^n \prod_{j=1}^k \pi_{j}^{y_{ij}} = \sum_{i=1}^n \sum_{j=1}^k y_{ij} \log{\pi_{j}}.\\ \end{aligned}\end{split}\]

Since in maximum likelihood estimation, we maximizing the objective function \(l(\theta)\) by having \(\pi_{j} = p_{\theta} (y_{ij} \mid \mathbf{x}_i)\). Therefore, for any multi-class classification, maximizing the above log-likelihood function \(l(\theta)\) is equivalent to minimizing the CE loss \(\textrm{CE}(y, \hat{y})\).

To test the above proof, let’s apply the built-in measure NegativeLogLikelihood. Using the same labels and preds as in the earlier example, we will get the same numerical loss as the previous example up to the 5 decimal place.

# Implementation of cross-entropy loss in PyTorch combines `nn.LogSoftmax()`
# and `nn.NLLLoss()`
nll_loss = NLLLoss()
loss = nll_loss(torch.log(preds), labels)
loss
tensor(0.9486)

22.11.6. Summary

  • Information theory is a field of study about encoding, decoding, transmitting, and manipulating information.

  • Entropy is the unit to measure how much information is presented in different signals.

  • KL divergence can also measure the divergence between two distributions.

  • Cross-entropy can be viewed as an objective function of multi-class classification. Minimizing cross-entropy loss is equivalent to maximizing the log-likelihood function.

22.11.7. Exercises

  1. Verify that the card examples from the first section indeed have the claimed entropy.

  2. Show that the KL divergence \(D(p\|q)\) is nonnegative for all distributions \(p\) and \(q\). Hint: use Jensen’s inequality, i.e., use the fact that \(-\log x\) is a convex function.

  3. Let’s compute the entropy from a few data sources:

    • Assume that you are watching the output generated by a monkey at a typewriter. The monkey presses any of the \(44\) keys of the typewriter at random (you can assume that it has not discovered any special keys or the shift key yet). How many bits of randomness per character do you observe?

    • Being unhappy with the monkey, you replaced it by a drunk typesetter. It is able to generate words, albeit not coherently. Instead, it picks a random word out of a vocabulary of \(2,000\) words. Let’s assume that the average length of a word is \(4.5\) letters in English. How many bits of randomness per character do you observe now?

    • Still being unhappy with the result, you replace the typesetter by a high quality language model. The language model can currently obtain a perplexity as low as \(15\) points per word. The character perplexity of a language model is defined as the inverse of the geometric mean of a set of probabilities, each probability is corresponding to a character in the word. To be specific, if the length of a given word is \(l\), then \(\textrm{PPL}(\textrm{word}) = \left[\prod_i p(\textrm{character}_i)\right]^{ -\frac{1}{l}} = \exp \left[ - \frac{1}{l} \sum_i{\log p(\textrm{character}_i)} \right].\) Assume that the test word has 4.5 letters, how many bits of randomness per character do you observe now?

  4. Explain intuitively why \(I(X, Y) = H(X) - H(X \mid Y)\). Then, show this is true by expressing both sides as an expectation with respect to the joint distribution.

  5. What is the KL Divergence between the two Gaussian distributions \(\mathcal{N}(\mu_1, \sigma_1^2)\) and \(\mathcal{N}(\mu_2, \sigma_2^2)\)?

5.4. Numerical Stability and Initialization 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.

5.4. Numerical Stability and Initialization
Open the notebook in SageMaker Studio Lab

Thus far, every model that we have implemented required that we initialize its parameters according to some pre-specified distribution. Until now, we took the initialization scheme for granted, glossing over the details of how these choices are made. You might have even gotten the impression that these choices are not especially important. On the contrary, the choice of initialization scheme plays a significant role in neural network learning, and it can be crucial for maintaining numerical stability. Moreover, these choices can be tied up in interesting ways with the choice of the nonlinear activation function. Which function we choose and how we initialize parameters can determine how quickly our optimization algorithm converges. Poor choices here can cause us to encounter exploding or vanishing gradients while training. In this section, we delve into these topics in greater detail and discuss some useful heuristics that you will find useful throughout your career in deep learning.

%matplotlib inline
import torch
from d2l import torch as d2l

5.4.1. Vanishing and Exploding Gradients

Consider a deep network with \(L\) layers, input \(\mathbf{x}\) and output \(\mathbf{o}\). With each layer \(l\) defined by a transformation \(f_l\) parametrized by weights \(\mathbf{W}^{(l)}\), whose hidden layer output is \(\mathbf{h}^{(l)}\) (let \(\mathbf{h}^{(0)} = \mathbf{x}\)), our network can be expressed as:

(5.4.1)\[\mathbf{h}^{(l)} = f_l (\mathbf{h}^{(l-1)}) \textrm{ and thus } \mathbf{o} = f_L \circ \cdots \circ f_1(\mathbf{x}).\]

If all the hidden layer output and the input are vectors, we can write the gradient of \(\mathbf{o}\) with respect to any set of parameters \(\mathbf{W}^{(l)}\) as follows:

(5.4.2)\[\partial_{\mathbf{W}^{(l)}} \mathbf{o} = \underbrace{\partial_{\mathbf{h}^{(L-1)}} \mathbf{h}^{(L)}}_{ \mathbf{M}^{(L)} \stackrel{\textrm{def}}{=}} \cdots \underbrace{\partial_{\mathbf{h}^{(l)}} \mathbf{h}^{(l+1)}}_{ \mathbf{M}^{(l+1)} \stackrel{\textrm{def}}{=}} \underbrace{\partial_{\mathbf{W}^{(l)}} \mathbf{h}^{(l)}}_{ \mathbf{v}^{(l)} \stackrel{\textrm{def}}{=}}.\]

In other words, this gradient is the product of \(L-l\) matrices \(\mathbf{M}^{(L)} \cdots \mathbf{M}^{(l+1)}\) and the gradient vector \(\mathbf{v}^{(l)}\). Thus we are susceptible to the same problems of numerical underflow that often crop up when multiplying together too many probabilities. When dealing with probabilities, a common trick is to switch into log-space, i.e., shifting pressure from the mantissa to the exponent of the numerical representation. Unfortunately, our problem above is more serious: initially the matrices \(\mathbf{M}^{(l)}\) may have a wide variety of eigenvalues. They might be small or large, and their product might be very large or very small.

The risks posed by unstable gradients go beyond numerical representation. Gradients of unpredictable magnitude also threaten the stability of our optimization algorithms. We may be facing parameter updates that are either (i) excessively large, destroying our model (the exploding gradient problem); or (ii) excessively small (the vanishing gradient problem), rendering learning impossible as parameters hardly move on each update.

5.4.1.1. Vanishing Gradients

One frequent culprit causing the vanishing gradient problem is the choice of the activation function \(\sigma\) that is appended following each layer’s linear operations. Historically, the sigmoid function \(1/(1 + \exp(-x))\) (introduced in Section 5.1) was popular because it resembles a thresholding function. Since early artificial neural networks were inspired by biological neural networks, the idea of neurons that fire either fully or not at all (like biological neurons) seemed appealing. Let’s take a closer look at the sigmoid to see why it can cause vanishing gradients.

x = torch.arange(-8.0, 8.0, 0.1, requires_grad=True)
y = torch.sigmoid(x)
y.backward(torch.ones_like(x))

d2l.plot(x.detach().numpy(), [y.detach().numpy(), x.grad.numpy()],
         legend=['sigmoid', 'gradient'], figsize=(4.5, 2.5))
../_images/output_numerical-stability-and-init_e60514_18_0.svg

As you can see, the sigmoid’s gradient vanishes both when its inputs are large and when they are small. Moreover, when backpropagating through many layers, unless we are in the Goldilocks zone, where the inputs to many of the sigmoids are close to zero, the gradients of the overall product may vanish. When our network boasts many layers, unless we are careful, the gradient will likely be cut off at some layer. Indeed, this problem used to plague deep network training. Consequently, ReLUs, which are more stable (but less neurally plausible), have emerged as the default choice for practitioners.

5.4.1.2. Exploding Gradients

The opposite problem, when gradients explode, can be similarly vexing. To illustrate this a bit better, we draw 100 Gaussian random matrices and multiply them with some initial matrix. For the scale that we picked (the choice of the variance \(\sigma^2=1\)), the matrix product explodes. When this happens because of the initialization of a deep network, we have no chance of getting a gradient descent optimizer to converge.

M = torch.normal(0, 1, size=(4, 4))
print('a single matrix \n',M)
for i in range(100):
    M = M @ torch.normal(0, 1, size=(4, 4))
print('after multiplying 100 matrices\n', M)
a single matrix
 tensor([[-0.8755, -1.2171,  1.3316,  0.1357],
        [ 0.4399,  1.4073, -1.9131, -0.4608],
        [-2.1420,  0.3643, -0.5267,  1.0277],
        [-0.1734, -0.7549,  2.3024,  1.3085]])
after multiplying 100 matrices
 tensor([[-2.9185e+23,  1.3915e+25, -1.1865e+25,  1.4354e+24],
        [ 4.9142e+23, -2.3430e+25,  1.9979e+25, -2.4169e+24],
        [ 2.6578e+23, -1.2672e+25,  1.0805e+25, -1.3072e+24],
        [-5.2223e+23,  2.4899e+25, -2.1231e+25,  2.5684e+24]])

5.4.1.3. Breaking the Symmetry

Another problem in neural network design is the symmetry inherent in their parametrization. Assume that we have a simple MLP with one hidden layer and two units. In this case, we could permute the weights \(\mathbf{W}^{(1)}\) of the first layer and likewise permute the weights of the output layer to obtain the same function. There is nothing special differentiating the first and second hidden units. In other words, we have permutation symmetry among the hidden units of each layer.

This is more than just a theoretical nuisance. Consider the aforementioned one-hidden-layer MLP with two hidden units. For illustration, suppose that the output layer transforms the two hidden units into only one output unit. Imagine what would happen if we initialized all the parameters of the hidden layer as \(\mathbf{W}^{(1)} = c\) for some constant \(c\). In this case, during forward propagation either hidden unit takes the same inputs and parameters producing the same activation which is fed to the output unit. During backpropagation, differentiating the output unit with respect to parameters \(\mathbf{W}^{(1)}\) gives a gradient all of whose elements take the same value. Thus, after gradient-based iteration (e.g., minibatch stochastic gradient descent), all the elements of \(\mathbf{W}^{(1)}\) still take the same value. Such iterations would never break the symmetry on their own and we might never be able to realize the network’s expressive power. The hidden layer would behave as if it had only a single unit. Note that while minibatch stochastic gradient descent would not break this symmetry, dropout regularization (to be introduced later) would!

5.4.2. Parameter Initialization

One way of addressing—or at least mitigating—the issues raised above is through careful initialization. As we will see later, additional care during optimization and suitable regularization can further enhance stability.

5.4.2.1. Default Initialization

In the previous sections, e.g., in Section 3.5, we used a normal distribution to initialize the values of our weights. If we do not specify the initialization method, the framework will use a default random initialization method, which often works well in practice for moderate problem sizes.

5.4.2.2. Xavier Initialization

Let’s look at the scale distribution of an output \(o_{i}\) for some fully connected layer without nonlinearities. With \(n_\textrm{in}\) inputs \(x_j\) and their associated weights \(w_{ij}\) for this layer, an output is given by

(5.4.3)\[o_{i} = \sum_{j=1}^{n_\textrm{in}} w_{ij} x_j.\]

The weights \(w_{ij}\) are all drawn independently from the same distribution. Furthermore, let’s assume that this distribution has zero mean and variance \(\sigma^2\). Note that this does not mean that the distribution has to be Gaussian, just that the mean and variance need to exist. For now, let’s assume that the inputs to the layer \(x_j\) also have zero mean and variance \(\gamma^2\) and that they are independent of \(w_{ij}\) and independent of each other. In this case, we can compute the mean of \(o_i\):

(5.4.4)\[\begin{split}\begin{aligned} E[o_i] & = \sum_{j=1}^{n_\textrm{in}} E[w_{ij} x_j] \\&= \sum_{j=1}^{n_\textrm{in}} E[w_{ij}] E[x_j] \\&= 0, \end{aligned}\end{split}\]

and the variance:

(5.4.5)\[\begin{split}\begin{aligned} \textrm{Var}[o_i] & = E[o_i^2] - (E[o_i])^2 \\ & = \sum_{j=1}^{n_\textrm{in}} E[w^2_{ij} x^2_j] - 0 \\ & = \sum_{j=1}^{n_\textrm{in}} E[w^2_{ij}] E[x^2_j] \\ & = n_\textrm{in} \sigma^2 \gamma^2. \end{aligned}\end{split}\]

One way to keep the variance fixed is to set \(n_\textrm{in} \sigma^2 = 1\). Now consider backpropagation. There we face a similar problem, albeit with gradients being propagated from the layers closer to the output. Using the same reasoning as for forward propagation, we see that the gradients’ variance can blow up unless \(n_\textrm{out} \sigma^2 = 1\), where \(n_\textrm{out}\) is the number of outputs of this layer. This leaves us in a dilemma: we cannot possibly satisfy both conditions simultaneously. Instead, we simply try to satisfy:

(5.4.6)\[\begin{aligned} \frac{1}{2} (n_\textrm{in} + n_\textrm{out}) \sigma^2 = 1 \textrm{ or equivalently } \sigma = \sqrt{\frac{2}{n_\textrm{in} + n_\textrm{out}}}. \end{aligned}\]

This is the reasoning underlying the now-standard and practically beneficial Xavier initialization, named after the first author of its creators (Glorot and Bengio, 2010). Typically, the Xavier initialization samples weights from a Gaussian distribution with zero mean and variance \(\sigma^2 = \frac{2}{n_\textrm{in} + n_\textrm{out}}\). We can also adapt this to choose the variance when sampling weights from a uniform distribution. Note that the uniform distribution \(U(-a, a)\) has variance \(\frac{a^2}{3}\). Plugging \(\frac{a^2}{3}\) into our condition on \(\sigma^2\) prompts us to initialize according to

(5.4.7)\[U\left(-\sqrt{\frac{6}{n_\textrm{in} + n_\textrm{out}}}, \sqrt{\frac{6}{n_\textrm{in} + n_\textrm{out}}}\right).\]

Though the assumption for nonexistence of nonlinearities in the above mathematical reasoning can be easily violated in neural networks, the Xavier initialization method turns out to work well in practice.

5.4.2.3. Beyond

The reasoning above barely scratches the surface of modern approaches to parameter initialization. A deep learning framework often implements over a dozen different heuristics. Moreover, parameter initialization continues to be a hot area of fundamental research in deep learning. Among these are heuristics specialized for tied (shared) parameters, super-resolution, sequence models, and other situations. For instance, Xiao et al. (2018) demonstrated the possibility of training 10,000-layer neural networks without architectural tricks by using a carefully-designed initialization method.

If the topic interests you we suggest a deep dive into this module’s offerings, reading the papers that proposed and analyzed each heuristic, and then exploring the latest publications on the topic. Perhaps you will stumble across or even invent a clever idea and contribute an implementation to deep learning frameworks.

5.4.3. Summary

Vanishing and exploding gradients are common issues in deep networks. Great care in parameter initialization is required to ensure that gradients and parameters remain well controlled. Initialization heuristics are needed to ensure that the initial gradients are neither too large nor too small. Random initialization is key to ensuring that symmetry is broken before optimization. Xavier initialization suggests that, for each layer, variance of any output is not affected by the number of inputs, and variance of any gradient is not affected by the number of outputs. ReLU activation functions mitigate the vanishing gradient problem. This can accelerate convergence.

5.4.4. Exercises

  1. Can you design other cases where a neural network might exhibit symmetry that needs breaking, besides the permutation symmetry in an MLP’s layers?

  2. Can we initialize all weight parameters in linear regression or in softmax regression to the same value?

  3. Look up analytic bounds on the eigenvalues of the product of two matrices. What does this tell you about ensuring that gradients are well conditioned?

  4. If we know that some terms diverge, can we fix this after the fact? Look at the paper on layerwise adaptive rate scaling for inspiration (You et al., 2017).

1.1. Linear Models

Assigned source reading · The scikit-learn developers

Copyright (c) 2007–2026 The scikit-learn developers. All rights reserved.

Original source · BSD 3-Clause 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
BSD 3-Clause License

Copyright (c) 2007-2026 The scikit-learn developers.
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

* Redistributions of source code must retain the above copyright notice, this
  list of conditions and the following disclaimer.

* Redistributions in binary form must reproduce the above copyright notice,
  this list of conditions and the following disclaimer in the documentation
  and/or other materials provided with the distribution.

* Neither the name of the copyright holder nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE LIABLE
FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL
DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY,
OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

1.1. Linear Models

The following are a set of methods intended for regression in which the target value is expected to be a linear combination of the features. In mathematical notation, the predicted value \(\hat{y}\) can be written as:

\[\hat{y}(w, x) = w_0 + w_1 x_1 + ... + w_p x_p\]

Across the module, we designate the vector \(w = (w_1, ..., w_p)\) as coef_ and \(w_0\) as intercept_.

To perform classification with generalized linear models, see Logistic regression.

1.1.1. Ordinary Least Squares

LinearRegression fits a linear model with coefficients \(w = (w_1, ..., w_p)\) to minimize the residual sum of squares between the observed targets in the dataset, and the targets predicted by the linear approximation. Mathematically it solves a problem of the form:

\[\min_{w} || X w - y||_2^2\]
../_images/sphx_glr_plot_ols_ridge_001.png

LinearRegression takes in its fit method arguments X, y, sample_weight and stores the coefficients \(w\) of the linear model in its coef_ and intercept_ attributes:

>>> from sklearn import linear_model
>>> reg = linear_model.LinearRegression()
>>> reg.fit([[0, 0], [1, 1], [2, 2]], [0, 1, 2])
LinearRegression()
>>> reg.coef_
array([0.5, 0.5])
>>> reg.intercept_
0.0

The coefficient estimates for Ordinary Least Squares rely on the independence of the features. When features are correlated and some columns of the design matrix \(X\) have an approximately linear dependence, the design matrix becomes close to singular and as a result, the least-squares estimate becomes highly sensitive to random errors in the observed target, producing a large variance. This situation of multicollinearity can arise, for example, when data are collected without an experimental design.

Examples

1.1.1.1. Non-Negative Least Squares

It is possible to constrain all the coefficients to be non-negative, which may be useful when they represent some physical or naturally non-negative quantities (e.g., frequency counts or prices of goods). LinearRegression accepts a boolean positive parameter: when set to True Non-Negative Least Squares are then applied.

Examples

1.1.1.2. Ordinary Least Squares Complexity

The least squares solution is computed using the singular value decomposition of \(X\). If \(X\) is a matrix of shape (n_samples, n_features) this method has a cost of \(O(n_{\text{samples}} n_{\text{features}}^2)\), assuming that \(n_{\text{samples}} \geq n_{\text{features}}\).

1.1.2. Ridge regression and classification

1.1.2.1. Regression

Ridge regression addresses some of the problems of Ordinary Least Squares by imposing a penalty on the size of the coefficients. The ridge coefficients minimize a penalized residual sum of squares:

\[\min_{w} || X w - y||_2^2 + \alpha ||w||_2^2\]

The complexity parameter \(\alpha \geq 0\) controls the amount of shrinkage: the larger the value of \(\alpha\), the greater the amount of shrinkage and thus the coefficients become more robust to collinearity.

../_images/sphx_glr_plot_ridge_path_001.png

As with other linear models, Ridge will take in its fit method arrays X, y and will store the coefficients \(w\) of the linear model in its coef_ member:

>>> from sklearn import linear_model
>>> reg = linear_model.Ridge(alpha=.5)
>>> reg.fit([[0, 0], [0, 0], [1, 1]], [0, .1, 1])
Ridge(alpha=0.5)
>>> reg.coef_
array([0.34545455, 0.34545455])
>>> reg.intercept_
np.float64(0.13636)

Note that the class Ridge allows for the user to specify that the solver be automatically chosen by setting solver="auto". When this option is specified, Ridge will choose between the "lbfgs", "cholesky", and "sparse_cg" solvers. Ridge will begin checking the conditions shown in the following table from top to bottom. If the condition is true, the corresponding solver is chosen.

Solver

Condition

‘lbfgs’

The positive=True option is specified.

‘cholesky’

The input array X is not sparse.

‘sparse_cg’

None of the above conditions are fulfilled.

Examples

1.1.2.2. Classification

The Ridge regressor has a classifier variant: RidgeClassifier. This classifier first converts binary targets to {-1, 1} and then treats the problem as a regression task, optimizing the same objective as above. The predicted class corresponds to the sign of the regressor’s prediction. For multiclass classification, the problem is treated as multi-output regression, and the predicted class corresponds to the output with the highest value.

It might seem questionable to use a (penalized) Least Squares loss to fit a classification model instead of the more traditional logistic or hinge losses. However, in practice, all those models can lead to similar cross-validation scores in terms of accuracy or precision/recall, while the penalized least squares loss used by the RidgeClassifier allows for a very different choice of the numerical solvers with distinct computational performance profiles.

The RidgeClassifier can be significantly faster than e.g. LogisticRegression with a high number of classes because it can compute the projection matrix \((X^T X)^{-1} X^T\) only once.

This classifier is sometimes referred to as a Least Squares Support Vector Machine with a linear kernel.

Examples

1.1.2.3. Ridge Complexity

This method has the same order of complexity as Ordinary Least Squares.

1.1.2.4. Setting the regularization parameter: leave-one-out Cross-Validation

RidgeCV and RidgeClassifierCV implement ridge regression/classification with built-in cross-validation of the alpha parameter. They work in the same way as GridSearchCV except that it defaults to efficient Leave-One-Out cross-validation. When using the default cross-validation, alpha cannot be 0 due to the formulation used to calculate Leave-One-Out error. See [RL2007] for details.

Usage example:

>>> import numpy as np
>>> from sklearn import linear_model
>>> reg = linear_model.RidgeCV(alphas=np.logspace(-6, 6, 13))
>>> reg.fit([[0, 0], [0, 0.1], [1, 1]], [0, -0.1, 1])
RidgeCV(alphas=array([1.e-06, 1.e-05, 1.e-04, 1.e-03, 1.e-02, 1.e-01, 1.e+00, 1.e+01,
      1.e+02, 1.e+03, 1.e+04, 1.e+05, 1.e+06]))
>>> reg.alpha_
np.float64(0.1)

Specifying the value of the cv attribute will trigger the use of cross-validation with GridSearchCV, for example cv=10 for 10-fold cross-validation, rather than Leave-One-Out Cross-Validation.

References
[RL2007]

“Notes on Regularized Least Squares”, Rifkin & Lippert (technical report, course slides).

1.1.3. Lasso

The Lasso is a linear model that estimates sparse coefficients, i.e., it is able to set coefficients exactly to zero. It is useful in some contexts due to its tendency to prefer solutions with fewer non-zero coefficients, effectively reducing the number of features upon which the given solution is dependent. For this reason, Lasso and its variants are fundamental to the field of compressed sensing. Under certain conditions, it can recover the exact set of non-zero coefficients (see Compressive sensing: tomography reconstruction with L1 prior (Lasso)).

Mathematically, it consists of a linear model with an added regularization term. The objective function to minimize is:

\[\min_{w} P(w) = {\frac{1}{2n_{\text{samples}}} ||X w - y||_2 ^ 2 + \alpha ||w||_1}\]

The lasso estimate thus solves the least-squares with added penalty \(\alpha ||w||_1\), where \(\alpha\) is a constant and \(||w||_1\) is the \(\ell_1\)-norm of the coefficient vector.

The implementation in the class Lasso uses coordinate descent as the algorithm to fit the coefficients. See Least Angle Regression for another implementation:

>>> from sklearn import linear_model
>>> reg = linear_model.Lasso(alpha=0.1)
>>> reg.fit([[0, 0], [1, 1]], [0, 1])
Lasso(alpha=0.1)
>>> reg.predict([[1, 1]])
array([0.8])

The function lasso_path is useful for lower-level tasks, as it computes the coefficients along the full path of possible values.

Examples

Note

Feature selection with Lasso

As the Lasso regression yields sparse models, it can thus be used to perform feature selection, as detailed in L1-based feature selection.

References

The following references explain the origin of the Lasso as well as properties of the Lasso problem and the duality gap computation used for convergence control.

1.1.3.1. Coordinate Descent with Gap Safe Screening Rules

Coordinate descent (CD) is a strategy to solve a minimization problem that considers a single feature \(j\) at a time. This way, the optimization problem is reduced to a 1-dimensional problem which is easier to solve:

\[\min_{w_j} {\frac{1}{2n_{\text{samples}}} ||x_j w_j + X_{-j}w_{-j} - y||_2 ^ 2 + \alpha |w_j|}\]

with index \(-j\) meaning all features but \(j\). The solution is

\[w_j = \frac{S(x_j^T (y - X_{-j}w_{-j}), \alpha)}{||x_j||_2^2}\]

with the soft-thresholding function \(S(z, \alpha) = \operatorname{sign}(z) \max(0, |z|-\alpha)\). Note that the soft-thresholding function is exactly zero whenever \(\alpha \geq |z|\). The CD solver then loops over the features either in a cycle, picking one feature after the other in the order given by X (selection="cyclic"), or by randomly picking features (selection="random"). It stops if the duality gap is smaller than the provided tolerance tol.

Mathematical details

The duality gap \(G(w, v)\) is an upper bound of the difference between the current primal objective function of the Lasso, \(P(w)\), and its minimum \(P(w^\star)\), i.e. \(G(w, v) \geq P(w) - P(w^\star)\). It is given by \(G(w, v) = P(w) - D(v)\) with dual objective function

\[D(v) = \frac{1}{2n_{\text{samples}}}(y^Tv - ||v||_2^2)\]

subject to \(v \in ||X^Tv||_{\infty} \leq n_{\text{samples}}\alpha\). At optimum, the duality gap is zero, \(G(w^\star, v^\star) = 0\) (a property called strong duality). With (scaled) dual variable \(v = c r\), current residual \(r = y - Xw\) and dual scaling

\[\begin{split}c = \begin{cases} 1, & ||X^Tr||_{\infty} \leq n_{\text{samples}}\alpha, \\ \frac{n_{\text{samples}}\alpha}{||X^Tr||_{\infty}}, & \text{otherwise} \end{cases}\end{split}\]

the stopping criterion is

\[\text{tol} \frac{||y||_2^2}{n_{\text{samples}}} < G(w, cr)\,.\]

A clever method to speedup the coordinate descent algorithm is to screen features such that at optimum \(w_j = 0\). Gap safe screening rules are such a tool. Anywhere during the optimization algorithm, they can tell which feature we can safely exclude, i.e., set to zero with certainty.

References

1.1.3.2. Setting regularization parameter

The alpha parameter controls the degree of sparsity of the estimated coefficients.

1.1.3.2.1. Using cross-validation

scikit-learn exposes objects that set the Lasso alpha parameter by cross-validation: LassoCV and LassoLarsCV. LassoLarsCV is based on the Least Angle Regression algorithm explained below.

For high-dimensional datasets with many collinear features, LassoCV is most often preferable. However, LassoLarsCV has the advantage of exploring more relevant values of alpha parameter, and if the number of samples is very small compared to the number of features, it is often faster than LassoCV.

lasso_cv_1 lasso_cv_2

1.1.3.2.2. Information-criteria based model selection

Alternatively, the estimator LassoLarsIC proposes to use the Akaike information criterion (AIC) and the Bayes Information criterion (BIC). It is a computationally cheaper alternative to find the optimal value of alpha as the regularization path is computed only once instead of k+1 times when using k-fold cross-validation.

Indeed, these criteria are computed on the in-sample training set. In short, they penalize the over-optimistic scores of the different Lasso models by their flexibility (cf. to “Mathematical details” section below).

However, such criteria need a proper estimation of the degrees of freedom of the solution, are derived for large samples (asymptotic results) and assume the correct model is candidates under investigation. They also tend to break when the problem is badly conditioned (e.g. more features than samples).

../_images/sphx_glr_plot_lasso_lars_ic_001.png

Examples

1.1.3.2.3. AIC and BIC criteria

The definition of AIC (and thus BIC) might differ in the literature. In this section, we give more information regarding the criterion computed in scikit-learn.

Mathematical details

The AIC criterion is defined as:

\[AIC = -2 \log(\hat{L}) + 2 d\]

where \(\hat{L}\) is the maximum likelihood of the model and \(d\) is the number of parameters (as well referred to as degrees of freedom in the previous section).

The definition of BIC replaces the constant \(2\) by \(\log(N)\):

\[BIC = -2 \log(\hat{L}) + \log(N) d\]

where \(N\) is the number of samples.

For a linear Gaussian model, the maximum log-likelihood is defined as:

\[\log(\hat{L}) = - \frac{n}{2} \log(2 \pi) - \frac{n}{2} \log(\sigma^2) - \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{2\sigma^2}\]

where \(\sigma^2\) is an estimate of the noise variance, \(y_i\) and \(\hat{y}_i\) are respectively the true and predicted targets, and \(n\) is the number of samples.

Plugging the maximum log-likelihood in the AIC formula yields:

\[AIC = n \log(2 \pi \sigma^2) + \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{\sigma^2} + 2 d\]

The first term of the above expression is sometimes discarded since it is a constant when \(\sigma^2\) is provided. In addition, it is sometimes stated that the AIC is equivalent to the \(C_p\) statistic [12]. In a strict sense, however, it is equivalent only up to some constant and a multiplicative factor.

At last, we mentioned above that \(\sigma^2\) is an estimate of the noise variance. In LassoLarsIC when the parameter noise_variance is not provided (default), the noise variance is estimated via the unbiased estimator [13] defined as:

\[\sigma^2 = \frac{\sum_{i=1}^{n} (y_i - \hat{y}_i)^2}{n - p}\]

where \(p\) is the number of features and \(\hat{y}_i\) is the predicted target using an ordinary least squares regression. Note, that this formula is valid only when n_samples > n_features.

References

1.1.3.2.4. Comparison with the regularization parameter of SVM

The equivalence between alpha and the regularization parameter of SVM, C is given by alpha = 1 / C or alpha = 1 / (n_samples * C), depending on the estimator and the exact objective function optimized by the model.

1.1.4. Multi-task Lasso

The MultiTaskLasso is a linear model that estimates sparse coefficients for multiple regression problems jointly: y is a 2D array, of shape (n_samples, n_tasks). The constraint is that the selected features are the same for all the regression problems, also called tasks.

The following figure compares the location of the non-zero entries in the coefficient matrix W obtained with a simple Lasso or a MultiTaskLasso. The Lasso estimates yield scattered non-zeros while the non-zeros of the MultiTaskLasso are full columns.

multi_task_lasso_1 multi_task_lasso_2

Fitting a time-series model, imposing that any active feature be active at all times.

Examples

Mathematical details

Mathematically, it consists of a linear model trained with a mixed \(\ell_1\) \(\ell_2\)-norm for regularization. The objective function to minimize is:

\[\min_{W} { \frac{1}{2n_{\text{samples}}} ||X W - Y||_{\text{Fro}} ^ 2 + \alpha ||W||_{21}}\]

where \(\text{Fro}\) indicates the Frobenius norm

\[||A||_{\text{Fro}} = \sqrt{\sum_{ij} a_{ij}^2}\]

and \(\ell_1\) \(\ell_2\) reads

\[||A||_{2 1} = \sum_i \sqrt{\sum_j a_{ij}^2}.\]

The implementation in the class MultiTaskLasso uses coordinate descent as the algorithm to fit the coefficients.

1.1.5. Elastic-Net

ElasticNet is a linear regression model trained with both \(\ell_1\) and \(\ell_2\)-norm regularization of the coefficients. This combination allows for learning a sparse model where few of the weights are non-zero like Lasso, while still maintaining the regularization properties of Ridge. We control the convex combination of \(\ell_1\) and \(\ell_2\) using the l1_ratio parameter.

Elastic-net is useful when there are multiple features that are correlated with one another. Lasso is likely to pick one of these at random, while elastic-net is likely to pick both.

A practical advantage of trading-off between Lasso and Ridge is that it allows Elastic-Net to inherit some of Ridge’s stability under rotation.

The objective function to minimize is in this case

\[\min_{w} { \frac{1}{2n_{\text{samples}}} ||X w - y||_2 ^ 2 + \alpha \rho ||w||_1 + \frac{\alpha(1-\rho)}{2} ||w||_2 ^ 2}\]
../_images/sphx_glr_plot_lasso_lasso_lars_elasticnet_path_002.png

The class ElasticNetCV can be used to set the parameters alpha (\(\alpha\)) and l1_ratio (\(\rho\)) by cross-validation.

Examples

References

The following two references explain the iterations used in the coordinate descent solver of scikit-learn, as well as the duality gap computation used for convergence control.

  • “Regularization Path For Generalized linear Models by Coordinate Descent”, Friedman, Hastie & Tibshirani, J Stat Softw, 2010 (Paper).

  • “An Interior-Point Method for Large-Scale L1-Regularized Least Squares,” S. J. Kim, K. Koh, M. Lustig, S. Boyd and D. Gorinevsky, in IEEE Journal of Selected Topics in Signal Processing, 2007 (Paper)

1.1.6. Multi-task Elastic-Net

The MultiTaskElasticNet is an elastic-net model that estimates sparse coefficients for multiple regression problems jointly: Y is a 2D array of shape (n_samples, n_tasks). The constraint is that the selected features are the same for all the regression problems, also called tasks.

Mathematically, it consists of a linear model trained with a mixed \(\ell_1\) \(\ell_2\)-norm and \(\ell_2\)-norm for regularization. The objective function to minimize is:

\[\min_{W} { \frac{1}{2n_{\text{samples}}} ||X W - Y||_{\text{Fro}}^2 + \alpha \rho ||W||_{2 1} + \frac{\alpha(1-\rho)}{2} ||W||_{\text{Fro}}^2}\]

The implementation in the class MultiTaskElasticNet uses coordinate descent as the algorithm to fit the coefficients.

The class MultiTaskElasticNetCV can be used to set the parameters alpha (\(\alpha\)) and l1_ratio (\(\rho\)) by cross-validation.

1.1.7. Least Angle Regression

Least-angle regression (LARS) is a regression algorithm for high-dimensional data, developed by Bradley Efron, Trevor Hastie, Iain Johnstone and Robert Tibshirani. LARS is similar to forward stepwise regression. At each step, it finds the feature most correlated with the target. When there are multiple features having equal correlation, instead of continuing along the same feature, it proceeds in a direction equiangular between the features.

The advantages of LARS are:

  • It is numerically efficient in contexts where the number of features is significantly greater than the number of samples.

  • It is computationally just as fast as forward selection and has the same order of complexity as ordinary least squares.

  • It produces a full piecewise linear solution path, which is useful in cross-validation or similar attempts to tune the model.

  • If two features are almost equally correlated with the target, then their coefficients should increase at approximately the same rate. The algorithm thus behaves as intuition would expect, and also is more stable.

  • It is easily modified to produce solutions for other estimators, like the Lasso.

The disadvantages of the LARS method include:

  • Because LARS is based upon an iterative refitting of the residuals, it would appear to be especially sensitive to the effects of noise. This problem is discussed in detail by Weisberg in the discussion section of the Efron et al. (2004) Annals of Statistics article.

The LARS model can be used via the estimator Lars, or its low-level implementation lars_path or lars_path_gram.

1.1.8. LARS Lasso

LassoLars is a lasso model implemented using the LARS algorithm, and unlike the implementation based on coordinate descent, this yields the exact solution, which is piecewise linear as a function of the norm of its coefficients.

../_images/sphx_glr_plot_lasso_lasso_lars_elasticnet_path_001.png
>>> from sklearn import linear_model
>>> reg = linear_model.LassoLars(alpha=.1)
>>> reg.fit([[0, 0], [1, 1]], [0, 1])
LassoLars(alpha=0.1)
>>> reg.coef_
array([0.6, 0.        ])

Examples

The LARS algorithm provides the full path of the coefficients along the regularization parameter almost for free, thus a common operation is to retrieve the path with one of the functions lars_path or lars_path_gram.

Mathematical formulation

The algorithm is similar to forward stepwise regression, but instead of including features at each step, the estimated coefficients are increased in a direction equiangular to each one’s correlations with the residual.

Instead of giving a vector result, the LARS solution consists of a curve denoting the solution for each value of the \(\ell_1\) norm of the parameter vector. The full coefficients path is stored in the array coef_path_ of shape (n_features, max_features + 1). The first column is always zero.

References

1.1.9. Orthogonal Matching Pursuit (OMP)

OrthogonalMatchingPursuit and orthogonal_mp implement the OMP algorithm for approximating the fit of a linear model with constraints imposed on the number of non-zero coefficients (i.e. the \(\ell_0\) pseudo-norm).

Being a forward feature selection method like Least Angle Regression, orthogonal matching pursuit can approximate the optimum solution vector with a fixed number of non-zero elements:

\[\underset{w}{\operatorname{arg\,min\,}} ||y - Xw||_2^2 \text{ subject to } ||w||_0 \leq n_{\text{nonzero_coefs}}\]

Alternatively, orthogonal matching pursuit can target a specific error instead of a specific number of non-zero coefficients. This can be expressed as:

\[\underset{w}{\operatorname{arg\,min\,}} ||w||_0 \text{ subject to } ||y-Xw||_2^2 \leq \text{tol}\]

OMP is based on a greedy algorithm that includes at each step the atom most highly correlated with the current residual. It is similar to the simpler matching pursuit (MP) method, but better in that at each iteration, the residual is recomputed using an orthogonal projection on the space of the previously chosen dictionary elements.

Examples

References

1.1.10. Bayesian Regression

Bayesian regression techniques can be used to include regularization parameters in the estimation procedure: the regularization parameter is not set in a hard sense but tuned to the data at hand.

This can be done by introducing uninformative priors over the hyper parameters of the model. The \(\ell_{2}\) regularization used in Ridge regression and classification is equivalent to finding a maximum a posteriori estimation under a Gaussian prior over the coefficients \(w\) with precision \(\lambda^{-1}\). Instead of setting lambda manually, it is possible to treat it as a random variable to be estimated from the data.

To obtain a fully probabilistic model, the output \(y\) is assumed to be Gaussian distributed around \(X w\):

\[p(y|X,w,\alpha) = \mathcal{N}(y|X w,\alpha^{-1})\]

where \(\alpha\) is again treated as a random variable that is to be estimated from the data.

The advantages of Bayesian Regression are:

  • It adapts to the data at hand.

  • It can be used to include regularization parameters in the estimation procedure.

The disadvantages of Bayesian regression include:

  • Inference of the model can be time consuming.

References

1.1.10.1. Bayesian Ridge Regression

BayesianRidge estimates a probabilistic model of the regression problem as described above. The prior for the coefficient \(w\) is given by a spherical Gaussian:

\[p(w|\lambda) = \mathcal{N}(w|0,\lambda^{-1}\mathbf{I}_{p})\]

The priors over \(\alpha\) and \(\lambda\) are chosen to be gamma distributions, the conjugate prior for the precision of the Gaussian. The resulting model is called Bayesian Ridge Regression, and is similar to the classical Ridge.

The parameters \(w\), \(\alpha\) and \(\lambda\) are estimated jointly during the fit of the model, the regularization parameters \(\alpha\) and \(\lambda\) being estimated by maximizing the log marginal likelihood. The scikit-learn implementation is based on the algorithm described in Appendix A of (Tipping, 2001) where the update of the parameters \(\alpha\) and \(\lambda\) is done as suggested in (MacKay, 1992). The initial value of the maximization procedure can be set with the hyperparameters alpha_init and lambda_init.

There are four more hyperparameters, \(\alpha_1\), \(\alpha_2\), \(\lambda_1\) and \(\lambda_2\) of the gamma prior distributions over \(\alpha\) and \(\lambda\). These are usually chosen to be non-informative. By default \(\alpha_1 = \alpha_2 = \lambda_1 = \lambda_2 = 10^{-6}\).

Bayesian Ridge Regression is used for regression:

>>> from sklearn import linear_model
>>> X = [[0., 0.], [1., 1.], [2., 2.], [3., 3.]]
>>> Y = [0., 1., 2., 3.]
>>> reg = linear_model.BayesianRidge()
>>> reg.fit(X, Y)
BayesianRidge()

After being fitted, the model can then be used to predict new values:

>>> reg.predict([[1, 0.]])
array([0.50000013])

The coefficients \(w\) of the model can be accessed:

>>> reg.coef_
array([0.49999993, 0.49999993])

Due to the Bayesian framework, the weights found are slightly different from the ones found by Ordinary Least Squares. However, Bayesian Ridge Regression is more robust to ill-posed problems.

Examples

References

1.1.10.2. Automatic Relevance Determination - ARD

The Automatic Relevance Determination (as being implemented in ARDRegression) is a kind of linear model which is very similar to the Bayesian Ridge Regression, but that leads to sparser coefficients \(w\) [1] [2].

ARDRegression poses a different prior over \(w\): it drops the spherical Gaussian distribution for a centered elliptic Gaussian distribution. This means each coefficient \(w_{i}\) can itself be drawn from a Gaussian distribution, centered on zero and with a precision \(\lambda_{i}\):

\[p(w|\lambda) = \mathcal{N}(w|0,A^{-1})\]

with \(A\) being a positive definite diagonal matrix and \(\text{diag}(A) = \lambda = \{\lambda_{1},...,\lambda_{p}\}\).

In contrast to the Bayesian Ridge Regression, each coordinate of \(w_{i}\) has its own standard deviation \(\frac{1}{\lambda_i}\). The prior over all \(\lambda_i\) is chosen to be the same gamma distribution given by the hyperparameters \(\lambda_1\) and \(\lambda_2\).

ARD is also known in the literature as Sparse Bayesian Learning and Relevance Vector Machine [3] [4].

See Comparing Linear Bayesian Regressors for a worked-out comparison between ARD and Bayesian Ridge Regression.

See L1-based models for Sparse Signals for a comparison between various methods - Lasso, ARD and ElasticNet - on correlated data.

References

1.1.11. Logistic regression

The logistic regression is implemented in LogisticRegression. Despite its name, it is implemented as a linear model for classification rather than regression in terms of the scikit-learn/ML nomenclature. The logistic regression is also known in the literature as logit regression, maximum-entropy classification (MaxEnt) or the log-linear classifier. In this model, the probabilities describing the possible outcomes of a single trial are modeled using a logistic function.

This implementation can fit binary, One-vs-Rest, or multinomial logistic regression with optional \(\ell_1\), \(\ell_2\) or Elastic-Net regularization.

Note

Regularization

Regularization is applied by default, which is common in machine learning but not in statistics. Another advantage of regularization is that it improves numerical stability. No regularization amounts to setting C to a very high value.

Note

Logistic Regression as a special case of the Generalized Linear Models (GLM)

Logistic regression is a special case of Generalized Linear Models with a Binomial / Bernoulli conditional distribution and a Logit link. The numerical output of the logistic regression, which is the predicted probability, can be used as a classifier by applying a threshold (by default 0.5) to it. This is how it is implemented in scikit-learn, so it expects a categorical target, making the Logistic Regression a classifier.

Examples

1.1.11.1. Binary Case

For notational ease, we assume that the target \(y_i\) takes values in the set \(\{0, 1\}\) for data point \(i\). Once fitted, the predict_proba method of LogisticRegression predicts the probability of the positive class \(P(y_i=1|X_i)\) as

\[\hat{p}(X_i) = \operatorname{expit}(X_i w + w_0) = \frac{1}{1 + \exp(-X_i w - w_0)}.\]

As an optimization problem, binary class logistic regression with regularization term \(r(w)\) minimizes the following cost function:

(1)\[\min_{w} \frac{1}{S}\sum_{i=1}^n s_i \left(-y_i \log(\hat{p}(X_i)) - (1 - y_i) \log(1 - \hat{p}(X_i))\right) + \frac{r(w)}{S C}\,,\]

where \({s_i}\) corresponds to the weights assigned by the user to a specific training sample (the vector \(s\) is formed by element-wise multiplication of the class weights and sample weights), and the sum \(S = \sum_{i=1}^n s_i\).

We currently provide four choices for the regularization or penalty term \(r(w)\) via the arguments C and l1_ratio:

penalty

\(r(w)\)

none (C=np.inf)

\(0\)

\(\ell_1\) (l1_ratio=1)

\(\|w\|_1\)

\(\ell_2\) (l1_ratio=0)

\(\frac{1}{2}\|w\|_2^2 = \frac{1}{2}w^T w\)

ElasticNet (0<l1_ratio<1)

\(\frac{1 - \rho}{2}w^T w + \rho \|w\|_1\)

For ElasticNet, \(\rho\) (which corresponds to the l1_ratio parameter) controls the strength of \(\ell_1\) regularization vs. \(\ell_2\) regularization. Elastic-Net is equivalent to \(\ell_1\) when \(\rho = 1\) and equivalent to \(\ell_2\) when \(\rho=0\).

Note that the scale of the class weights and the sample weights will influence the optimization problem. For instance, multiplying the sample weights by a constant \(b>0\) is equivalent to multiplying the (inverse) regularization strength C by \(b\).

1.1.11.2. Multinomial Case

The binary case can be extended to \(K\) classes leading to the multinomial logistic regression, see also log-linear model.

Note

It is possible to parameterize a \(K\)-class classification model using only \(K-1\) weight vectors, leaving one class probability fully determined by the other class probabilities by leveraging the fact that all class probabilities must sum to one. We deliberately choose to overparameterize the model using \(K\) weight vectors for ease of implementation and to preserve the symmetrical inductive bias regarding ordering of classes, see [16]. This effect becomes especially important when using regularization. The choice of overparameterization can be detrimental for unpenalized models since then the solution may not be unique, as shown in [16].

Mathematical details

Let \(y_i \in \{1, \ldots, K\}\) be the label (ordinal) encoded target variable for observation \(i\). Instead of a single coefficient vector, we now have a matrix of coefficients \(W\) where each row vector \(W_k\) corresponds to class \(k\). We aim at predicting the class probabilities \(P(y_i=k|X_i)\) via predict_proba as:

\[\hat{p}_k(X_i) = \frac{\exp(X_i W_k + W_{0, k})}{\sum_{l=0}^{K-1} \exp(X_i W_l + W_{0, l})}.\]

The objective for the optimization becomes

\[\min_W -\frac{1}{S}\sum_{i=1}^n \sum_{k=0}^{K-1} s_{ik} [y_i = k] \log(\hat{p}_k(X_i)) + \frac{r(W)}{S C}\,,\]

where \([P]\) represents the Iverson bracket which evaluates to \(0\) if \(P\) is false, otherwise it evaluates to \(1\).

Again, \(s_{ik}\) are the weights assigned by the user (multiplication of sample weights and class weights) with their sum \(S = \sum_{i=1}^n \sum_{k=0}^{K-1} s_{ik}\).

We currently provide four choices for the regularization or penalty term \(r(W)\) via the arguments C and l1_ratio, where \(m\) is the number of features:

penalty

\(r(W)\)

none (C=np.inf)

\(0\)

\(\ell_1\) (l1_ratio=1)

\(\|W\|_{1,1} = \sum_{i=1}^m\sum_{j=1}^{K}|W_{i,j}|\)

\(\ell_2\) (l1_ratio=0)

\(\frac{1}{2}\|W\|_F^2 = \frac{1}{2}\sum_{i=1}^m\sum_{j=1}^{K} W_{i,j}^2\)

ElasticNet (0<l1_ratio<1)

\(\frac{1 - \rho}{2}\|W\|_F^2 + \rho \|W\|_{1,1}\)

1.1.11.3. Solvers

The solvers implemented in the class LogisticRegression are “lbfgs”, “liblinear”, “newton-cg”, “newton-cholesky”, “sag” and “saga”:

The following table summarizes the penalties and multinomial multiclass supported by each solver:

Solvers

Penalties

‘lbfgs’

‘liblinear’

‘newton-cg’

‘newton-cholesky’

‘sag’

‘saga’

L2 penalty

yes

yes

yes

yes

yes

yes

L1 penalty

no

yes

no

no

no

yes

Elastic-Net (L1 + L2)

no

no

no

no

no

yes

No penalty

yes

no

yes

yes

yes

yes

Multiclass support

multinomial multiclass

yes

no

yes

yes

yes

yes

Behaviors

Penalize the intercept (bad)

no

yes

no

no

no

no

Faster for large datasets

no

no

no

no

yes

yes

Robust to unscaled datasets

yes

yes

yes

yes

no

no

The “lbfgs” solver is used by default for its robustness. For n_samples >> n_features, “newton-cholesky” is a good choice and can reach high precision (tiny tol values). For large datasets the “saga” solver is usually faster (than “lbfgs”), in particular for low precision (high tol). For large dataset, you may also consider using SGDClassifier with loss="log_loss", which might be even faster but requires more tuning.

References

1.1.11.3.1. Differences between solvers

There might be a difference in the scores obtained between LogisticRegression with solver=liblinear or LinearSVC and the external liblinear library directly, when fit_intercept=False and the fit coef_ (or) the data to be predicted are zeroes. This is because for the sample(s) with decision_function zero, LogisticRegression and LinearSVC predict the negative class, while liblinear predicts the positive class. Note that a model with fit_intercept=False and having many samples with decision_function zero, is likely to be an underfit, bad model and you are advised to set fit_intercept=True and increase the intercept_scaling.

Solvers’ details
  • The solver “liblinear” uses a coordinate descent (CD) algorithm, and relies on the excellent C++ LIBLINEAR library, which is shipped with scikit-learn. However, the CD algorithm implemented in liblinear cannot learn a true multinomial (multiclass) model. If you still want to use “liblinear” on multiclass problems, you can use a “one-vs-rest” scheme OneVsRestClassifier(LogisticRegression(solver="liblinear")), see :class:`~sklearn.multiclass.OneVsRestClassifier. Note that minimizing the multinomial loss is expected to give better calibrated results as compared to a “one-vs-rest” scheme. For \(\ell_1\) regularization sklearn.svm.l1_min_c allows to calculate the lower bound for C in order to get a non “null” (all feature weights to zero) model.

  • The “lbfgs”, “newton-cg”, “newton-cholesky” and “sag” solvers only support \(\ell_2\) regularization or no regularization, and are found to converge faster for some high-dimensional data. These solvers (and “saga”) learn a true multinomial logistic regression model [5].

  • The “sag” solver uses Stochastic Average Gradient descent [6]. It is faster than other solvers for large datasets, when both the number of samples and the number of features are large.

  • The “saga” solver [7] is a variant of “sag” that also supports the non-smooth \(\ell_1\) penalty (l1_ratio=1). This is therefore the solver of choice for sparse multinomial logistic regression. It is also the only solver that supports Elastic-Net (0 < l1_ratio < 1).

  • The “lbfgs” is an optimization algorithm that approximates the Broyden–Fletcher–Goldfarb–Shanno algorithm [8], which belongs to quasi-Newton methods. As such, it can deal with a wide range of different training data and is therefore the default solver. Its performance, however, suffers on poorly scaled datasets and on datasets with one-hot encoded categorical features with rare categories.

  • The “newton-cholesky” solver is an exact Newton solver that calculates the Hessian matrix and solves the resulting linear system. It is a very good choice for n_samples >> n_features and can reach high precision (tiny values of tol), but has a few shortcomings: Only \(\ell_2\) regularization is supported. Furthermore, because the Hessian matrix is explicitly computed, the memory usage has a quadratic dependency on n_features as well as on n_classes.

For a comparison of some of these solvers, see [9].

References

Note

Feature selection with sparse logistic regression

A logistic regression with \(\ell_1\) penalty yields sparse models, and can thus be used to perform feature selection, as detailed in L1-based feature selection.

Note

P-value estimation

It is possible to obtain the p-values and confidence intervals for coefficients in cases of regression without penalization. The statsmodels package natively supports this. Within sklearn, one could use bootstrapping instead as well.

LogisticRegressionCV implements Logistic Regression with built-in cross-validation support, to find the optimal C and l1_ratio parameters according to the scoring attribute. The “newton-cg”, “sag”, “saga” and “lbfgs” solvers are found to be faster for high-dimensional dense data, due to warm-starting (see Glossary).

1.1.12. Generalized Linear Models

Generalized Linear Models (GLM) extend linear models in two ways [10]. First, the predicted values \(\hat{y}\) are linked to a linear combination of the input variables \(X\) via an inverse link function \(h\) as

\[\hat{y}(w, X) = h(Xw).\]

Secondly, the squared loss function is replaced by the unit deviance \(d\) of a distribution in the exponential family (or more precisely, a reproductive exponential dispersion model (EDM) [11]).

The minimization problem becomes:

\[\min_{w} \frac{1}{2 n_{\text{samples}}} \sum_i d(y_i, \hat{y}_i) + \frac{\alpha}{2} ||w||_2^2,\]

where \(\alpha\) is the L2 regularization penalty. When sample weights are provided, the average becomes a weighted average.

The following table lists some specific EDMs and their unit deviance :

Distribution

Target Domain

Unit Deviance \(d(y, \hat{y})\)

Normal

\(y \in (-\infty, \infty)\)

\((y-\hat{y})^2\)

Bernoulli

\(y \in \{0, 1\}\)

\(2({y}\log\frac{y}{\hat{y}}+({1}-{y})\log\frac{{1}-{y}}{{1}-\hat{y}})\)

Categorical

\(y \in \{0, 1, ..., k\}\)

\(2\sum_{i \in \{0, 1, ..., k\}} I(y = i) y_\text{i}\log\frac{I(y = i)}{\hat{I(y = i)}}\)

Poisson

\(y \in [0, \infty)\)

\(2(y\log\frac{y}{\hat{y}}-y+\hat{y})\)

Gamma

\(y \in (0, \infty)\)

\(2(\log\frac{\hat{y}}{y}+\frac{y}{\hat{y}}-1)\)

Inverse Gaussian

\(y \in (0, \infty)\)

\(\frac{(y-\hat{y})^2}{y\hat{y}^2}\)

The Probability Density Functions (PDF) of these distributions are illustrated in the following figure,

../_images/poisson_gamma_tweedie_distributions.png

PDF of a random variable Y following Poisson, Tweedie (power=1.5) and Gamma distributions with different mean values (\(\mu\)). Observe the point mass at \(Y=0\) for the Poisson distribution and the Tweedie (power=1.5) distribution, but not for the Gamma distribution which has a strictly positive target domain.

The Bernoulli distribution is a discrete probability distribution modelling a Bernoulli trial - an event that has only two mutually exclusive outcomes. The Categorical distribution is a generalization of the Bernoulli distribution for a categorical random variable. While a random variable in a Bernoulli distribution has two possible outcomes, a Categorical random variable can take on one of K possible categories, with the probability of each category specified separately.

The choice of the distribution depends on the problem at hand:

  • If the target values \(y\) are counts (non-negative integer valued) or relative frequencies (non-negative), you might use a Poisson distribution with a log-link.

  • If the target values are positive valued and skewed, you might try a Gamma distribution with a log-link.

  • If the target values seem to be heavier tailed than a Gamma distribution, you might try an Inverse Gaussian distribution (or even higher variance powers of the Tweedie family).

  • If the target values \(y\) are probabilities, you can use the Bernoulli distribution. The Bernoulli distribution with a logit link can be used for binary classification. The Categorical distribution with a softmax link can be used for multiclass classification.

Examples of use cases
  • Agriculture / weather modeling: number of rain events per year (Poisson), amount of rainfall per event (Gamma), total rainfall per year (Tweedie / Compound Poisson Gamma).

  • Risk modeling / insurance policy pricing: number of claim events / policyholder per year (Poisson), cost per event (Gamma), total cost per policyholder per year (Tweedie / Compound Poisson Gamma).

  • Credit Default: probability that a loan can’t be paid back (Bernoulli).

  • Fraud Detection: probability that a financial transaction like a cash transfer is a fraudulent transaction (Bernoulli).

  • Predictive maintenance: number of production interruption events per year (Poisson), duration of interruption (Gamma), total interruption time per year (Tweedie / Compound Poisson Gamma).

  • Medical Drug Testing: probability of curing a patient in a set of trials or probability that a patient will experience side effects (Bernoulli).

  • News Classification: classification of news articles into three categories namely Business News, Politics and Entertainment news (Categorical).

References

1.1.12.1. Usage

TweedieRegressor implements a generalized linear model for the Tweedie distribution, that allows to model any of the above mentioned distributions using the appropriate power parameter. In particular:

  • power = 0: Normal distribution. Specific estimators such as Ridge, ElasticNet are generally more appropriate in this case.

  • power = 1: Poisson distribution. PoissonRegressor is exposed for convenience. However, it is strictly equivalent to TweedieRegressor(power=1, link='log').

  • power = 2: Gamma distribution. GammaRegressor is exposed for convenience. However, it is strictly equivalent to TweedieRegressor(power=2, link='log').

  • power = 3: Inverse Gaussian distribution.

The link function is determined by the link parameter.

Usage example:

>>> from sklearn.linear_model import TweedieRegressor
>>> reg = TweedieRegressor(power=1, alpha=0.5, link='log')
>>> reg.fit([[0, 0], [0, 1], [2, 2]], [0, 1, 2])
TweedieRegressor(alpha=0.5, link='log', power=1)
>>> reg.coef_
array([0.2463, 0.4337])
>>> reg.intercept_
np.float64(-0.7638)

Examples

Practical considerations

The feature matrix X should be standardized before fitting. This ensures that the penalty treats features equally.

Since the linear predictor \(Xw\) can be negative and Poisson, Gamma and Inverse Gaussian distributions don’t support negative values, it is necessary to apply an inverse link function that guarantees the non-negativeness. For example with link='log', the inverse link function becomes \(h(Xw)=\exp(Xw)\).

If you want to model a relative frequency, i.e. counts per exposure (time, volume, …) you can do so by using a Poisson distribution and passing \(y=\frac{\mathrm{counts}}{\mathrm{exposure}}\) as target values together with \(\mathrm{exposure}\) as sample weights. For a concrete example see e.g. Tweedie regression on insurance claims.

When performing cross-validation for the power parameter of TweedieRegressor, it is advisable to specify an explicit scoring function, because the default scorer TweedieRegressor.score is a function of power itself.

1.1.13. Stochastic Gradient Descent - SGD

Stochastic gradient descent is a simple yet very efficient approach to fit linear models. It is particularly useful when the number of samples (and the number of features) is very large. The partial_fit method allows online/out-of-core learning.

The classes SGDClassifier and SGDRegressor provide functionality to fit linear models for classification and regression using different (convex) loss functions and different penalties. E.g., with loss="log", SGDClassifier fits a logistic regression model, while with loss="hinge" it fits a linear support vector machine (SVM).

You can refer to the dedicated Stochastic Gradient Descent documentation section for more details.

1.1.13.1. Perceptron

The Perceptron is another simple classification algorithm suitable for large scale learning and derives from SGD. By default:

  • It does not require a learning rate.

  • It is not regularized (penalized).

  • It updates its model only on mistakes.

The last characteristic implies that the Perceptron is slightly faster to train than SGD with the hinge loss and that the resulting models are sparser.

In fact, the Perceptron is a wrapper around the SGDClassifier class using a perceptron loss and a constant learning rate. Refer to mathematical section of the SGD procedure for more details.

1.1.13.2. Passive Aggressive Algorithms

The passive-aggressive (PA) algorithms are another family of 2 algorithms (PA-I and PA-II) for large-scale online learning that derive from SGD. They are similar to the Perceptron in that they do not require a learning rate. However, contrary to the Perceptron, they include a regularization parameter eta0 (\(C\) in the reference paper).

For classification, SGDClassifier(loss="hinge", penalty=None, learning_rate="pa1", eta0=1.0) can be used for PA-I or with learning_rate="pa2" for PA-II. For regression, SGDRegressor(loss="epsilon_insensitive", penalty=None, learning_rate="pa1", eta0=1.0) can be used for PA-I or with learning_rate="pa2" for PA-II.

References

1.1.14. Robustness regression: outliers and modeling errors

Robust regression aims to fit a regression model in the presence of corrupt data: either outliers, or error in the model.

../_images/sphx_glr_plot_theilsen_001.png

1.1.14.1. Different scenario and useful concepts

There are different things to keep in mind when dealing with data corrupted by outliers:

  • Outliers in X or in y?

    Outliers in the y direction

    Outliers in the X direction

    y_outliers

    X_outliers

  • Fraction of outliers versus amplitude of error

    The number of outlying points matters, but also how much they are outliers.

    Small outliers

    Large outliers

    y_outliers

    large_y_outliers

An important notion of robust fitting is that of breakdown point: the fraction of data that can be outlying for the fit to start missing the inlying data.

Note that in general, robust fitting in high-dimensional setting (large n_features) is very hard. The robust models here will probably not work in these settings.

1.1.14.2. RANSAC: RANdom SAmple Consensus

RANSAC (RANdom SAmple Consensus) fits a model from random subsets of inliers from the complete data set.

RANSAC is a non-deterministic algorithm producing only a reasonable result with a certain probability, which is dependent on the number of iterations (see max_trials parameter). It is typically used for linear and non-linear regression problems and is especially popular in the field of photogrammetric computer vision.

The algorithm splits the complete input sample data into a set of inliers, which may be subject to noise, and outliers, which are e.g. caused by erroneous measurements or invalid hypotheses about the data. The resulting model is then estimated only from the determined inliers.

../_images/sphx_glr_plot_ransac_001.png

Examples

Details of the algorithm

Each iteration performs the following steps:

  1. Select min_samples random samples from the original data and check whether the set of data is valid (see is_data_valid).

  2. Fit a model to the random subset (estimator.fit) and check whether the estimated model is valid (see is_model_valid).

  3. Classify all data as inliers or outliers by calculating the residuals to the estimated model (estimator.predict(X) - y) - all data samples with absolute residuals smaller than or equal to the residual_threshold are considered as inliers.

  4. Save fitted model as best model if number of inlier samples is maximal. In case the current estimated model has the same number of inliers, it is only considered as the best model if it has better score.

These steps are performed either a maximum number of times (max_trials) or until one of the special stop criteria are met (see stop_n_inliers and stop_score). The final model is estimated using all inlier samples (consensus set) of the previously determined best model.

The is_data_valid and is_model_valid functions allow to identify and reject degenerate combinations of random sub-samples. If the estimated model is not needed for identifying degenerate cases, is_data_valid should be used as it is called prior to fitting the model and thus leading to better computational performance.

References

1.1.14.3. Theil-Sen estimator: generalized-median-based estimator

The TheilSenRegressor estimator uses a generalization of the median in multiple dimensions. It is thus robust to multivariate outliers. Note however that the robustness of the estimator decreases quickly with the dimensionality of the problem. It loses its robustness properties and becomes no better than an ordinary least squares in high dimension.

Examples

Theoretical considerations

TheilSenRegressor is comparable to the Ordinary Least Squares (OLS) in terms of asymptotic efficiency and as an unbiased estimator. In contrast to OLS, Theil-Sen is a non-parametric method which means it makes no assumption about the underlying distribution of the data. Since Theil-Sen is a median-based estimator, it is more robust against corrupted data aka outliers. In univariate setting, Theil-Sen has a breakdown point of about 29.3% in case of a simple linear regression which means that it can tolerate arbitrary corrupted data of up to 29.3%.

../_images/sphx_glr_plot_theilsen_001.png

The implementation of TheilSenRegressor in scikit-learn follows a generalization to a multivariate linear regression model [14] using the spatial median which is a generalization of the median to multiple dimensions [15].

In terms of time and space complexity, Theil-Sen scales according to

\[\binom{n_{\text{samples}}}{n_{\text{subsamples}}}\]

which makes it infeasible to be applied exhaustively to problems with a large number of samples and features. Therefore, the magnitude of a subpopulation can be chosen to limit the time and space complexity by considering only a random subset of all possible combinations.

References

Also see the Wikipedia page

1.1.14.4. Huber Regression

The HuberRegressor is different from Ridge because it applies a linear loss to samples that are defined as outliers by the epsilon parameter. A sample is classified as an inlier if the absolute error of that sample is less than the threshold epsilon. It differs from TheilSenRegressor and RANSACRegressor because it does not ignore the effect of the outliers but gives a lesser weight to them.

../_images/sphx_glr_plot_huber_vs_ridge_001.png

Examples

Mathematical details

HuberRegressor minimizes

\[\min_{w, \sigma} {\sum_{i=1}^n\left(\sigma + H_{\epsilon}\left(\frac{X_{i}w - y_{i}}{\sigma}\right)\sigma\right) + \alpha {||w||_2}^2}\]

where the loss function is given by

\[\begin{split}H_{\epsilon}(z) = \begin{cases} z^2, & \text {if } |z| < \epsilon, \\ 2\epsilon|z| - \epsilon^2, & \text{otherwise} \end{cases}\end{split}\]

It is advised to set the parameter epsilon to 1.35 to achieve 95% statistical efficiency.

References

  • Peter J. Huber, Elvezio M. Ronchetti: Robust Statistics, Concomitant scale estimates, p. 172.

The HuberRegressor differs from using SGDRegressor with loss set to huber in the following ways.

  • HuberRegressor is scaling invariant. Once epsilon is set, scaling X and y down or up by different values would produce the same robustness to outliers as before. as compared to SGDRegressor where epsilon has to be set again when X and y are scaled.

  • HuberRegressor should be more efficient to use on data with small number of samples while SGDRegressor needs a number of passes on the training data to produce the same robustness.

Note that this estimator is different from the R implementation of Robust Regression because the R implementation does a weighted least squares implementation with weights given to each sample on the basis of how much the residual is greater than a certain threshold.

1.1.15. Quantile Regression

Quantile regression estimates the median or other quantiles of \(y\) conditional on \(X\), while ordinary least squares (OLS) estimates the conditional mean.

Quantile regression may be useful if one is interested in predicting an interval instead of point prediction. Sometimes, prediction intervals are calculated based on the assumption that prediction error is distributed normally with zero mean and constant variance. Quantile regression provides sensible prediction intervals even for errors with non-constant (but predictable) variance or non-normal distribution.

../_images/sphx_glr_plot_quantile_regression_002.png

Based on minimizing the pinball loss, conditional quantiles can also be estimated by models other than linear models. For example, GradientBoostingRegressor can predict conditional quantiles if its parameter loss is set to "quantile" and parameter alpha is set to the quantile that should be predicted. See the example in Prediction Intervals for Gradient Boosting Regression.

Most implementations of quantile regression are based on linear programming problem. The current implementation is based on scipy.optimize.linprog.

Examples

Mathematical details

As a linear model, the QuantileRegressor gives linear predictions \(\hat{y}(w, X) = Xw\) for the \(q\)-th quantile, \(q \in (0, 1)\). The weights or coefficients \(w\) are then found by the following minimization problem:

\[\min_{w} {\frac{1}{n_{\text{samples}}} \sum_i PB_q(y_i - X_i w) + \alpha ||w||_1}.\]

This consists of the pinball loss (also known as linear loss), see also mean_pinball_loss,

\[\begin{split}PB_q(t) = q \max(t, 0) + (1 - q) \max(-t, 0) = \begin{cases} q t, & t > 0, \\ 0, & t = 0, \\ (q-1) t, & t < 0 \end{cases}\end{split}\]

and the L1 penalty controlled by parameter alpha, similar to Lasso.

As the pinball loss is only linear in the residuals, quantile regression is much more robust to outliers than squared error based estimation of the mean. Somewhat in between is the HuberRegressor.

References

1.1.16. Polynomial regression: extending linear models with basis functions

One common pattern within machine learning is to use linear models trained on nonlinear functions of the data. This approach maintains the generally fast performance of linear methods, while allowing them to fit a much wider range of data.

Mathematical details

For example, a simple linear regression can be extended by constructing polynomial features from the coefficients. In the standard linear regression case, you might have a model that looks like this for two-dimensional data:

\[\hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2\]

If we want to fit a paraboloid to the data instead of a plane, we can combine the features in second-order polynomials, so that the model looks like this:

\[\hat{y}(w, x) = w_0 + w_1 x_1 + w_2 x_2 + w_3 x_1 x_2 + w_4 x_1^2 + w_5 x_2^2\]

The (sometimes surprising) observation is that this is still a linear model: to see this, imagine creating a new set of features

\[z = [x_1, x_2, x_1 x_2, x_1^2, x_2^2]\]

With this re-labeling of the data, our problem can be written

\[\hat{y}(w, z) = w_0 + w_1 z_1 + w_2 z_2 + w_3 z_3 + w_4 z_4 + w_5 z_5\]

We see that the resulting polynomial regression is in the same class of linear models we considered above (i.e. the model is linear in \(w\)) and can be solved by the same techniques. By considering linear fits within a higher-dimensional space built with these basis functions, the model has the flexibility to fit a much broader range of data.

Here is an example of applying this idea to one-dimensional data, using polynomial features of varying degrees:

../_images/sphx_glr_plot_polynomial_interpolation_001.png

This figure is created using the PolynomialFeatures transformer, which transforms an input data matrix into a new data matrix of a given degree. It can be used as follows:

>>> from sklearn.preprocessing import PolynomialFeatures
>>> import numpy as np
>>> X = np.arange(6).reshape(3, 2)
>>> X
array([[0, 1],
       [2, 3],
       [4, 5]])
>>> poly = PolynomialFeatures(degree=2)
>>> poly.fit_transform(X)
array([[ 1.,  0.,  1.,  0.,  0.,  1.],
       [ 1.,  2.,  3.,  4.,  6.,  9.],
       [ 1.,  4.,  5., 16., 20., 25.]])

The features of X have been transformed from \([x_1, x_2]\) to \([1, x_1, x_2, x_1^2, x_1 x_2, x_2^2]\), and can now be used within any linear model.

This sort of preprocessing can be streamlined with the Pipeline tools. A single object representing a simple polynomial regression can be created and used as follows:

>>> from sklearn.preprocessing import PolynomialFeatures
>>> from sklearn.linear_model import LinearRegression
>>> from sklearn.pipeline import Pipeline
>>> import numpy as np
>>> model = Pipeline([('poly', PolynomialFeatures(degree=3)),
...                   ('linear', LinearRegression(fit_intercept=False))])
>>> # fit to an order-3 polynomial data
>>> x = np.arange(5)
>>> y = 3 - 2 * x + x ** 2 - x ** 3
>>> model = model.fit(x[:, np.newaxis], y)
>>> model.named_steps['linear'].coef_
array([ 3., -2.,  1., -1.])

The linear model trained on polynomial features is able to exactly recover the input polynomial coefficients.

In some cases it’s not necessary to include higher powers of any single feature, but only the so-called interaction features that multiply together at most \(d\) distinct features. These can be gotten from PolynomialFeatures with the setting interaction_only=True.

For example, when dealing with boolean features, \(x_i^n = x_i\) for all \(n\) and is therefore useless; but \(x_i x_j\) represents the conjunction of two booleans. This way, we can solve the XOR problem with a linear classifier:

>>> from sklearn.linear_model import Perceptron
>>> from sklearn.preprocessing import PolynomialFeatures
>>> import numpy as np
>>> X = np.array([[0, 0], [0, 1], [1, 0], [1, 1]])
>>> y = X[:, 0] ^ X[:, 1]
>>> y
array([0, 1, 1, 0])
>>> X = PolynomialFeatures(interaction_only=True).fit_transform(X).astype(int)
>>> X
array([[1, 0, 0, 0],
       [1, 0, 1, 0],
       [1, 1, 0, 0],
       [1, 1, 1, 1]])
>>> clf = Perceptron(fit_intercept=False, max_iter=10, tol=None,
...                  shuffle=False).fit(X, y)

And the classifier “predictions” are perfect:

>>> clf.predict(X)
array([0, 1, 1, 0])
>>> clf.score(X, y)
1.0

enum — Support for enumerations

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.

enum — Support for enumerations

Added in version 3.4.

Source code: Lib/enum.py


An enumeration:

  • is a set of symbolic names (members) bound to unique values

  • can be iterated over to return its canonical (i.e. non-alias) members in definition order

  • uses call syntax to return members by value

  • uses index syntax to return members by name

Enumerations are created either by using class syntax, or by using function-call syntax:

>>> from enum import Enum

>>> # class syntax
>>> class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3

>>> # functional syntax
>>> Color = Enum('Color', [('RED', 1), ('GREEN', 2), ('BLUE', 3)])

Even though we can use class syntax to create Enums, Enums are not normal Python classes. See How are Enums different? for more details.

Note

Nomenclature

  • The class Color is an enumeration (or enum)

  • The attributes Color.RED, Color.GREEN, etc., are enumeration members (or members) and are functionally constants.

  • The enum members have names and values (the name of Color.RED is RED, the value of Color.BLUE is 3, etc.)


Module contents

EnumType

The type for Enum and its subclasses.

Enum

Base class for creating enumerated constants.

IntEnum

Base class for creating enumerated constants that are also subclasses of int. (Notes)

StrEnum

Base class for creating enumerated constants that are also subclasses of str. (Notes)

Flag

Base class for creating enumerated constants that can be combined using the bitwise operations without losing their Flag membership.

IntFlag

Base class for creating enumerated constants that can be combined using the bitwise operators without losing their IntFlag membership. IntFlag members are also subclasses of int. (Notes)

ReprEnum

Used by IntEnum, StrEnum, and IntFlag to keep the str() of the mixed-in type.

EnumCheck

An enumeration with the values CONTINUOUS, NAMED_FLAGS, and UNIQUE, for use with verify() to ensure various constraints are met by a given enumeration.

FlagBoundary

An enumeration with the values STRICT, CONFORM, EJECT, and KEEP which allows for more fine-grained control over how invalid values are dealt with in an enumeration.

EnumDict

A subclass of dict for use when subclassing EnumType.

auto

Instances are replaced with an appropriate value for Enum members. StrEnum defaults to the lower-cased version of the member name, while other Enums default to 1 and increase from there.

@~enum.property

Allows Enum members to have attributes without conflicting with member names. The value and name attributes are implemented this way.

@unique

Enum class decorator that ensures only one name is bound to any one value.

@verify

Enum class decorator that checks user-selectable constraints on an enumeration.

@member

Make obj a member. Can be used as a decorator.

@nonmember

Do not make obj a member. Can be used as a decorator.

@global_enum

Modify the str() and repr() of an enum to show its members as belonging to the module instead of its class, and export the enum members to the global namespace.

show_flag_values()

Return a list of all power-of-two integers contained in a flag.

enum.bin()

Like built-in bin(), except negative values are represented in two’s complement, and the leading bit always indicates sign (0 implies positive, 1 implies negative).

Added in version 3.6: Flag, IntFlag, auto

Added in version 3.11: StrEnum, EnumCheck, ReprEnum, FlagBoundary, property, member, nonmember, global_enum, show_flag_values

Added in version 3.13: EnumDict


Data types

class enum.EnumType

EnumType is the metaclass for enum enumerations. It is possible to subclass EnumType – see Subclassing EnumType for details.

EnumType is responsible for setting the correct __repr__(), __str__(), __format__(), and __reduce__() methods on the final enum, as well as creating the enum members, properly handling duplicates, providing iteration over the enum class, etc.

Added in version 3.11: Before 3.11 EnumType was called EnumMeta, which is still available as an alias.

__call__(cls, value, names=None, *, module=None, qualname=None, type=None, start=1, boundary=None)

This method is called in two different ways:

  • to look up an existing member:

    cls:

    The enum class being called.

    value:

    The value to lookup.

  • to use the cls enum to create a new enum (only if the existing enum does not have any members):

    cls:

    The enum class being called.

    value:

    The name of the new Enum to create.

    names:

    The names/values of the members for the new Enum.

    module:

    The name of the module the new Enum is created in.

    qualname:

    The actual location in the module where this Enum can be found.

    type:

    A mix-in type for the new Enum.

    start:

    The first integer value for the Enum (used by auto).

    boundary:

    How to handle out-of-range values from bit operations (Flag only).

__contains__(cls, member)

Returns True if member belongs to the cls:

>>> some_var = Color.RED
>>> some_var in Color
True
>>> Color.RED.value in Color
True

Changed in version 3.12: Before Python 3.12, a TypeError is raised if a non-Enum-member is used in a containment check.

__dir__(cls)

Returns ['__class__', '__doc__', '__members__', '__module__'] and the names of the members in cls:

>>> dir(Color)
['BLUE', 'GREEN', 'RED', '__class__', '__contains__', '__doc__', '__getitem__', '__init_subclass__', '__iter__', '__len__', '__members__', '__module__', '__name__', '__qualname__']
__getitem__(cls, name)

Returns the Enum member in cls matching name, or raises a KeyError:

>>> Color['BLUE']
<Color.BLUE: 3>
__iter__(cls)

Returns each member in cls in definition order:

>>> list(Color)
[<Color.RED: 1>, <Color.GREEN: 2>, <Color.BLUE: 3>]
__len__(cls)

Returns the number of members in cls:

>>> len(Color)
3
__members__

Returns a mapping of every enum name to its member, including aliases

__reversed__(cls)

Returns each member in cls in reverse definition order:

>>> list(reversed(Color))
[<Color.BLUE: 3>, <Color.GREEN: 2>, <Color.RED: 1>]
class enum.Enum

Enum is the base class for all enum enumerations.

name

The name used to define the Enum member:

>>> Color.BLUE.name
'BLUE'
value

The value given to the Enum member:

>>> Color.RED.value
1

Value of the member, can be set in __new__().

Note

Enum member values

Member values can be anything: int, str, etc. If the exact value is unimportant you may use auto instances and an appropriate value will be chosen for you. See auto for the details.

While mutable/unhashable values, such as dict, list or a mutable dataclass, can be used, they will have a quadratic performance impact during creation relative to the total number of mutable/unhashable values in the enum.

_name_

Name of the member.

_value_

Value of the member, can be set in __new__().

_order_

No longer used, kept for backward compatibility. (class attribute, removed during class creation).

The _order_ attribute can be provided to help keep Python 2 / Python 3 code in sync. It will be checked against the actual order of the enumeration and raise an error if the two do not match:

>>> class Color(Enum):
...     _order_ = 'RED GREEN BLUE'
...     RED = 1
...     BLUE = 3
...     GREEN = 2
...
Traceback (most recent call last):
...
TypeError: member order does not match _order_:
   ['RED', 'BLUE', 'GREEN']
   ['RED', 'GREEN', 'BLUE']

Note

In Python 2 code the _order_ attribute is necessary as definition order is lost before it can be recorded.

Added in version 3.6.

_ignore_

_ignore_ is only used during creation and is removed from the enumeration once creation is complete.

_ignore_ is a list of names that will not become members, and whose names will also be removed from the completed enumeration. See TimePeriod for an example.

Added in version 3.7.

__dir__(self)

Returns ['__class__', '__doc__', '__module__', 'name', 'value'] and any public methods defined on self.__class__:

>>> from enum import Enum
>>> import datetime as dt
>>> class Weekday(Enum):
...     MONDAY = 1
...     TUESDAY = 2
...     WEDNESDAY = 3
...     THURSDAY = 4
...     FRIDAY = 5
...     SATURDAY = 6
...     SUNDAY = 7
...     @classmethod
...     def today(cls):
...         print(f'today is {cls(dt.date.today().isoweekday()).name}')
...
>>> dir(Weekday.SATURDAY)
['__class__', '__doc__', '__eq__', '__hash__', '__module__', 'name', 'today', 'value']
_generate_next_value_(name, start, count, last_values)
name:

The name of the member being defined (e.g. ‘RED’).

start:

The start value for the Enum; the default is 1.

count:

The number of members currently defined, not including this one.

last_values:

A list of the previous values.

A staticmethod that is used to determine the next value returned by auto.

Note

For standard Enum classes the next value chosen is the highest value seen incremented by one.

For Flag classes the next value chosen will be the next highest power-of-two.

This method may be overridden, e.g.:

>>> from enum import auto, Enum
>>> class PowersOfThree(Enum):
...     @staticmethod
...     def _generate_next_value_(name, start, count, last_values):
...         return 3 ** (count + 1)
...     FIRST = auto()
...     SECOND = auto()
...
>>> PowersOfThree.SECOND.value
9

Added in version 3.6.

Changed in version 3.13: Prior versions would use the last seen value instead of the highest value.

__init__(self, *args, **kwds)

By default, does nothing. If multiple values are given in the member assignment, those values become separate arguments to __init__; e.g.

>>> from enum import Enum
>>> class Weekday(Enum):
...     MONDAY = 1, 'Mon'

Weekday.__init__() would be called as Weekday.__init__(self, 1, 'Mon')

__init_subclass__(cls, **kwds)

A classmethod that is used to further configure subsequent subclasses. By default, does nothing.

_missing_(cls, value)

A classmethod for looking up values not found in cls. By default it does nothing, but can be overridden to implement custom search behavior:

>>> from enum import auto, StrEnum
>>> class Build(StrEnum):
...     DEBUG = auto()
...     OPTIMIZED = auto()
...     @classmethod
...     def _missing_(cls, value):
...         value = value.lower()
...         for member in cls:
...             if member.value == value:
...                 return member
...         return None
...
>>> Build.DEBUG.value
'debug'
>>> Build('deBUG')
<Build.DEBUG: 'debug'>

Added in version 3.6.

__new__(cls, *args, **kwds)

By default, doesn’t exist. If specified, either in the enum class definition or in a mixin class (such as int), all values given in the member assignment will be passed; e.g.

>>> from enum import Enum
>>> class MyIntEnum(int, Enum):
...     TWENTYSIX = '1a', 16

results in the call int('1a', 16) and a value of 26 for the member.

Note

When writing a custom __new__, do not use super().__new__ – call the appropriate __new__ instead.

__repr__(self)

Returns the string used for repr() calls. By default, returns the Enum name, member name, and value, but can be overridden:

>>> from enum import auto, Enum
>>> class OtherStyle(Enum):
...     ALTERNATE = auto()
...     OTHER = auto()
...     SOMETHING_ELSE = auto()
...     def __repr__(self):
...         cls_name = self.__class__.__name__
...         return f'{cls_name}.{self.name}'
...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
(OtherStyle.ALTERNATE, 'OtherStyle.ALTERNATE', 'OtherStyle.ALTERNATE')
__str__(self)

Returns the string used for str() calls. By default, returns the Enum name and member name, but can be overridden:

>>> from enum import auto, Enum
>>> class OtherStyle(Enum):
...     ALTERNATE = auto()
...     OTHER = auto()
...     SOMETHING_ELSE = auto()
...     def __str__(self):
...         return f'{self.name}'
...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
(<OtherStyle.ALTERNATE: 1>, 'ALTERNATE', 'ALTERNATE')
__format__(self)

Returns the string used for format() and f-string calls. By default, returns __str__() return value, but can be overridden:

>>> from enum import auto, Enum
>>> class OtherStyle(Enum):
...     ALTERNATE = auto()
...     OTHER = auto()
...     SOMETHING_ELSE = auto()
...     def __format__(self, spec):
...         return f'{self.name}'
...
>>> OtherStyle.ALTERNATE, str(OtherStyle.ALTERNATE), f"{OtherStyle.ALTERNATE}"
(<OtherStyle.ALTERNATE: 1>, 'OtherStyle.ALTERNATE', 'ALTERNATE')

Note

Using auto with Enum results in integers of increasing value, starting with 1.

Changed in version 3.12: Added Dataclass support.

_add_alias_()

Adds a new name as an alias to an existing member:

>>> Color.RED._add_alias_("ERROR")
>>> Color.ERROR
<Color.RED: 1>

Raises a NameError if the name is already assigned to a different member.

Added in version 3.13.

_add_value_alias_()

Adds a new value as an alias to an existing member:

>>> Color.RED._add_value_alias_(42)
>>> Color(42)
<Color.RED: 1>
Raises a ValueError if the value is already linked with a different member.
See MultiValueEnum for an example.

Added in version 3.13.

class enum.IntEnum

IntEnum is the same as Enum, but its members are also integers and can be used anywhere that an integer can be used. If any integer operation is performed with an IntEnum member, the resulting value loses its enumeration status.

>>> from enum import IntEnum
>>> class Number(IntEnum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...
>>> Number.THREE
<Number.THREE: 3>
>>> Number.ONE + Number.TWO
3
>>> Number.THREE + 5
8
>>> Number.THREE == 3
True

Note

Using auto with IntEnum results in integers of increasing value, starting with 1.

Changed in version 3.11: __str__() is now int.__str__() to better support the replacement of existing constants use-case. __format__() was already int.__format__() for that same reason.

class enum.StrEnum

StrEnum is the same as Enum, but its members are also strings and can be used in most of the same places that a string can be used. The result of any string operation performed on or with a StrEnum member is not part of the enumeration.

>>> from enum import StrEnum, auto
>>> class Color(StrEnum):
...     RED = 'r'
...     GREEN = 'g'
...     BLUE = 'b'
...     UNKNOWN = auto()
...
>>> Color.RED
<Color.RED: 'r'>
>>> Color.UNKNOWN
<Color.UNKNOWN: 'unknown'>
>>> str(Color.UNKNOWN)
'unknown'

Note

There are places in the stdlib that check for an exact str instead of a str subclass (i.e. type(unknown) == str instead of isinstance(unknown, str)), and in those locations you will need to use str(MyStrEnum.MY_MEMBER).

Note

Using auto with StrEnum results in the lower-cased member name as the value.

Note

__str__() is str.__str__() to better support the replacement of existing constants use-case. __format__() is likewise str.__format__() for that same reason.

Added in version 3.11.

class enum.Flag

Flag is the same as Enum, but its members support the bitwise operators & (AND), | (OR), ^ (XOR), and ~ (INVERT); the results of those operations are (aliases of) members of the enumeration.

__contains__(self, value)

Returns True if value is in self:

>>> from enum import Flag, auto
>>> class Color(Flag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> purple = Color.RED | Color.BLUE
>>> white = Color.RED | Color.GREEN | Color.BLUE
>>> Color.GREEN in purple
False
>>> Color.GREEN in white
True
>>> purple in white
True
>>> white in purple
False
__iter__(self)

Returns all contained non-alias members:

>>> list(Color.RED)
[<Color.RED: 1>]
>>> list(purple)
[<Color.RED: 1>, <Color.BLUE: 4>]

Added in version 3.11.

__len__(self)

Returns number of members in flag:

>>> len(Color.GREEN)
1
>>> len(white)
3

Added in version 3.11.

__bool__(self)

Returns True if any members in flag, False otherwise:

>>> bool(Color.GREEN)
True
>>> bool(white)
True
>>> black = Color(0)
>>> bool(black)
False
__or__(self, other)

Returns current flag binary or’ed with other:

>>> Color.RED | Color.GREEN
<Color.RED|GREEN: 3>
__and__(self, other)

Returns current flag binary and’ed with other:

>>> purple & white
<Color.RED|BLUE: 5>
>>> purple & Color.GREEN
<Color: 0>
__xor__(self, other)

Returns current flag binary xor’ed with other:

>>> purple ^ white
<Color.GREEN: 2>
>>> purple ^ Color.GREEN
<Color.RED|GREEN|BLUE: 7>
__invert__(self)

Returns all the flags in type(self) that are not in self:

>>> ~white
<Color: 0>
>>> ~purple
<Color.GREEN: 2>
>>> ~Color.RED
<Color.GREEN|BLUE: 6>
_numeric_repr_()

Function used to format any remaining unnamed numeric values. Default is the value’s repr; common choices are hex() and oct().

Note

Using auto with Flag results in integers that are powers of two, starting with 1.

Changed in version 3.11: The repr() of zero-valued flags has changed. It is now:

>>> Color(0)
<Color: 0>
class enum.IntFlag

IntFlag is the same as Flag, but its members are also integers and can be used anywhere that an integer can be used.

>>> from enum import IntFlag, auto
>>> class Color(IntFlag):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> Color.RED & 2
<Color: 0>
>>> Color.RED | 2
<Color.RED|GREEN: 3>

If any integer operation is performed with an IntFlag member, the result is not an IntFlag:

>>> Color.RED + 2
3

If a Flag operation is performed with an IntFlag member and:

  • the result is a valid IntFlag: an IntFlag is returned

  • the result is not a valid IntFlag: the result depends on the FlagBoundary setting

The repr() of unnamed zero-valued flags has changed. It is now:

>>> Color(0)
<Color: 0>

Note

Using auto with IntFlag results in integers that are powers of two, starting with 1.

Changed in version 3.11: __str__() is now int.__str__() to better support the replacement of existing constants use-case. __format__() was already int.__format__() for that same reason.

Inversion of an IntFlag now returns a positive value that is the union of all flags not in the given flag, rather than a negative value. This matches the existing Flag behavior.

class enum.ReprEnum

ReprEnum uses the repr() of Enum, but the str() of the mixed-in data type:

Inherit from ReprEnum to keep the str() / format() of the mixed-in data type instead of using the Enum-default str().

Added in version 3.11.

class enum.EnumCheck

EnumCheck contains the options used by the verify() decorator to ensure various constraints; failed constraints result in a ValueError.

UNIQUE

Ensure that each value has only one name:

>>> from enum import Enum, verify, UNIQUE
>>> @verify(UNIQUE)
... class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 3
...     CRIMSON = 1
Traceback (most recent call last):
...
ValueError: aliases found in <enum 'Color'>: CRIMSON -> RED
CONTINUOUS

Ensure that there are no missing values between the lowest-valued member and the highest-valued member:

>>> from enum import Enum, verify, CONTINUOUS
>>> @verify(CONTINUOUS)
... class Color(Enum):
...     RED = 1
...     GREEN = 2
...     BLUE = 5
Traceback (most recent call last):
...
ValueError: invalid enum 'Color': missing values 3, 4
NAMED_FLAGS

Ensure that any flag groups/masks contain only named flags – useful when values are specified instead of being generated by auto():

>>> from enum import Flag, verify, NAMED_FLAGS
>>> @verify(NAMED_FLAGS)
... class Color(Flag):
...     RED = 1
...     GREEN = 2
...     BLUE = 4
...     WHITE = 15
...     NEON = 31
Traceback (most recent call last):
...
ValueError: invalid Flag 'Color': aliases WHITE and NEON are missing combined values of 0x18 [use enum.show_flag_values(value) for details]

Note

CONTINUOUS and NAMED_FLAGS are designed to work with integer-valued members.

Added in version 3.11.

class enum.FlagBoundary

FlagBoundary controls how out-of-range values are handled in Flag and its subclasses.

STRICT

Out-of-range values cause a ValueError to be raised. This is the default for Flag:

>>> from enum import Flag, STRICT, auto
>>> class StrictFlag(Flag, boundary=STRICT):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> StrictFlag(2**2 + 2**4)
Traceback (most recent call last):
...
ValueError: <flag 'StrictFlag'> invalid value 20
    given 0b0 10100
  allowed 0b0 00111
CONFORM

Out-of-range values have invalid values removed, leaving a valid Flag value:

>>> from enum import Flag, CONFORM, auto
>>> class ConformFlag(Flag, boundary=CONFORM):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> ConformFlag(2**2 + 2**4)
<ConformFlag.BLUE: 4>
EJECT

Out-of-range values lose their Flag membership and revert to int.

>>> from enum import Flag, EJECT, auto
>>> class EjectFlag(Flag, boundary=EJECT):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> EjectFlag(2**2 + 2**4)
20
KEEP

Out-of-range values are kept, and the Flag membership is kept. This is the default for IntFlag:

>>> from enum import Flag, KEEP, auto
>>> class KeepFlag(Flag, boundary=KEEP):
...     RED = auto()
...     GREEN = auto()
...     BLUE = auto()
...
>>> KeepFlag(2**2 + 2**4)
<KeepFlag.BLUE|16: 20>

Added in version 3.11.

class enum.EnumDict

EnumDict is a subclass of dict that is used as the namespace for defining enum classes (see Preparing the class namespace). It is exposed to allow subclasses of EnumType with advanced behavior like having multiple values per member. It should be called with the name of the enum class being created, otherwise private names and internal classes will not be handled correctly.

Note that only the MutableMapping interface (__setitem__() and update()) is overridden. It may be possible to bypass the checks using other dict operations like |=.

member_names

A list of member names.

Added in version 3.13.


Supported __dunder__ names

__members__ is a read-only ordered mapping of member_name:member items. It is only available on the class.

__new__(), if specified, must create and return the enum members; it is also a very good idea to set the member’s _value_ appropriately. Once all the members are created it is no longer used.

Supported _sunder_ names

  • _name_ – name of the member

  • _value_ – value of the member; can be set in __new__

  • _missing_() – a lookup function used when a value is not found; may be overridden

  • _ignore_ – a list of names, either as a list or a str, that will not be transformed into members, and will be removed from the final class

  • _order_ – no longer used, kept for backward compatibility (class attribute, removed during class creation)

  • _generate_next_value_() – used to get an appropriate value for an enum member; may be overridden

  • _add_alias_() – adds a new name as an alias to an existing member.

  • _add_value_alias_() – adds a new value as an alias to an existing member.

  • While _sunder_ names are generally reserved for the further development of the Enum class and can not be used, some are explicitly allowed:

Added in version 3.6: _missing_, _order_, _generate_next_value_

Added in version 3.7: _ignore_

Added in version 3.13: _add_alias_, _add_value_alias_, _repr_*


Utilities and decorators

class enum.auto

auto can be used in place of a value. If used, the Enum machinery will call an Enum’s _generate_next_value_() to get an appropriate value. For Enum and IntEnum that appropriate value will be the highest value seen plus one; for Flag and IntFlag it will be the first power-of-two greater than the highest value seen; for StrEnum it will be the lower-cased version of the member’s name. Care must be taken if mixing auto() with manually specified values.

auto instances are only resolved when at the top level of an assignment, either by itself or as part of a tuple:

  • FIRST = auto() will work (auto() is replaced with 1);

  • SECOND = auto(), -2 will work (auto is replaced with 2, so 2, -2 is used to create the SECOND enum member;

  • THIRD = [auto(), -3] will not work ([<auto instance>, -3] is used to create the THIRD enum member)

Changed in version 3.11.1: In prior versions, auto() had to be the only thing on the assignment line to work properly.

_generate_next_value_ can be overridden to customize the values used by auto.

Note

In version 3.13 the default _generate_next_value_ will always return the highest member value incremented by 1, and will fail if any member is an incompatible type.

@enum.property

A decorator similar to the built-in @property, but specifically for enumerations. It allows member attributes to have the same names as members themselves.

Note

The property and the member must be defined in separate classes; for example, the value and name attributes are defined in the Enum class, and Enum subclasses can define members with the names value and name.

Added in version 3.11.

@enum.unique

A class decorator specifically for enumerations. It searches an enumeration’s __members__, gathering any aliases it finds; if any are found ValueError is raised with the details:

>>> from enum import Enum, unique
>>> @unique
... class Mistake(Enum):
...     ONE = 1
...     TWO = 2
...     THREE = 3
...     FOUR = 3
...
Traceback (most recent call last):
...
ValueError: duplicate values found in <enum 'Mistake'>: FOUR -> THREE
@enum.verify

A class decorator specifically for enumerations. Members from EnumCheck are used to specify which constraints should be checked on the decorated enumeration.

Added in version 3.11.

@enum.member

A decorator for use in enums: its target will become a member.

Added in version 3.11.

@enum.nonmember

A decorator for use in enums: its target will not become a member.

Added in version 3.11.

@enum.global_enum

A decorator to change the str() and repr() of an enum to show its members as belonging to the module instead of its class. Should only be used when the enum members are exported to the module global namespace (see re.RegexFlag for an example).

Added in version 3.11.

enum.show_flag_values(value)

Return a list of all power-of-two integers contained in a flag value.

Added in version 3.11.

enum.bin(num, max_bits=None)

Like built-in bin(), except negative values are represented in two’s complement, and the leading bit always indicates sign (0 implies positive, 1 implies negative).

>>> import enum
>>> enum.bin(10)
'0b0 1010'
>>> enum.bin(~10)   # ~10 is -11
'0b1 0101'

Added in version 3.11.


Notes

IntEnum, StrEnum, and IntFlag

These three enum types are designed to be drop-in replacements for existing integer- and string-based values; as such, they have extra limitations:

  • __str__ uses the value and not the name of the enum member

  • __format__, because it uses __str__, will also use the value of the enum member instead of its name

If you do not need/want those limitations, you can either create your own base class by mixing in the int or str type yourself:

>>> from enum import Enum
>>> class MyIntEnum(int, Enum):
...     pass

or you can reassign the appropriate str(), etc., in your enum:

>>> from enum import Enum, IntEnum
>>> class MyIntEnum(IntEnum):
...     __str__ = Enum.__str__

typing — Support for type hints

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.

typing — Support for type hints

Added in version 3.5.

Source code: Lib/typing.py

Note

The Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, linters, etc.


This module provides runtime support for type hints.

Consider the function below:

def surface_area_of_cube(edge_length: float) -> str:
    return f"The surface area of the cube is {6 * edge_length ** 2}."

The function surface_area_of_cube takes an argument expected to be an instance of float, as indicated by the type hint edge_length: float. The function is expected to return an instance of str, as indicated by the -> str hint.

While type hints can be simple classes like float or str, they can also be more complex. The typing module provides a vocabulary of more advanced type hints.

New features are frequently added to the typing module. The typing_extensions package provides backports of these new features to older versions of Python.

See also

Typing cheat sheet

A quick overview of type hints (hosted at the mypy docs)

Type System Reference section of the mypy docs

The Python typing system is standardised via PEPs, so this reference should broadly apply to most Python type checkers. (Some parts may still be specific to mypy.)

Static Typing with Python

Type-checker-agnostic documentation written by the community detailing type system features, useful typing related tools and typing best practices.

Specification for the Python Type System

The canonical, up-to-date specification of the Python type system can be found at Specification for the Python type system.

Type aliases

A type alias is defined using the type statement, which creates an instance of TypeAliasType. In this example, Vector and list[float] will be treated equivalently by static type checkers:

type Vector = list[float]

def scale(scalar: float, vector: Vector) -> Vector:
    return [scalar * num for num in vector]

# passes type checking; a list of floats qualifies as a Vector.
new_vector = scale(2.0, [1.0, -4.2, 5.4])

Type aliases are useful for simplifying complex type signatures. For example:

from collections.abc import Sequence

type ConnectionOptions = dict[str, str]
type Address = tuple[str, int]
type Server = tuple[Address, ConnectionOptions]

def broadcast_message(message: str, servers: Sequence[Server]) -> None:
    ...

# The static type checker will treat the previous type signature as
# being exactly equivalent to this one.
def broadcast_message(
    message: str,
    servers: Sequence[tuple[tuple[str, int], dict[str, str]]]
) -> None:
    ...

The type statement is new in Python 3.12. For backwards compatibility, type aliases can also be created through simple assignment:

Vector = list[float]

Or marked with TypeAlias to make it explicit that this is a type alias, not a normal variable assignment:

from typing import TypeAlias

Vector: TypeAlias = list[float]

NewType

Use the NewType helper to create distinct types:

from typing import NewType

UserId = NewType('UserId', int)
some_id = UserId(524313)

The static type checker will treat the new type as if it were a subclass of the original type. This is useful in helping catch logical errors:

def get_user_name(user_id: UserId) -> str:
    ...

# passes type checking
user_a = get_user_name(UserId(42351))

# fails type checking; an int is not a UserId
user_b = get_user_name(-1)

You may still perform all int operations on a variable of type UserId, but the result will always be of type int. This lets you pass in a UserId wherever an int might be expected, but will prevent you from accidentally creating a UserId in an invalid way:

# 'output' is of type 'int', not 'UserId'
output = UserId(23413) + UserId(54341)

Note that these checks are enforced only by the static type checker. At runtime, the statement Derived = NewType('Derived', Base) will make Derived a callable that immediately returns whatever parameter you pass it. That means the expression Derived(some_value) does not create a new class or introduce much overhead beyond that of a regular function call.

More precisely, the expression some_value is Derived(some_value) is always true at runtime.

It is invalid to create a subtype of Derived:

from typing import NewType

UserId = NewType('UserId', int)

# Fails at runtime and does not pass type checking
class AdminUserId(UserId): pass

However, it is possible to create a NewType based on a ‘derived’ NewType:

from typing import NewType

UserId = NewType('UserId', int)

ProUserId = NewType('ProUserId', UserId)

and typechecking for ProUserId will work as expected.

See PEP 484 for more details.

Note

Recall that the use of a type alias declares two types to be equivalent to one another. Doing type Alias = Original will make the static type checker treat Alias as being exactly equivalent to Original in all cases. This is useful when you want to simplify complex type signatures.

In contrast, NewType declares one type to be a subtype of another. Doing Derived = NewType('Derived', Original) will make the static type checker treat Derived as a subclass of Original, which means a value of type Original cannot be used in places where a value of type Derived is expected. This is useful when you want to prevent logic errors with minimal runtime cost.

Added in version 3.5.2.

Changed in version 3.10: NewType is now a class rather than a function. As a result, there is some additional runtime cost when calling NewType over a regular function.

Changed in version 3.11: The performance of calling NewType has been restored to its level in Python 3.9.

Annotating callable objects

Functions – or other callable objects – can be annotated using collections.abc.Callable or deprecated typing.Callable. Callable[[int], str] signifies a function that takes a single parameter of type int and returns a str.

For example:

from collections.abc import Callable, Awaitable

def feeder(get_next_item: Callable[[], str]) -> None:
    ...  # Body

def async_query(on_success: Callable[[int], None],
                on_error: Callable[[int, Exception], None]) -> None:
    ...  # Body

async def on_update(value: str) -> None:
    ...  # Body

callback: Callable[[str], Awaitable[None]] = on_update

The subscription syntax must always be used with exactly two values: the argument list and the return type. The argument list must be a list of types, a ParamSpec, Concatenate, or an ellipsis (...). The return type must be a single type.

If a literal ellipsis ... is given as the argument list, it indicates that a callable with any arbitrary parameter list would be acceptable:

def concat(x: str, y: str) -> str:
    return x + y

x: Callable[..., str]
x = str     # OK
x = concat  # Also OK

Callable cannot express complex signatures such as functions that take a variadic number of arguments, overloaded functions, or functions that have keyword-only parameters. However, these signatures can be expressed by defining a Protocol class with a __call__() method:

from collections.abc import Iterable
from typing import Protocol

class Combiner(Protocol):
    def __call__(self, *vals: bytes, maxlen: int | None = None) -> list[bytes]: ...

def batch_proc(data: Iterable[bytes], cb_results: Combiner) -> bytes:
    for item in data:
        ...

def good_cb(*vals: bytes, maxlen: int | None = None) -> list[bytes]:
    ...
def bad_cb(*vals: bytes, maxitems: int | None) -> list[bytes]:
    ...

batch_proc([], good_cb)  # OK
batch_proc([], bad_cb)   # Error! Argument 2 has incompatible type because of
                         # different name and kind in the callback

Callables which take other callables as arguments may indicate that their parameter types are dependent on each other using ParamSpec. Additionally, if that callable adds or removes arguments from other callables, the Concatenate operator may be used. They take the form Callable[ParamSpecVariable, ReturnType] and Callable[Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable], ReturnType] respectively.

Changed in version 3.10: Callable now supports ParamSpec and Concatenate. See PEP 612 for more details.

See also

The documentation for ParamSpec and Concatenate provides examples of usage in Callable.

Generics

Since type information about objects kept in containers cannot be statically inferred in a generic way, many container classes in the standard library support subscription to denote the expected types of container elements.

from collections.abc import Mapping, Sequence

class Employee: ...

# Sequence[Employee] indicates that all elements in the sequence
# must be instances of "Employee".
# Mapping[str, str] indicates that all keys and all values in the mapping
# must be strings.
def notify_by_email(employees: Sequence[Employee],
                    overrides: Mapping[str, str]) -> None: ...

Generic functions and classes can be parameterized by using type parameter syntax:

from collections.abc import Sequence

def first[T](l: Sequence[T]) -> T:  # Function is generic over the TypeVar "T"
    return l[0]

Or by using the TypeVar factory directly:

from collections.abc import Sequence
from typing import TypeVar

U = TypeVar('U')                  # Declare type variable "U"

def second(l: Sequence[U]) -> U:  # Function is generic over the TypeVar "U"
    return l[1]

Changed in version 3.12: Syntactic support for generics is new in Python 3.12.

Annotating tuples

For most containers in Python, the typing system assumes that all elements in the container will be of the same type. For example:

from collections.abc import Mapping

# Type checker will infer that all elements in ``x`` are meant to be ints
x: list[int] = []

# Type checker error: ``list`` only accepts a single type argument:
y: list[int, str] = [1, 'foo']

# Type checker will infer that all keys in ``z`` are meant to be strings,
# and that all values in ``z`` are meant to be either strings or ints
z: Mapping[str, str | int] = {}

list only accepts one type argument, so a type checker would emit an error on the y assignment above. Similarly, Mapping only accepts two type arguments: the first indicates the type of the keys, and the second indicates the type of the values.

Unlike most other Python containers, however, it is common in idiomatic Python code for tuples to have elements which are not all of the same type. For this reason, tuples are special-cased in Python’s typing system. tuple accepts any number of type arguments:

# OK: ``x`` is assigned to a tuple of length 1 where the sole element is an int
x: tuple[int] = (5,)

# OK: ``y`` is assigned to a tuple of length 2;
# element 1 is an int, element 2 is a str
y: tuple[int, str] = (5, "foo")

# Error: the type annotation indicates a tuple of length 1,
# but ``z`` has been assigned to a tuple of length 3
z: tuple[int] = (1, 2, 3)

To denote a tuple which could be of any length, and in which all elements are of the same type T, use the literal ellipsis ...: tuple[T, ...]. To denote an empty tuple, use tuple[()]. Using plain tuple as an annotation is equivalent to using tuple[Any, ...]:

x: tuple[int, ...] = (1, 2)
# These reassignments are OK: ``tuple[int, ...]`` indicates x can be of any length
x = (1, 2, 3)
x = ()
# This reassignment is an error: all elements in ``x`` must be ints
x = ("foo", "bar")

# ``y`` can only ever be assigned to an empty tuple
y: tuple[()] = ()

z: tuple = ("foo", "bar")
# These reassignments are OK: plain ``tuple`` is equivalent to ``tuple[Any, ...]``
z = (1, 2, 3)
z = ()

The type of class objects

A variable annotated with C may accept a value of type C. In contrast, a variable annotated with type[C] (or deprecated typing.Type[C]) may accept values that are classes themselves – specifically, it will accept the class object of C. For example:

a = 3         # Has type ``int``
b = int       # Has type ``type[int]``
c = type(a)   # Also has type ``type[int]``

Note that type[C] is covariant:

class User: ...
class ProUser(User): ...
class TeamUser(User): ...

def make_new_user(user_class: type[User]) -> User:
    # ...
    return user_class()

make_new_user(User)      # OK
make_new_user(ProUser)   # Also OK: ``type[ProUser]`` is a subtype of ``type[User]``
make_new_user(TeamUser)  # Still fine
make_new_user(User())    # Error: expected ``type[User]`` but got ``User``
make_new_user(int)       # Error: ``type[int]`` is not a subtype of ``type[User]``

The only legal parameters for type are classes, Any, type variables, and unions of any of these types. For example:

def new_non_team_user(user_class: type[BasicUser | ProUser]): ...

new_non_team_user(BasicUser)  # OK
new_non_team_user(ProUser)    # OK
new_non_team_user(TeamUser)   # Error: ``type[TeamUser]`` is not a subtype
                              # of ``type[BasicUser | ProUser]``
new_non_team_user(User)       # Also an error

type[Any] is equivalent to type, which is the root of Python’s metaclass hierarchy.

Annotating generators and coroutines

A generator can be annotated using the generic type Generator[YieldType, SendType, ReturnType]. For example:

def echo_round() -> Generator[int, float, str]:
    sent = yield 0
    while sent >= 0:
        sent = yield round(sent)
    return 'Done'

Note that unlike many other generic classes in the standard library, the SendType of Generator behaves contravariantly, not covariantly or invariantly.

The SendType and ReturnType parameters default to None:

def infinite_stream(start: int) -> Generator[int]:
    while True:
        yield start
        start += 1

It is also possible to set these types explicitly:

def infinite_stream(start: int) -> Generator[int, None, None]:
    while True:
        yield start
        start += 1

Simple generators that only ever yield values can also be annotated as having a return type of either Iterable[YieldType] or Iterator[YieldType]:

def infinite_stream(start: int) -> Iterator[int]:
    while True:
        yield start
        start += 1

Async generators are handled in a similar fashion, but don’t expect a ReturnType type argument (AsyncGenerator[YieldType, SendType]). The SendType argument defaults to None, so the following definitions are equivalent:

async def infinite_stream(start: int) -> AsyncGenerator[int]:
    while True:
        yield start
        start = await increment(start)

async def infinite_stream(start: int) -> AsyncGenerator[int, None]:
    while True:
        yield start
        start = await increment(start)

As in the synchronous case, AsyncIterable[YieldType] and AsyncIterator[YieldType] are available as well:

async def infinite_stream(start: int) -> AsyncIterator[int]:
    while True:
        yield start
        start = await increment(start)

Coroutines can be annotated using Coroutine[YieldType, SendType, ReturnType]. Generic arguments correspond to those of Generator, for example:

from collections.abc import Coroutine
c: Coroutine[list[str], str, int]  # Some coroutine defined elsewhere
x = c.send('hi')                   # Inferred type of 'x' is list[str]
async def bar() -> None:
    y = await c                    # Inferred type of 'y' is int

User-defined generic types

A user-defined class can be defined as a generic class.

from logging import Logger

class LoggedVar[T]:
    def __init__(self, value: T, name: str, logger: Logger) -> None:
        self.name = name
        self.logger = logger
        self.value = value

    def set(self, new: T) -> None:
        self.log('Set ' + repr(self.value))
        self.value = new

    def get(self) -> T:
        self.log('Get ' + repr(self.value))
        return self.value

    def log(self, message: str) -> None:
        self.logger.info('%s: %s', self.name, message)

This syntax indicates that the class LoggedVar is parameterised around a single type variable T . This also makes T valid as a type within the class body.

Generic classes implicitly inherit from Generic. For compatibility with Python 3.11 and lower, it is also possible to inherit explicitly from Generic to indicate a generic class:

from typing import TypeVar, Generic

T = TypeVar('T')

class LoggedVar(Generic[T]):
    ...

Generic classes have __class_getitem__() methods, meaning they can be parameterised at runtime (e.g. LoggedVar[int] below):

from collections.abc import Iterable

def zero_all_vars(vars: Iterable[LoggedVar[int]]) -> None:
    for var in vars:
        var.set(0)

A generic type can have any number of type variables. All varieties of TypeVar are permissible as parameters for a generic type:

from typing import TypeVar, Generic, Sequence

class WeirdTrio[T, B: Sequence[bytes], S: (int, str)]:
    ...

OldT = TypeVar('OldT', contravariant=True)
OldB = TypeVar('OldB', bound=Sequence[bytes], covariant=True)
OldS = TypeVar('OldS', int, str)

class OldWeirdTrio(Generic[OldT, OldB, OldS]):
    ...

Each type variable argument to Generic must be distinct. This is thus invalid:

from typing import TypeVar, Generic
...

class Pair[M, M]:  # SyntaxError
    ...

T = TypeVar('T')

class Pair(Generic[T, T]):   # INVALID
    ...

Generic classes can also inherit from other classes:

from collections.abc import Sized

class LinkedList[T](Sized):
    ...

When inheriting from generic classes, some type parameters could be fixed:

from collections.abc import Mapping

class MyDict[T](Mapping[str, T]):
    ...

In this case MyDict has a single parameter, T.

Using a generic class without specifying type parameters assumes Any for each position. In the following example, MyIterable is not generic but implicitly inherits from Iterable[Any]:

from collections.abc import Iterable

class MyIterable(Iterable): # Same as Iterable[Any]
    ...

User-defined generic type aliases are also supported. Examples:

from collections.abc import Iterable

type Response[S] = Iterable[S] | int

# Return type here is same as Iterable[str] | int
def response(query: str) -> Response[str]:
    ...

type Vec[T] = Iterable[tuple[T, T]]

def inproduct[T: (int, float, complex)](v: Vec[T]) -> T: # Same as Iterable[tuple[T, T]]
    return sum(x*y for x, y in v)

For backward compatibility, generic type aliases can also be created through a simple assignment:

from collections.abc import Iterable
from typing import TypeVar

S = TypeVar("S")
Response = Iterable[S] | int

Changed in version 3.7: Generic no longer has a custom metaclass.

Changed in version 3.12: Syntactic support for generics and type aliases is new in version 3.12. Previously, generic classes had to explicitly inherit from Generic or contain a type variable in one of their bases.

User-defined generics for parameter expressions are also supported via parameter specification variables in the form [**P]. The behavior is consistent with type variables’ described above as parameter specification variables are treated by the typing module as a specialized type variable. The one exception to this is that a list of types can be used to substitute a ParamSpec:

>>> class Z[T, **P]: ...  # T is a TypeVar; P is a ParamSpec
...
>>> Z[int, [dict, float]]
__main__.Z[int, [dict, float]]

Classes generic over a ParamSpec can also be created using explicit inheritance from Generic. In this case, ** is not used:

from typing import ParamSpec, Generic

P = ParamSpec('P')

class Z(Generic[P]):
    ...

Another difference between TypeVar and ParamSpec is that a generic with only one parameter specification variable will accept parameter lists in the forms X[[Type1, Type2, ...]] and also X[Type1, Type2, ...] for aesthetic reasons. Internally, the latter is converted to the former, so the following are equivalent:

>>> class X[**P]: ...
...
>>> X[int, str]
__main__.X[[int, str]]
>>> X[[int, str]]
__main__.X[[int, str]]

Note that generics with ParamSpec may not have correct __parameters__ after substitution in some cases because they are intended primarily for static type checking.

Changed in version 3.10: Generic can now be parameterized over parameter expressions. See ParamSpec and PEP 612 for more details.

A user-defined generic class can have ABCs as base classes without a metaclass conflict. Generic metaclasses are not supported. The outcome of parameterizing generics is cached, and most types in the typing module are hashable and comparable for equality.

The Any type

A special kind of type is Any. A static type checker will treat every type as assignable to Any and Any as assignable to every type.

This means that it is possible to perform any operation or method call on a value of type Any and assign it to any variable:

from typing import Any

a: Any = None
a = []          # OK
a = 2           # OK

s: str = ''
s = a           # OK

def foo(item: Any) -> int:
    # Passes type checking; 'item' could be any type,
    # and that type might have a 'bar' method
    item.bar()
    ...

Notice that no type checking is performed when assigning a value of type Any to a more precise type. For example, the static type checker did not report an error when assigning a to s even though s was declared to be of type str and receives an int value at runtime!

Furthermore, all functions without a return type or parameter types will implicitly default to using Any:

def legacy_parser(text):
    ...
    return data

# A static type checker will treat the above
# as having the same signature as:
def legacy_parser(text: Any) -> Any:
    ...
    return data

This behavior allows Any to be used as an escape hatch when you need to mix dynamically and statically typed code.

Contrast the behavior of Any with the behavior of object. Similar to Any, every type is a subtype of object. However, unlike Any, the reverse is not true: object is not a subtype of every other type.

That means when the type of a value is object, a type checker will reject almost all operations on it, and assigning it to a variable (or using it as a return value) of a more specialized type is a type error. For example:

def hash_a(item: object) -> int:
    # Fails type checking; an object does not have a 'magic' method.
    item.magic()
    ...

def hash_b(item: Any) -> int:
    # Passes type checking
    item.magic()
    ...

# Passes type checking, since ints and strs are subclasses of object
hash_a(42)
hash_a("foo")

# Passes type checking, since Any is assignable to all types
hash_b(42)
hash_b("foo")

Use object to indicate that a value could be any type in a typesafe manner. Use Any to indicate that a value is dynamically typed.

Nominal vs structural subtyping

Initially PEP 484 defined the Python static type system as using nominal subtyping. This means that a class A is allowed where a class B is expected if and only if A is a subclass of B.

This requirement previously also applied to abstract base classes, such as Iterable. The problem with this approach is that a class had to be explicitly marked to support them, which is unpythonic and unlike what one would normally do in idiomatic dynamically typed Python code. For example, this conforms to PEP 484:

from collections.abc import Sized, Iterable, Iterator

class Bucket(Sized, Iterable[int]):
    ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[int]: ...

PEP 544 solves this problem by allowing users to write the above code without explicit base classes in the class definition, allowing Bucket to be implicitly considered a subtype of both Sized and Iterable[int] by static type checkers. This is known as structural subtyping (or static duck-typing):

from collections.abc import Iterator, Iterable

class Bucket:  # Note: no base classes
    ...
    def __len__(self) -> int: ...
    def __iter__(self) -> Iterator[int]: ...

def collect(items: Iterable[int]) -> int: ...
result = collect(Bucket())  # Passes type check

Moreover, by subclassing a special class Protocol, a user can define new custom protocols to fully enjoy structural subtyping (see examples below).

Module contents

The typing module defines the following classes, functions and decorators.

Special typing primitives

Special types

These can be used as types in annotations. They do not support subscription using [].

typing.Any

Special type indicating an unconstrained type.

  • Every type is assignable to Any.

  • Any is assignable to every type.

Changed in version 3.11: Any can now be used as a base class. This can be useful for avoiding type checker errors with classes that can duck type anywhere or are highly dynamic.

typing.AnyStr

A constrained type variable.

Definition:

AnyStr = TypeVar('AnyStr', str, bytes)

AnyStr is meant to be used for functions that may accept str or bytes arguments but cannot allow the two to mix.

For example:

def concat(a: AnyStr, b: AnyStr) -> AnyStr:
    return a + b

concat("foo", "bar")    # OK, output has type 'str'
concat(b"foo", b"bar")  # OK, output has type 'bytes'
concat("foo", b"bar")   # Error, cannot mix str and bytes

Note that, despite its name, AnyStr has nothing to do with the Any type, nor does it mean “any string”. In particular, AnyStr and str | bytes are different from each other and have different use cases:

# Invalid use of AnyStr:
# The type variable is used only once in the function signature,
# so cannot be "solved" by the type checker
def greet_bad(cond: bool) -> AnyStr:
    return "hi there!" if cond else b"greetings!"

# The better way of annotating this function:
def greet_proper(cond: bool) -> str | bytes:
    return "hi there!" if cond else b"greetings!"

Deprecated since version 3.13, will be removed in version 3.18: Deprecated in favor of the new type parameter syntax. Use class A[T: (str, bytes)]: ... instead of importing AnyStr. See PEP 695 for more details.

In Python 3.16, AnyStr will be removed from typing.__all__, and deprecation warnings will be emitted at runtime when it is accessed or imported from typing. AnyStr will be removed from typing in Python 3.18.

typing.LiteralString

Special type that includes only literal strings.

Any string literal is compatible with LiteralString, as is another LiteralString. However, an object typed as just str is not. A string created by composing LiteralString-typed objects is also acceptable as a LiteralString.

Example:

def run_query(sql: LiteralString) -> None:
    ...

def caller(arbitrary_string: str, literal_string: LiteralString) -> None:
    run_query("SELECT * FROM students")  # OK
    run_query(literal_string)  # OK
    run_query("SELECT * FROM " + literal_string)  # OK
    run_query(arbitrary_string)  # type checker error
    run_query(  # type checker error
        f"SELECT * FROM students WHERE name = {arbitrary_string}"
    )

LiteralString is useful for sensitive APIs where arbitrary user-generated strings could generate problems. For example, the two cases above that generate type checker errors could be vulnerable to an SQL injection attack.

See PEP 675 for more details.

Added in version 3.11.

typing.Never
typing.NoReturn

Never and NoReturn represent the bottom type, a type that has no members.

They can be used to indicate that a function never returns, such as sys.exit():

from typing import Never  # or NoReturn

def stop() -> Never:
    raise RuntimeError('no way')

Or to define a function that should never be called, as there are no valid arguments, such as assert_never():

from typing import Never  # or NoReturn

def never_call_me(arg: Never) -> None:
    pass

def int_or_str(arg: int | str) -> None:
    never_call_me(arg)  # type checker error
    match arg:
        case int():
            print("It's an int")
        case str():
            print("It's a str")
        case _:
            never_call_me(arg)  # OK, arg is of type Never (or NoReturn)

Never and NoReturn have the same meaning in the type system and static type checkers treat both equivalently.

Added in version 3.6.2: Added NoReturn.

Added in version 3.11: Added Never.

typing.Self

Special type to represent the current enclosed class.

For example:

from typing import Self, reveal_type

class Foo:
    def return_self(self) -> Self:
        ...
        return self

class SubclassOfFoo(Foo): pass

reveal_type(Foo().return_self())  # Revealed type is "Foo"
reveal_type(SubclassOfFoo().return_self())  # Revealed type is "SubclassOfFoo"

This annotation is semantically equivalent to the following, albeit in a more succinct fashion:

from typing import TypeVar

Self = TypeVar("Self", bound="Foo")

class Foo:
    def return_self(self: Self) -> Self:
        ...
        return self

In general, if something returns self, as in the above examples, you should use Self as the return annotation. If Foo.return_self was annotated as returning "Foo", then the type checker would infer the object returned from SubclassOfFoo.return_self as being of type Foo rather than SubclassOfFoo.

Other common use cases include:

  • classmethods that are used as alternative constructors and return instances of the cls parameter.

  • Annotating an __enter__() method which returns self.

You should not use Self as the return annotation if the method is not guaranteed to return an instance of a subclass when the class is subclassed:

class Eggs:
    # Self would be an incorrect return annotation here,
    # as the object returned is always an instance of Eggs,
    # even in subclasses
    def returns_eggs(self) -> "Eggs":
        return Eggs()

See PEP 673 for more details.

Added in version 3.11.

typing.TypeAlias

Special annotation for explicitly declaring a type alias.

For example:

from typing import TypeAlias

Factors: TypeAlias = list[int]

TypeAlias is particularly useful on older Python versions for annotating aliases that make use of forward references, as it can be hard for type checkers to distinguish these from normal variable assignments:

from typing import Generic, TypeAlias, TypeVar

T = TypeVar("T")

# "Box" does not exist yet,
# so we have to use quotes for the forward reference on Python <3.12.
# Using ``TypeAlias`` tells the type checker that this is a type alias declaration,
# not a variable assignment to a string.
BoxOfStrings: TypeAlias = "Box[str]"

class Box(Generic[T]):
    @classmethod
    def make_box_of_strings(cls) -> BoxOfStrings: ...

See PEP 613 for more details.

Added in version 3.10.

Deprecated since version 3.12: TypeAlias is deprecated in favor of the type statement, which creates instances of TypeAliasType and which natively supports forward references. Note that while TypeAlias and TypeAliasType serve similar purposes and have similar names, they are distinct and the latter is not the type of the former. Removal of TypeAlias is not currently planned, but users are encouraged to migrate to type statements.

Special forms

These can be used as types in annotations. They all support subscription using [], but each has a unique syntax.

class typing.Union

Union type; Union[X, Y] is equivalent to X | Y and means either X or Y.

To define a union, use e.g. Union[int, str] or the shorthand int | str. Using that shorthand is recommended. Details:

  • The arguments must be types and there must be at least one.

  • Unions of unions are flattened, e.g.:

    Union[Union[int, str], float] == Union[int, str, float]
    

    However, this does not apply to unions referenced through a type alias, to avoid forcing evaluation of the underlying TypeAliasType:

    type A = Union[int, str]
    Union[A, float] != Union[int, str, float]
    
  • Unions of a single argument vanish, e.g.:

    Union[int] == int  # The constructor actually returns int
    
  • Redundant arguments are skipped, e.g.:

    Union[int, str, int] == Union[int, str] == int | str
    
  • When comparing unions, the argument order is ignored, e.g.:

    Union[int, str] == Union[str, int]
    
  • You cannot subclass or instantiate a Union.

  • You cannot write Union[X][Y].

Changed in version 3.7: Don’t remove explicit subclasses from unions at runtime.

Changed in version 3.10: Unions can now be written as X | Y. See union type expressions.

Changed in version 3.14: types.UnionType is now an alias for Union, and both Union[int, str] and int | str create instances of the same class. To check whether an object is a Union at runtime, use isinstance(obj, Union). For compatibility with earlier versions of Python, use get_origin(obj) is typing.Union or get_origin(obj) is types.UnionType.

typing.Optional

Optional[X] is equivalent to X | None (or Union[X, None]).

Note that this is not the same concept as an optional argument, which is one that has a default. An optional argument with a default does not require the Optional qualifier on its type annotation just because it is optional. For example:

def foo(arg: int = 0) -> None:
    ...

On the other hand, if an explicit value of None is allowed, the use of Optional is appropriate, whether the argument is optional or not. For example:

def foo(arg: Optional[int] = None) -> None:
    ...

Changed in version 3.10: Optional can now be written as X | None. See union type expressions.

typing.Concatenate

Special form for annotating higher-order functions.

Concatenate can be used in conjunction with Callable and ParamSpec to annotate a higher-order callable which adds, removes, or transforms parameters of another callable. Usage is in the form Concatenate[Arg1Type, Arg2Type, ..., ParamSpecVariable]. Concatenate is valid when used in Callable type hints and when instantiating user-defined generic classes with ParamSpec parameters. The last parameter to Concatenate must be a ParamSpec or ellipsis (...).

For example, to annotate a decorator with_lock which provides a threading.Lock to the decorated function, Concatenate can be used to indicate that with_lock expects a callable which takes in a Lock as the first argument, and returns a callable with a different type signature. In this case, the ParamSpec indicates that the returned callable’s parameter types are dependent on the parameter types of the callable being passed in:

from collections.abc import Callable
from threading import Lock
from typing import Concatenate

# Use this lock to ensure that only one thread is executing a function
# at any time.
my_lock = Lock()

def with_lock[**P, R](f: Callable[Concatenate[Lock, P], R]) -> Callable[P, R]:
    '''A type-safe decorator which provides a lock.'''
    def inner(*args: P.args, **kwargs: P.kwargs) -> R:
        # Provide the lock as the first argument.
        return f(my_lock, *args, **kwargs)
    return inner

@with_lock
def sum_threadsafe(lock: Lock, numbers: list[float]) -> float:
    '''Add a list of numbers together in a thread-safe manner.'''
    with lock:
        return sum(numbers)

# We don't need to pass in the lock ourselves thanks to the decorator.
sum_threadsafe([1.1, 2.2, 3.3])

Added in version 3.10.

See also

typing.Literal

Special typing form to define “literal types”.

Literal can be used to indicate to type checkers that the annotated object has a value equivalent to one of the provided literals.

For example:

def validate_simple(data: Any) -> Literal[True]:  # always returns True
    ...

type Mode = Literal['r', 'rb', 'w', 'wb']
def open_helper(file: str, mode: Mode) -> str:
    ...

open_helper('/some/path', 'r')      # Passes type check
open_helper('/other/path', 'typo')  # Error in type checker

Literal[...] cannot be subclassed. At runtime, an arbitrary value is allowed as type argument to Literal[...], but type checkers may impose restrictions. See PEP 586 for more details about literal types.

Additional details:

  • The arguments must be literal values and there must be at least one.

  • Nested Literal types are flattened, e.g.:

    assert Literal[Literal[1, 2], 3] == Literal[1, 2, 3]
    

    However, this does not apply to Literal types referenced through a type alias, to avoid forcing evaluation of the underlying TypeAliasType:

    type A = Literal[1, 2]
    assert Literal[A, 3] != Literal[1, 2, 3]
    
  • Redundant arguments are skipped, e.g.:

    assert Literal[1, 2, 1] == Literal[1, 2]
    
  • When comparing literals, the argument order is ignored, e.g.:

    assert Literal[1, 2] == Literal[2, 1]
    
  • You cannot subclass or instantiate a Literal.

  • You cannot write Literal[X][Y].

Added in version 3.8.

Changed in version 3.9.1: Literal now de-duplicates parameters. Equality comparisons of Literal objects are no longer order dependent. Literal objects will now raise a TypeError exception during equality comparisons if one of their parameters are not hashable.

typing.ClassVar

Special type construct to mark class variables.

As introduced in PEP 526, a variable annotation wrapped in ClassVar indicates that a given attribute is intended to be used as a class variable and should not be set on instances of that class. Usage:

class Starship:
    stats: ClassVar[dict[str, int]] = {} # class variable
    damage: int = 10                     # instance variable

ClassVar accepts only types and cannot be further subscribed.

ClassVar is not a class itself, and cannot be used with isinstance() or issubclass(). ClassVar does not change Python runtime behavior, but it can be used by static type checkers. For example, a type checker might flag the following code as an error:

enterprise_d = Starship(3000)
enterprise_d.stats = {} # Error, setting class variable on instance
Starship.stats = {}     # This is OK

Added in version 3.5.3.

Changed in version 3.13: ClassVar can now be nested in Final and vice versa.

typing.Final

Special typing construct to indicate final names to type checkers.

Final names cannot be reassigned in any scope. Final names declared in class scopes cannot be overridden in subclasses.

For example:

MAX_SIZE: Final = 9000
MAX_SIZE += 1  # Error reported by type checker

class Connection:
    TIMEOUT: Final[int] = 10

class FastConnector(Connection):
    TIMEOUT = 1  # Error reported by type checker

There is no runtime checking of these properties. See PEP 591 for more details.

Added in version 3.8.

Changed in version 3.13: Final can now be nested in ClassVar and vice versa.

typing.Required

Special typing construct to mark a TypedDict key as required.

This is mainly useful for total=False TypedDicts. See TypedDict and PEP 655 for more details.

Added in version 3.11.

typing.NotRequired

Special typing construct to mark a TypedDict key as potentially missing.

See TypedDict and PEP 655 for more details.

Added in version 3.11.

typing.ReadOnly

A special typing construct to mark an item of a TypedDict as read-only.

For example:

class Movie(TypedDict):
   title: ReadOnly[str]
   year: int

def mutate_movie(m: Movie) -> None:
   m["year"] = 1999  # allowed
   m["title"] = "The Matrix"  # type checker error

There is no runtime checking for this property.

See TypedDict and PEP 705 for more details.

Added in version 3.13.

typing.Annotated

Special typing form to add context-specific metadata to an annotation.

Add metadata x to a given type T by using the annotation Annotated[T, x]. Metadata added using Annotated can be used by static analysis tools or at runtime. At runtime, the metadata is stored in a __metadata__ attribute.

If a library or tool encounters an annotation Annotated[T, x] and has no special logic for the metadata, it should ignore the metadata and simply treat the annotation as T. As such, Annotated can be useful for code that wants to use annotations for purposes outside Python’s static typing system.

Using Annotated[T, x] as an annotation still allows for static typechecking of T, as type checkers will simply ignore the metadata x. In this way, Annotated differs from the @no_type_check decorator, which can also be used for adding annotations outside the scope of the typing system, but completely disables typechecking for a function or class.

The responsibility of how to interpret the metadata lies with the tool or library encountering an Annotated annotation. A tool or library encountering an Annotated type can scan through the metadata elements to determine if they are of interest (e.g., using isinstance()).

Annotated[<type>, <metadata>]

Here is an example of how you might use Annotated to add metadata to type annotations if you were doing range analysis:

@dataclass
class ValueRange:
    lo: int
    hi: int

T1 = Annotated[int, ValueRange(-10, 5)]
T2 = Annotated[T1, ValueRange(-20, 3)]

The first argument to Annotated must be a valid type. Multiple metadata elements can be supplied as Annotated supports variadic arguments. The order of the metadata elements is preserved and matters for equality checks:

@dataclass
class ctype:
     kind: str

a1 = Annotated[int, ValueRange(3, 10), ctype("char")]
a2 = Annotated[int, ctype("char"), ValueRange(3, 10)]

assert a1 != a2  # Order matters

It is up to the tool consuming the annotations to decide whether the client is allowed to add multiple metadata elements to one annotation and how to merge those annotations.

Nested Annotated types are flattened. The order of the metadata elements starts with the innermost annotation:

assert Annotated[Annotated[int, ValueRange(3, 10)], ctype("char")] == Annotated[
    int, ValueRange(3, 10), ctype("char")
]

However, this does not apply to Annotated types referenced through a type alias, to avoid forcing evaluation of the underlying TypeAliasType:

type From3To10[T] = Annotated[T, ValueRange(3, 10)]
assert Annotated[From3To10[int], ctype("char")] != Annotated[
   int, ValueRange(3, 10), ctype("char")
]

Duplicated metadata elements are not removed:

assert Annotated[int, ValueRange(3, 10)] != Annotated[
    int, ValueRange(3, 10), ValueRange(3, 10)
]

Annotated can be used with nested and generic aliases:

@dataclass
class MaxLen:
    value: int

type Vec[T] = Annotated[list[tuple[T, T]], MaxLen(10)]

# When used in a type annotation, a type checker will treat "V" the same as
# ``Annotated[list[tuple[int, int]], MaxLen(10)]``:
type V = Vec[int]

Annotated cannot be used with an unpacked TypeVarTuple:

type Variadic[*Ts] = Annotated[*Ts, Ann1] = Annotated[T1, T2, T3, ..., Ann1]  # NOT valid

where T1, T2, … are TypeVars. This is invalid as only one type should be passed to Annotated.

By default, get_type_hints() strips the metadata from annotations. Pass include_extras=True to have the metadata preserved:

>>> from typing import Annotated, get_type_hints
>>> def func(x: Annotated[int, "metadata"]) -> None: pass
...
>>> get_type_hints(func)
{'x': <class 'int'>, 'return': <class 'NoneType'>}
>>> get_type_hints(func, include_extras=True)
{'x': typing.Annotated[int, 'metadata'], 'return': <class 'NoneType'>}

At runtime, the metadata associated with an Annotated type can be retrieved via the __metadata__ attribute:

>>> from typing import Annotated
>>> X = Annotated[int, "very", "important", "metadata"]
>>> X
typing.Annotated[int, 'very', 'important', 'metadata']
>>> X.__metadata__
('very', 'important', 'metadata')

If you want to retrieve the original type wrapped by Annotated, use the __origin__ attribute:

>>> from typing import Annotated, get_origin
>>> Password = Annotated[str, "secret"]
>>> Password.__origin__
<class 'str'>

Note that using get_origin() will return Annotated itself:

>>> get_origin(Password)
typing.Annotated

See also

PEP 593 - Flexible function and variable annotations

The PEP introducing Annotated to the standard library.

Added in version 3.9.

typing.TypeForm

A special form representing the value that results from evaluating a type expression.

This value encodes the information supplied in the type expression, and it represents the type described by that type expression.

When used in a type expression, TypeForm describes a set of type form objects. It accepts a single type argument, which must be a valid type expression. TypeForm[T] describes the set of all type form objects that represent the type T or types assignable to T.

TypeForm(obj) simply returns obj unchanged. This is useful for explicitly marking a value as a type form for static type checkers.

Example:

from typing import Any, TypeForm

def cast[T](typ: TypeForm[T], value: Any) -> T: ...

reveal_type(cast(int, "x"))  # Revealed type is "int"

See PEP 747 for details.

Added in version 3.15.

typing.TypeIs

Special typing construct for marking user-defined type predicate functions.

TypeIs can be used to annotate the return type of a user-defined type predicate function. TypeIs only accepts a single type argument. At runtime, functions marked this way should return a boolean and take at least one positional argument.

TypeIs aims to benefit type narrowing – a technique used by static type checkers to determine a more precise type of an expression within a program’s code flow. Usually type narrowing is done by analyzing conditional code flow and applying the narrowing to a block of code. The conditional expression here is sometimes referred to as a “type predicate”:

def is_str(val: str | float):
    # "isinstance" type predicate
    if isinstance(val, str):
        # Type of ``val`` is narrowed to ``str``
        ...
    else:
        # Else, type of ``val`` is narrowed to ``float``.
        ...

Sometimes it would be convenient to use a user-defined boolean function as a type predicate. Such a function should use TypeIs[...] or TypeGuard as its return type to alert static type checkers to this intention. TypeIs usually has more intuitive behavior than TypeGuard, but it cannot be used when the input and output types are incompatible (e.g., list[object] to list[int]) or when the function does not return True for all instances of the narrowed type.

Using -> TypeIs[NarrowedType] tells the static type checker that for a given function:

  1. The return value is a boolean.

  2. If the return value is True, the type of its argument is the intersection of the argument’s original type and NarrowedType.

  3. If the return value is False, the type of its argument is narrowed to exclude NarrowedType.

For example:

from typing import assert_type, final, TypeIs

class Parent: pass
class Child(Parent): pass
@final
class Unrelated: pass

def is_parent(val: object) -> TypeIs[Parent]:
    return isinstance(val, Parent)

def run(arg: Child | Unrelated):
    if is_parent(arg):
        # Type of ``arg`` is narrowed to the intersection
        # of ``Parent`` and ``Child``, which is equivalent to
        # ``Child``.
        assert_type(arg, Child)
    else:
        # Type of ``arg`` is narrowed to exclude ``Parent``,
        # so only ``Unrelated`` is left.
        assert_type(arg, Unrelated)

The type inside TypeIs must be consistent with the type of the function’s argument; if it is not, static type checkers will raise an error. An incorrectly written TypeIs function can lead to unsound behavior in the type system; it is the user’s responsibility to write such functions in a type-safe manner.

If a TypeIs function is a class or instance method, then the type in TypeIs maps to the type of the second parameter (after cls or self).

In short, the form def foo(arg: TypeA) -> TypeIs[TypeB]: ..., means that if foo(arg) returns True, then arg is an instance of TypeB, and if it returns False, it is not an instance of TypeB.

TypeIs also works with type variables. For more information, see PEP 742 (Narrowing types with TypeIs).

Added in version 3.13.

typing.TypeGuard

Special typing construct for marking user-defined type predicate functions.

Type predicate functions are user-defined functions that return whether their argument is an instance of a particular type. TypeGuard works similarly to TypeIs, but has subtly different effects on type checking behavior (see below).

Using -> TypeGuard tells the static type checker that for a given function:

  1. The return value is a boolean.

  2. If the return value is True, the type of its argument is the type inside TypeGuard.

TypeGuard also works with type variables. See PEP 647 for more details.

For example:

def is_str_list(val: list[object]) -> TypeGuard[list[str]]:
    '''Determines whether all objects in the list are strings'''
    return all(isinstance(x, str) for x in val)

def func1(val: list[object]):
    if is_str_list(val):
        # Type of ``val`` is narrowed to ``list[str]``.
        print(" ".join(val))
    else:
        # Type of ``val`` remains as ``list[object]``.
        print("Not a list of strings!")

TypeIs and TypeGuard differ in the following ways:

  • TypeIs requires the narrowed type to be a subtype of the input type, while TypeGuard does not. The main reason is to allow for things like narrowing list[object] to list[str] even though the latter is not a subtype of the former, since list is invariant.

  • When a TypeGuard function returns True, type checkers narrow the type of the variable to exactly the TypeGuard type. When a TypeIs function returns True, type checkers can infer a more precise type combining the previously known type of the variable with the TypeIs type. (Technically, this is known as an intersection type.)

  • When a TypeGuard function returns False, type checkers cannot narrow the type of the variable at all. When a TypeIs function returns False, type checkers can narrow the type of the variable to exclude the TypeIs type.

Added in version 3.10.

typing.Unpack

Typing operator to conceptually mark an object as having been unpacked.

For example, using the unpack operator * on a type variable tuple is equivalent to using Unpack to mark the type variable tuple as having been unpacked:

Ts = TypeVarTuple('Ts')
tup: tuple[*Ts]
# Effectively does:
tup: tuple[Unpack[Ts]]

In fact, Unpack can be used interchangeably with * in the context of typing.TypeVarTuple and builtins.tuple types. You might see Unpack being used explicitly in older versions of Python, where * couldn’t be used in certain places:

# In older versions of Python, TypeVarTuple and Unpack
# are located in the `typing_extensions` backports package.
from typing_extensions import TypeVarTuple, Unpack

Ts = TypeVarTuple('Ts')
tup: tuple[*Ts]         # Syntax error on Python <= 3.10!
tup: tuple[Unpack[Ts]]  # Semantically equivalent, and backwards-compatible

Unpack can also be used along with typing.TypedDict for typing **kwargs in a function signature:

from typing import TypedDict, Unpack

class Movie(TypedDict):
    name: str
    year: int

# This function expects two keyword arguments - `name` of type `str`
# and `year` of type `int`.
def foo(**kwargs: Unpack[Movie]): ...

See PEP 692 for more details on using Unpack for **kwargs typing.

Added in version 3.11.

Building generic types and type aliases

The following classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating generic types and type aliases.

These objects can be created through special syntax (type parameter lists and the type statement). For compatibility with Python 3.11 and earlier, they can also be created without the dedicated syntax, as documented below.

class typing.Generic

Abstract base class for generic types.

A generic type is typically declared by adding a list of type parameters after the class name:

class Mapping[KT, VT]:
    def __getitem__(self, key: KT) -> VT:
        ...
        # Etc.

Such a class implicitly inherits from Generic. The runtime semantics of this syntax are discussed in the Language Reference.

This class can then be used as follows:

def lookup_name[X, Y](mapping: Mapping[X, Y], key: X, default: Y) -> Y:
    try:
        return mapping[key]
    except KeyError:
        return default

Here the brackets after the function name indicate a generic function.

For backwards compatibility, generic classes can also be declared by explicitly inheriting from Generic. In this case, the type parameters must be declared separately:

KT = TypeVar('KT')
VT = TypeVar('VT')

class Mapping(Generic[KT, VT]):
    def __getitem__(self, key: KT) -> VT:
        ...
        # Etc.
class typing.TypeVar(name, *constraints, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)

Type variable.

The preferred way to construct a type variable is via the dedicated syntax for generic functions, generic classes, and generic type aliases:

class Sequence[T]:  # T is a TypeVar
    ...

This syntax can also be used to create bounded and constrained type variables:

class StrSequence[S: str]:  # S is a TypeVar with a `str` upper bound;
    ...                     # we can say that S is "bounded by `str`"


class StrOrBytesSequence[A: (str, bytes)]:  # A is a TypeVar constrained to str or bytes
    ...

However, if desired, reusable type variables can also be constructed manually, like so:

T = TypeVar('T')  # Can be anything
S = TypeVar('S', bound=str)  # Can be any subtype of str
A = TypeVar('A', str, bytes)  # Must be exactly str or bytes

Type variables exist primarily for the benefit of static type checkers. They serve as the parameters for generic types as well as for generic function and type alias definitions. See Generic for more information on generic types. Generic functions work as follows:

def repeat[T](x: T, n: int) -> Sequence[T]:
    """Return a list containing n references to x."""
    return [x]*n


def print_capitalized[S: str](x: S) -> S:
    """Print x capitalized, and return x."""
    print(x.capitalize())
    return x


def concatenate[A: (str, bytes)](x: A, y: A) -> A:
    """Add two strings or bytes objects together."""
    return x + y

Note that type variables can be bounded, constrained, or neither, but cannot be both bounded and constrained.

The variance of type variables is inferred by type checkers when they are created through the type parameter syntax or when infer_variance=True is passed. Manually created type variables may be explicitly marked covariant or contravariant by passing covariant=True or contravariant=True. By default, manually created type variables are invariant. See PEP 484 and PEP 695 for more details.

Bounded type variables and constrained type variables have different semantics in several important ways. Using a bounded type variable means that the TypeVar will be solved using the most specific type possible:

x = print_capitalized('a string')
reveal_type(x)  # revealed type is str

class StringSubclass(str):
    pass

y = print_capitalized(StringSubclass('another string'))
reveal_type(y)  # revealed type is StringSubclass

z = print_capitalized(45)  # error: int is not a subtype of str

The upper bound of a type variable can be a concrete type, abstract type (ABC or Protocol), or even a union of types:

# Can be anything with an __abs__ method
def print_abs[T: SupportsAbs](arg: T) -> None:
    print("Absolute value:", abs(arg))

U = TypeVar('U', bound=str|bytes)  # Can be any subtype of the union str|bytes
V = TypeVar('V', bound=SupportsAbs)  # Can be anything with an __abs__ method

Using a constrained type variable, however, means that the TypeVar can only ever be solved as being exactly one of the constraints given:

a = concatenate('one', 'two')
reveal_type(a)  # revealed type is str

b = concatenate(StringSubclass('one'), StringSubclass('two'))
reveal_type(b)  # revealed type is str, despite StringSubclass being passed in

c = concatenate('one', b'two')  # error: type variable 'A' can be either str or bytes in a function call, but not both

At runtime, isinstance(x, T) will raise TypeError.

__name__

The name of the type variable.

__covariant__

Whether the type var has been explicitly marked as covariant.

__contravariant__

Whether the type var has been explicitly marked as contravariant.

__infer_variance__

Whether the type variable’s variance should be inferred by type checkers.

Added in version 3.12.

__bound__

The upper bound of the type variable, if any.

Changed in version 3.12: For type variables created through type parameter syntax, the bound is evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation).

evaluate_bound()

An evaluate function corresponding to the __bound__ attribute. When called directly, this method supports only the VALUE format, which is equivalent to accessing the __bound__ attribute directly, but the method object can be passed to annotationlib.call_evaluate_function() to evaluate the value in a different format.

Added in version 3.14.

__constraints__

A tuple containing the constraints of the type variable, if any.

Changed in version 3.12: For type variables created through type parameter syntax, the constraints are evaluated only when the attribute is accessed, not when the type variable is created (see Lazy evaluation).

evaluate_constraints()

An evaluate function corresponding to the __constraints__ attribute. When called directly, this method supports only the VALUE format, which is equivalent to accessing the __constraints__ attribute directly, but the method object can be passed to annotationlib.call_evaluate_function() to evaluate the value in a different format.

Added in version 3.14.

__default__

The default value of the type variable, or typing.NoDefault if it has no default.

Added in version 3.13.

evaluate_default()

An evaluate function corresponding to the __default__ attribute. When called directly, this method supports only the VALUE format, which is equivalent to accessing the __default__ attribute directly, but the method object can be passed to annotationlib.call_evaluate_function() to evaluate the value in a different format.

Added in version 3.14.

has_default()

Return whether or not the type variable has a default value. This is equivalent to checking whether __default__ is not the typing.NoDefault singleton, except that it does not force evaluation of the lazily evaluated default value.

Added in version 3.13.

Changed in version 3.12: Type variables can now be declared using the type parameter syntax introduced by PEP 695. The infer_variance parameter was added.

Changed in version 3.13: Support for default values was added.

class typing.TypeVarTuple(name, *, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)

Type variable tuple. A specialized form of type variable that enables variadic generics.

Type variable tuples can be declared in type parameter lists using a single asterisk (*) before the name:

def move_first_element_to_last[T, *Ts](tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
    return (*tup[1:], tup[0])

Or by explicitly invoking the TypeVarTuple constructor:

T = TypeVar("T")
Ts = TypeVarTuple("Ts")

def move_first_element_to_last(tup: tuple[T, *Ts]) -> tuple[*Ts, T]:
    return (*tup[1:], tup[0])

A normal type variable enables parameterization with a single type. A type variable tuple, in contrast, allows parameterization with an arbitrary number of types by acting like an arbitrary number of type variables wrapped in a tuple. For example:

# T is bound to int, Ts is bound to ()
# Return value is (1,), which has type tuple[int]
move_first_element_to_last(tup=(1,))

# T is bound to int, Ts is bound to (str,)
# Return value is ('spam', 1), which has type tuple[str, int]
move_first_element_to_last(tup=(1, 'spam'))

# T is bound to int, Ts is bound to (str, float)
# Return value is ('spam', 3.0, 1), which has type tuple[str, float, int]
move_first_element_to_last(tup=(1, 'spam', 3.0))

# This fails to type check (and fails at runtime)
# because tuple[()] is not compatible with tuple[T, *Ts]
# (at least one element is required)
move_first_element_to_last(tup=())

Note the use of the unpacking operator * in tuple[T, *Ts]. Conceptually, you can think of Ts as a tuple of type variables (T1, T2, ...). tuple[T, *Ts] would then become tuple[T, *(T1, T2, ...)], which is equivalent to tuple[T, T1, T2, ...]. (Note that in older versions of Python, you might see this written using Unpack instead, as Unpack[Ts].)

Type variable tuples must always be unpacked. This helps distinguish type variable tuples from normal type variables:

x: Ts          # Not valid
x: tuple[Ts]   # Not valid
x: tuple[*Ts]  # The correct way to do it

Type variable tuples can be used in the same contexts as normal type variables. For example, in class definitions, arguments, and return types:

class Array[*Shape]:
    def __getitem__(self, key: tuple[*Shape]) -> float: ...
    def __abs__(self) -> "Array[*Shape]": ...
    def get_shape(self) -> tuple[*Shape]: ...

Type variable tuples can be happily combined with normal type variables:

class Array[DType, *Shape]:  # This is fine
    pass

class Array2[*Shape, DType]:  # This would also be fine
    pass

class Height: ...
class Width: ...

float_array_1d: Array[float, Height] = Array()     # Totally fine
int_array_2d: Array[int, Height, Width] = Array()  # Yup, fine too

However, note that at most one type variable tuple may appear in a single list of type arguments or type parameters:

x: tuple[*Ts, *Ts]            # Not valid
class Array[*Shape, *Shape]:  # Not valid
    pass

Finally, an unpacked type variable tuple can be used as the type annotation of *args:

def call_soon[*Ts](
    callback: Callable[[*Ts], None],
    *args: *Ts
) -> None:
    ...
    callback(*args)

In contrast to non-unpacked annotations of *args - e.g. *args: int, which would specify that all arguments are int - *args: *Ts enables reference to the types of the individual arguments in *args. Here, this allows us to ensure the types of the *args passed to call_soon match the types of the (positional) arguments of callback.

See PEP 646 for more details on type variable tuples.

__name__

The name of the type variable tuple.

__covariant__

Whether the type variable tuple has been explicitly marked as covariant.

Added in version 3.15.

__contravariant__

Whether the type variable tuple has been explicitly marked as contravariant.

Added in version 3.15.

__infer_variance__

Whether the type variable tuple’s variance should be inferred by type checkers.

Added in version 3.15.

__default__

The default value of the type variable tuple, or typing.NoDefault if it has no default.

Added in version 3.13.

evaluate_default()

An evaluate function corresponding to the __default__ attribute. When called directly, this method supports only the VALUE format, which is equivalent to accessing the __default__ attribute directly, but the method object can be passed to annotationlib.call_evaluate_function() to evaluate the value in a different format.

Added in version 3.14.

has_default()

Return whether or not the type variable tuple has a default value. This is equivalent to checking whether __default__ is not the typing.NoDefault singleton, except that it does not force evaluation of the lazily evaluated default value.

Added in version 3.13.

Type variable tuples created with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. The bound argument is also accepted, similar to TypeVar, but its actual semantics are yet to be decided.

Added in version 3.11.

Changed in version 3.12: Type variable tuples can now be declared using the type parameter syntax introduced by PEP 695.

Changed in version 3.13: Support for default values was added.

Changed in version 3.15: Added support for the bound, covariant, contravariant, and infer_variance parameters.

class typing.ParamSpec(name, *, bound=None, covariant=False, contravariant=False, infer_variance=False, default=typing.NoDefault)

Parameter specification variable. A specialized version of type variables.

In type parameter lists, parameter specifications can be declared with two asterisks (**):

type IntFunc[**P] = Callable[P, int]

For compatibility with Python 3.11 and earlier, ParamSpec objects can also be created as follows:

P = ParamSpec('P')

Parameter specification variables exist primarily for the benefit of static type checkers. They are used to forward the parameter types of one callable to another callable – a pattern commonly found in higher order functions and decorators. They are only valid when used in Concatenate, or as the first argument to Callable, or as parameters for user-defined Generics. See Generic for more information on generic types.

For example, to add basic logging to a function, one can create a decorator add_logging to log function calls. The parameter specification variable tells the type checker that the callable passed into the decorator and the new callable returned by it have inter-dependent type parameters:

from collections.abc import Callable
import logging

def add_logging[T, **P](f: Callable[P, T]) -> Callable[P, T]:
    '''A type-safe decorator to add logging to a function.'''
    def inner(*args: P.args, **kwargs: P.kwargs) -> T:
        logging.info(f'{f.__name__} was called')
        return f(*args, **kwargs)
    return inner

@add_logging
def add_two(x: float, y: float) -> float:
    '''Add two numbers together.'''
    return x + y

Without ParamSpec, the simplest way to annotate this previously was to use a TypeVar with upper bound Callable[..., Any]. However this causes two problems:

  1. The type checker can’t type check the inner function because *args and **kwargs have to be typed Any.

  2. cast() may be required in the body of the add_logging decorator when returning the inner function, or the static type checker must be told to ignore the return inner.

args
kwargs

Since ParamSpec captures both positional and keyword parameters, P.args and P.kwargs can be used to split a ParamSpec into its components. P.args represents the tuple of positional parameters in a given call and should only be used to annotate *args. P.kwargs represents the mapping of keyword parameters to their values in a given call, and should be only be used to annotate **kwargs. Both attributes require the annotated parameter to be in scope. At runtime, P.args and P.kwargs are instances respectively of ParamSpecArgs and ParamSpecKwargs.

__name__

The name of the parameter specification.

__covariant__

Whether the parameter specification has been explicitly marked as covariant.

__contravariant__

Whether the parameter specification has been explicitly marked as contravariant.

__infer_variance__

Whether the parameter specification’s variance should be inferred by type checkers.

Added in version 3.12.

__default__

The default value of the parameter specification, or typing.NoDefault if it has no default.

Added in version 3.13.

evaluate_default()

An evaluate function corresponding to the __default__ attribute. When called directly, this method supports only the VALUE format, which is equivalent to accessing the __default__ attribute directly, but the method object can be passed to annotationlib.call_evaluate_function() to evaluate the value in a different format.

Added in version 3.14.

has_default()

Return whether or not the parameter specification has a default value. This is equivalent to checking whether __default__ is not the typing.NoDefault singleton, except that it does not force evaluation of the lazily evaluated default value.

Added in version 3.13.

Parameter specification variables created with covariant=True or contravariant=True can be used to declare covariant or contravariant generic types. The bound argument is also accepted, similar to TypeVar. However the actual semantics of these keywords are yet to be decided.

Added in version 3.10.

Changed in version 3.12: Parameter specifications can now be declared using the type parameter syntax introduced by PEP 695.

Changed in version 3.13: Support for default values was added.

Note

Only parameter specification variables defined in global scope can be pickled.

See also

class typing.ParamSpecArgs
class typing.ParamSpecKwargs

Arguments and keyword arguments attributes of a ParamSpec. The P.args attribute of a ParamSpec is an instance of ParamSpecArgs, and P.kwargs is an instance of ParamSpecKwargs. They are intended for runtime introspection and have no special meaning to static type checkers.

Calling get_origin() on either of these objects will return the original ParamSpec:

>>> from typing import ParamSpec, get_origin
>>> P = ParamSpec("P")
>>> get_origin(P.args) is P
True
>>> get_origin(P.kwargs) is P
True

Added in version 3.10.

class typing.TypeAliasType(name, value, *, type_params=(), qualname=None)

The type of type aliases created through the type statement.

Example:

>>> type Alias = int
>>> type(Alias)
<class 'typing.TypeAliasType'>

Added in version 3.12.

__name__

The name of the type alias:

>>> type Alias = int
>>> Alias.__name__
'Alias'
__qualname__

The qualified name of the type alias:

>>> class Class:
...     type Alias = int
...
>>> Class.Alias.__qualname__
'Class.Alias'

Added in version 3.15.

__module__

The name of the module in which the type alias was defined:

>>> type Alias = int
>>> Alias.__module__
'__main__'

This attribute is writable.

Changed in version 3.15: The attribute is now writable.

__type_params__

The type parameters of the type alias, or an empty tuple if the alias is not generic:

>>> type ListOrSet[T] = list[T] | set[T]
>>> ListOrSet.__type_params__
(T,)
>>> type NotGeneric = int
>>> NotGeneric.__type_params__
()
__value__

The type alias’s value. This is lazily evaluated, so names used in the definition of the alias are not resolved until the __value__ attribute is accessed:

>>> type Mutually = Recursive
>>> type Recursive = Mutually
>>> Mutually
Mutually
>>> Recursive
Recursive
>>> Mutually.__value__
Recursive
>>> Recursive.__value__
Mutually
evaluate_value()

An evaluate function corresponding to the __value__ attribute. When called directly, this method supports only the VALUE format, which is equivalent to accessing the __value__ attribute directly, but the method object can be passed to annotationlib.call_evaluate_function() to evaluate the value in a different format:

>>> type Alias = undefined
>>> Alias.__value__
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> from annotationlib import Format, call_evaluate_function
>>> Alias.evaluate_value(Format.VALUE)
Traceback (most recent call last):
...
NameError: name 'undefined' is not defined
>>> call_evaluate_function(Alias.evaluate_value, Format.FORWARDREF)
ForwardRef('undefined')

Added in version 3.14.

Unpacking

Type aliases support star unpacking using the *Alias syntax. This is equivalent to using Unpack[Alias] directly:

>>> type Alias = tuple[int, str]
>>> type Unpacked = tuple[bool, *Alias]
>>> Unpacked.__value__
tuple[bool, typing.Unpack[Alias]]

Added in version 3.14.

Other special directives

These functions and classes should not be used directly as annotations. Their intended purpose is to be building blocks for creating and declaring types.

class typing.NamedTuple

Typed version of collections.namedtuple().

Usage:

class Employee(NamedTuple):
    name: str
    id: int

This is equivalent to:

Employee = collections.namedtuple('Employee', ['name', 'id'])

To give a field a default value, you can assign to it in the class body:

class Employee(NamedTuple):
    name: str
    id: int = 3

employee = Employee('Guido')
assert employee.id == 3

Fields with a default value must come after any fields without a default.

The types for each field name can be retrieved by calling annotationlib.get_annotations() on the resulting class. (The field names are in the _fields attribute and the default values are in the _field_defaults attribute, both of which are part of the namedtuple() API.)

NamedTuple subclasses can also have docstrings and methods:

class Employee(NamedTuple):
    """Represents an employee."""
    name: str
    id: int = 3

    def __repr__(self) -> str:
        return f'<Employee {self.name}, id={self.id}>'

NamedTuple subclasses can be generic:

class Group[T](NamedTuple):
    key: T
    group: list[T]

Backward-compatible usage:

# For creating a generic NamedTuple on Python 3.11
T = TypeVar("T")

class Group(NamedTuple, Generic[T]):
    key: T
    group: list[T]

# A functional syntax is also supported
Employee = NamedTuple('Employee', [('name', str), ('id', int)])

Changed in version 3.6: Added support for PEP 526 variable annotation syntax.

Changed in version 3.6.1: Added support for default values, methods, and docstrings.

Changed in version 3.8: The _field_types and __annotations__ attributes are now regular dictionaries instead of instances of OrderedDict.

Changed in version 3.9: Removed the _field_types attribute in favor of the more standard __annotations__ attribute which has the same information.

Changed in version 3.9: NamedTuple is now a function rather than a class. It can still be used as a class base, as described above.

Changed in version 3.11: Added support for generic namedtuples.

Changed in version 3.14: Using super() (and the __class__ closure variable) in methods of NamedTuple subclasses is unsupported and causes a TypeError.

class typing.NewType(name, tp)

Helper class to create low-overhead distinct types.

A NewType is considered a distinct type by a type checker. At runtime, however, calling a NewType returns its argument unchanged.

Usage:

UserId = NewType('UserId', int)  # Declare the NewType "UserId"
first_user = UserId(1)  # "UserId" returns the argument unchanged at runtime
__module__

The name of the module in which the new type is defined.

__name__

The name of the new type.

__supertype__

The type that the new type is based on.

Added in version 3.5.2.

Changed in version 3.10: NewType is now a class rather than a function.

class typing.Protocol(Generic)

Base class for protocol classes.

Protocol classes are defined like this:

class Proto(Protocol):
    def meth(self) -> int:
        ...

Such classes are primarily used with static type checkers that recognize structural subtyping (static duck-typing), for example:

class C:
    def meth(self) -> int:
        return 0

def func(x: Proto) -> int:
    return x.meth()

func(C())  # Passes static type check

See PEP 544 for more details. Protocol classes decorated with @runtime_checkable (described later) act as simple-minded runtime protocols that check only the presence of given attributes, ignoring their type signatures. Protocol classes without this decorator cannot be used as the second argument to isinstance() or issubclass().

Protocol classes can be generic, for example:

class GenProto[T](Protocol):
    def meth(self) -> T:
        ...

In code that needs to be compatible with Python 3.11 or older, generic Protocols can be written as follows:

T = TypeVar("T")

class GenProto(Protocol[T]):
    def meth(self) -> T:
        ...

Added in version 3.8.

Deprecated since version 3.15, will be removed in version 3.20: It is deprecated to call isinstance() and issubclass() checks on protocol classes that were not explicitly decorated with runtime_checkable() but that inherit from a runtime-checkable protocol class. This will throw a TypeError in Python 3.20.

@typing.runtime_checkable

Mark a protocol class as a runtime protocol.

Such a protocol can be used with isinstance() and issubclass(). This allows a simple-minded structural check, very similar to “one-trick ponies” in collections.abc such as Iterable. For example:

@runtime_checkable
class Closable(Protocol):
    def close(self): ...

assert isinstance(open('/some/file'), Closable)

@runtime_checkable
class Named(Protocol):
    name: str

import threading
assert isinstance(threading.Thread(name='Bob'), Named)

Runtime checkability of protocols is not inherited. A subclass of a runtime-checkable protocol is only runtime-checkable if it is explicitly marked as such, regardless of class hierarchy:

@runtime_checkable
class Iterable(Protocol):
    def __iter__(self): ...

# Without @runtime_checkable, Reversible would no longer be runtime-checkable.
@runtime_checkable
class Reversible(Iterable, Protocol):
    def __reversed__(self): ...

This decorator raises TypeError when applied to a non-protocol class.

Note

@runtime_checkable will check only the presence of the required methods or attributes, not their type signatures or types. For example, ssl.SSLObject is a class, therefore it passes an issubclass() check against Callable. However, the ssl.SSLObject.__init__ method exists only to raise a TypeError with a more informative message, therefore making it impossible to call (instantiate) ssl.SSLObject.

Note

An isinstance() check against a runtime-checkable protocol can be surprisingly slow compared to an isinstance() check against a non-protocol class. Consider using alternative idioms such as hasattr() calls for structural checks in performance-sensitive code.

Added in version 3.8.

Changed in version 3.12: The internal implementation of isinstance() checks against runtime-checkable protocols now uses inspect.getattr_static() to look up attributes (previously, hasattr() was used). As a result, some objects which used to be considered instances of a runtime-checkable protocol may no longer be considered instances of that protocol on Python 3.12+, and vice versa. Most users are unlikely to be affected by this change.

Changed in version 3.12: The members of a runtime-checkable protocol are now considered “frozen” at runtime as soon as the class has been created. Monkey-patching attributes onto a runtime-checkable protocol will still work, but will have no impact on isinstance() checks comparing objects to the protocol. See What’s new in Python 3.12 for more details.

Deprecated since version 3.15, will be removed in version 3.20: It is deprecated to call isinstance() and issubclass() checks on protocol classes that were not explicitly decorated with runtime_checkable() but that inherit from a runtime-checkable protocol class. This will throw a TypeError in Python 3.20.

class typing.TypedDict(dict)

Special construct to add type hints to a dictionary. At runtime “TypedDict instances” are simply dicts.

TypedDict declares a dictionary type that expects all of its instances to have a certain set of keys, where each key is associated with a value of a consistent type. This expectation is not checked at runtime but is only enforced by type checkers. Usage:

class Point2D(TypedDict):
    x: int
    y: int
    label: str

a: Point2D = {'x': 1, 'y': 2, 'label': 'good'}  # OK
b: Point2D = {'z': 3, 'label': 'bad'}           # Fails type check

assert Point2D(x=1, y=2, label='first') == dict(x=1, y=2, label='first')

An alternative way to create a TypedDict is by using function-call syntax. The second argument must be a literal dict:

Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': str})

This functional syntax allows defining keys which are not valid identifiers, for example because they are keywords or contain hyphens, or when key names must not be mangled like regular private names:

# raises SyntaxError
class Point2D(TypedDict):
    in: int  # 'in' is a keyword
    x-y: int  # name with hyphens

class Definition(TypedDict):
    __schema: str  # mangled to `_Definition__schema`

# OK, functional syntax
Point2D = TypedDict('Point2D', {'in': int, 'x-y': int})
Definition = TypedDict('Definition', {'__schema': str})  # not mangled

By default, all keys must be present in a TypedDict. It is possible to mark individual keys as non-required using NotRequired:

class Point2D(TypedDict):
    x: int
    y: int
    label: NotRequired[str]

# Alternative syntax
Point2D = TypedDict('Point2D', {'x': int, 'y': int, 'label': NotRequired[str]})

This means that a Point2D TypedDict can have the label key omitted.

It is also possible to mark all keys as non-required by default by specifying a totality of False:

class Point2D(TypedDict, total=False):
    x: int
    y: int

# Alternative syntax
Point2D = TypedDict('Point2D', {'x': int, 'y': int}, total=False)

This means that a Point2D TypedDict can have any of the keys omitted. A type checker is only expected to support a literal False or True as the value of the total argument. True is the default, and makes all items defined in the class body required.

Individual keys of a total=False TypedDict can be marked as required using Required:

class Point2D(TypedDict, total=False):
    x: Required[int]
    y: Required[int]
    label: str

# Alternative syntax
Point2D = TypedDict('Point2D', {
    'x': Required[int],
    'y': Required[int],
    'label': str
}, total=False)

It is possible for a TypedDict type to inherit from one or more other TypedDict types using the class-based syntax. Usage:

class Point3D(Point2D):
    z: int

Point3D has three items: x, y and z. It is equivalent to this definition:

class Point3D(TypedDict):
    x: int
    y: int
    z: int

By default, a TypedDict is open, meaning that it may contain additional keys at runtime beyond those defined in the class body. The closed class argument can be used to control this; if closed=True, the TypedDict cannot contain additional keys.

class ClosedPoint(TypedDict, closed=True):
    x: int
    y: int

class ClosedPoint3D(ClosedPoint):  # type checker error: cannot add keys to a closed TypedDict
    z: int

Setting closed=False explicitly requests the default open behavior. If the argument is not passed, this state is inherited from the parent class.

In addition to being open or closed, a TypedDict can also be configured to have extra items. If the extra_items class argument is set to a type, the TypedDict can contain arbitrary additional keys, but the values of those keys must be of the specified type.

class ExtraItemsPoint(TypedDict, extra_items=int):
    x: int
    y: int

point: ExtraItemsPoint = {'x': 1, 'y': 2, 'anything': 3}  # OK

The extra_items argument is also inherited through subclassing. It is unset by default, and it may not be used together with the closed argument.

A TypedDict cannot inherit from a non-TypedDict class, except for Generic. For example:

class X(TypedDict):
    x: int

class Y(TypedDict):
    y: int

class Z(object): pass  # A non-TypedDict class

class XY(X, Y): pass  # OK

class XZ(X, Z): pass  # raises TypeError

A TypedDict can be generic:

class Group[T](TypedDict):
    key: T
    group: list[T]

To create a generic TypedDict that is compatible with Python 3.11 or lower, inherit from Generic explicitly:

T = TypeVar("T")

class Group(TypedDict, Generic[T]):
    key: T
    group: list[T]

A TypedDict can be introspected via annotationlib.get_annotations() (see Annotations Best Practices for more information on annotations best practices) and the following attributes:

__total__

Point2D.__total__ gives the value of the total argument. Example:

>>> from typing import TypedDict
>>> class Point2D(TypedDict): pass
>>> Point2D.__total__
True
>>> class Point2D(TypedDict, total=False): pass
>>> Point2D.__total__
False
>>> class Point3D(Point2D): pass
>>> Point3D.__total__
True

This attribute reflects only the value of the total argument to the current TypedDict class, not whether the class is semantically total. For example, a TypedDict with __total__ set to True may have keys marked with NotRequired, or it may inherit from another TypedDict with total=False. Therefore, it is generally better to use __required_keys__ and __optional_keys__ for introspection.

__required_keys__

Added in version 3.9.

__optional_keys__

Point2D.__required_keys__ and Point2D.__optional_keys__ return frozenset objects containing required and non-required keys, respectively.

Keys marked with Required will always appear in __required_keys__ and keys marked with NotRequired will always appear in __optional_keys__.

For backwards compatibility with Python 3.10 and below, it is also possible to use inheritance to declare both required and non-required keys in the same TypedDict. This is done by declaring a TypedDict with one value for the total argument and then inheriting from it in another TypedDict with a different value for total:

>>> class Point2D(TypedDict, total=False):
...     x: int
...     y: int
...
>>> class Point3D(Point2D):
...     z: int
...
>>> Point3D.__required_keys__ == frozenset({'z'})
True
>>> Point3D.__optional_keys__ == frozenset({'x', 'y'})
True

Added in version 3.9.

Note

If from __future__ import annotations is used or if annotations are given as strings, annotations are not evaluated when the TypedDict is defined. Therefore, the runtime introspection that __required_keys__ and __optional_keys__ rely on may not work properly, and the values of the attributes may be incorrect.

__readonly_keys__

A frozenset containing the names of all read-only keys. Keys are read-only if they carry the ReadOnly qualifier.

Added in version 3.13.

__mutable_keys__

A frozenset containing the names of all mutable keys. Keys are mutable if they do not carry the ReadOnly qualifier.

Added in version 3.13.

__closed__

The value of the closed class argument. It can be True, False, or None.

__extra_items__

The value of the extra_items class argument. It can be a valid type or NoExtraItems.

See the TypedDict section in the typing documentation for more examples and detailed rules.

Added in version 3.8.

Changed in version 3.9: TypedDict is now a function rather than a class. It can still be used as a class base, as described above.

Changed in version 3.11: Added support for marking individual keys as Required or NotRequired. See PEP 655.

Changed in version 3.11: Added support for generic TypedDicts.

Changed in version 3.13: Removed support for the keyword-argument method of creating TypedDicts.

Changed in version 3.13: Support for the ReadOnly qualifier was added. See PEP 705.

Changed in version 3.15: Support for the closed and extra_items class arguments was added. See PEP 728.

Protocols

The following protocols are provided by the typing module. All are decorated with @runtime_checkable.

class typing.SupportsAbs

A protocol with one abstract method __abs__ that is covariant in its return type.

class typing.SupportsBytes

A protocol with one abstract method __bytes__.

class typing.SupportsComplex

A protocol with one abstract method __complex__.

class typing.SupportsFloat

A protocol with one abstract method __float__.

class typing.SupportsIndex

A protocol with one abstract method __index__.

Added in version 3.8.

class typing.SupportsInt

A protocol with one abstract method __int__.

class typing.SupportsRound

A protocol with one abstract method __round__ that is covariant in its return type.

ABCs and Protocols for working with I/O

class typing.IO[AnyStr]
class typing.TextIO
class typing.BinaryIO

Generic class IO[AnyStr] and its subclasses TextIO(IO[str]) and BinaryIO(IO[bytes]) represent the types of I/O streams such as returned by open(). Please note that these classes are not protocols, and their interface is fairly broad.

The protocols io.Reader and io.Writer offer a simpler alternative for argument types, when only the read() or write() methods are accessed, respectively:

def read_and_write(reader: Reader[str], writer: Writer[bytes]):
    data = reader.read()
    writer.write(data.encode())

Also consider using collections.abc.Iterable for iterating over the lines of an input stream:

def read_config(stream: Iterable[str]):
    for line in stream:
        ...

Functions and decorators

typing.cast(typ, val)

Cast a value to a type.

This returns the value unchanged. To the type checker this signals that the return value has the designated type, but at runtime we intentionally don’t check anything (we want this to be as fast as possible).

typing.assert_type(val, typ, /)

Ask a static type checker to confirm that val has an inferred type of typ.

At runtime this does nothing: it returns the first argument unchanged with no checks or side effects, no matter the actual type of the argument.

When a static type checker encounters a call to assert_type(), it emits an error if the value is not of the specified type:

def greet(name: str) -> None:
    assert_type(name, str)  # OK, inferred type of `name` is `str`
    assert_type(name, int)  # type checker error

This function is useful for ensuring the type checker’s understanding of a script is in line with the developer’s intentions:

def complex_function(arg: object):
    # Do some complex type-narrowing logic,
    # after which we hope the inferred type will be `int`
    ...
    # Test whether the type checker correctly understands our function
    assert_type(arg, int)

Added in version 3.11.

typing.assert_never(arg, /)

Ask a static type checker to confirm that a line of code is unreachable.

Example:

def int_or_str(arg: int | str) -> None:
    match arg:
        case int():
            print("It's an int")
        case str():
            print("It's a str")
        case _ as unreachable:
            assert_never(unreachable)

Here, the annotations allow the type checker to infer that the last case can never execute, because arg is either an int or a str, and both options are covered by earlier cases.

If a type checker finds that a call to assert_never() is reachable, it will emit an error. For example, if the type annotation for arg was instead int | str | float, the type checker would emit an error pointing out that unreachable is of type float. For a call to assert_never to pass type checking, the inferred type of the argument passed in must be the bottom type, Never, and nothing else.

At runtime, this throws an exception when called.

See also

Unreachable Code and Exhaustiveness Checking has more information about exhaustiveness checking with static typing.

Added in version 3.11.

typing.reveal_type(obj, /)

Ask a static type checker to reveal the inferred type of an expression.

When a static type checker encounters a call to this function, it emits a diagnostic with the inferred type of the argument. For example:

x: int = 1
reveal_type(x)  # Revealed type is "builtins.int"

This can be useful when you want to debug how your type checker handles a particular piece of code.

At runtime, this function prints the runtime type of its argument to sys.stderr and returns the argument unchanged (allowing the call to be used within an expression):

x = reveal_type(1)  # prints "Runtime type is int"
print(x)  # prints "1"

Note that the runtime type may be different from (more or less specific than) the type statically inferred by a type checker.

Most type checkers support reveal_type() anywhere, even if the name is not imported from typing. Importing the name from typing, however, allows your code to run without runtime errors and communicates intent more clearly.

Added in version 3.11.

@typing.dataclass_transform(*, eq_default=True, order_default=False, kw_only_default=False, frozen_default=False, field_specifiers=(), **kwargs)

Decorator to mark an object as providing dataclass-like behavior.

@dataclass_transform may be used to decorate a class, metaclass, or a function that is itself a decorator. The presence of @dataclass_transform() tells a static type checker that the decorated object performs runtime “magic” that transforms a class in a similar way to @dataclasses.dataclass.

Example usage with a decorator function:

@dataclass_transform()
def create_model[T](cls: type[T]) -> type[T]:
    ...
    return cls

@create_model
class CustomerModel:
    id: int
    name: str

On a base class:

@dataclass_transform()
class ModelBase: ...

class CustomerModel(ModelBase):
    id: int
    name: str

On a metaclass:

@dataclass_transform()
class ModelMeta(type): ...

class ModelBase(metaclass=ModelMeta): ...

class CustomerModel(ModelBase):
    id: int
    name: str

The CustomerModel classes defined above will be treated by type checkers similarly to classes created with @dataclasses.dataclass. For example, type checkers will assume these classes have __init__ methods that accept id and name.

The decorated class, metaclass, or function may accept the following bool arguments which type checkers will assume have the same effect as they would have on the @dataclasses.dataclass decorator: init, eq, order, unsafe_hash, frozen, match_args, kw_only, and slots. It must be possible for the value of these arguments (True or False) to be statically evaluated.

The arguments to the @dataclass_transform decorator can be used to customize the default behaviors of the decorated class, metaclass, or function:

Parameters:
  • eq_default (bool) – Indicates whether the eq parameter is assumed to be True or False if it is omitted by the caller. Defaults to True.

  • order_default (bool) – Indicates whether the order parameter is assumed to be True or False if it is omitted by the caller. Defaults to False.

  • kw_only_default (bool) – Indicates whether the kw_only parameter is assumed to be True or False if it is omitted by the caller. Defaults to False.

  • frozen_default (bool) –

    Indicates whether the frozen parameter is assumed to be True or False if it is omitted by the caller. Defaults to False.

    Added in version 3.12.

  • field_specifiers (tuple[Callable[..., Any], ...]) – Specifies a static list of supported classes or functions that describe fields, similar to dataclasses.field(). Defaults to ().

  • **kwargs (Any) – Arbitrary other keyword arguments are accepted in order to allow for possible future extensions.

Type checkers recognize the following optional parameters on field specifiers:

Recognised parameters for field specifiers

Parameter name

Description

init

Indicates whether the field should be included in the synthesized __init__ method. If unspecified, init defaults to True.

default

Provides the default value for the field.

default_factory

Provides a runtime callback that returns the default value for the field. If neither default nor default_factory are specified, the field is assumed to have no default value and must be provided a value when the class is instantiated.

factory

An alias for the default_factory parameter on field specifiers.

kw_only

Indicates whether the field should be marked as keyword-only. If True, the field will be keyword-only. If False, it will not be keyword-only. If unspecified, the value of the kw_only parameter on the object decorated with @dataclass_transform will be used, or if that is unspecified, the value of kw_only_default on @dataclass_transform will be used.

alias

Provides an alternative name for the field. This alternative name is used in the synthesized __init__ method.

At runtime, this decorator records its arguments in the __dataclass_transform__ attribute on the decorated object. It has no other runtime effect.

See PEP 681 for more details.

Added in version 3.11.

@typing.overload

Decorator for creating overloaded functions and methods.

The @overload decorator allows describing functions and methods that support multiple different combinations of argument types. A series of @overload-decorated definitions must be followed by exactly one non-@overload-decorated definition (for the same function/method).

@overload-decorated definitions are for the benefit of the type checker only, since they will be overwritten by the non-@overload-decorated definition. The non-@overload-decorated definition, meanwhile, will be used at runtime but should be ignored by a type checker. At runtime, calling an @overload-decorated function directly will raise NotImplementedError.

An example of overload that gives a more precise type than can be expressed using a union or a type variable:

@overload
def process(response: None) -> None:
    ...
@overload
def process(response: int) -> tuple[int, str]:
    ...
@overload
def process(response: bytes) -> str:
    ...
def process(response):
    ...  # actual implementation goes here

See PEP 484 for more details and comparison with other typing semantics.

Changed in version 3.11: Overloaded functions can now be introspected at runtime using get_overloads().

typing.get_overloads(func)

Return a sequence of @overload-decorated definitions for func.

func is the function object for the implementation of the overloaded function. For example, given the definition of process in the documentation for @overload, get_overloads(process) will return a sequence of three function objects for the three defined overloads. If called on a function with no overloads, get_overloads() returns an empty sequence.

get_overloads() can be used for introspecting an overloaded function at runtime.

Added in version 3.11.

typing.clear_overloads()

Clear all registered overloads in the internal registry.

This can be used to reclaim the memory used by the registry.

Added in version 3.11.

@typing.final

Decorator to indicate final methods and final classes.

Decorating a method with @final indicates to a type checker that the method cannot be overridden in a subclass. Decorating a class with @final indicates that it cannot be subclassed.

For example:

class Base:
    @final
    def done(self) -> None:
        ...
class Sub(Base):
    def done(self) -> None:  # Error reported by type checker
        ...

@final
class Leaf:
    ...
class Other(Leaf):  # Error reported by type checker
    ...

There is no runtime checking of these properties. See PEP 591 for more details.

Added in version 3.8.

Changed in version 3.11: The decorator will now attempt to set a __final__ attribute to True on the decorated object. Thus, a check like if getattr(obj, "__final__", False) can be used at runtime to determine whether an object obj has been marked as final. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

@typing.no_type_check

Decorator to indicate that annotations are not type hints.

This works as a class or function decorator. With a class, it applies recursively to all methods and classes defined in that class (but not to methods defined in its superclasses or subclasses). Type checkers will ignore all annotations in a function or class with this decorator.

@no_type_check mutates the decorated object in place.

@typing.override

Decorator to indicate that a method in a subclass is intended to override a method or attribute in a superclass.

Type checkers should emit an error if a method decorated with @override does not, in fact, override anything. This helps prevent bugs that may occur when a base class is changed without an equivalent change to a child class.

For example:

class Base:
    def log_status(self) -> None:
        ...

class Sub(Base):
    @override
    def log_status(self) -> None:  # Okay: overrides Base.log_status
        ...

    @override
    def done(self) -> None:  # Error reported by type checker
        ...

There is no runtime checking of this property.

The decorator will attempt to set an __override__ attribute to True on the decorated object. Thus, a check like if getattr(obj, "__override__", False) can be used at runtime to determine whether an object obj has been marked as an override. If the decorated object does not support setting attributes, the decorator returns the object unchanged without raising an exception.

See PEP 698 for more details.

Added in version 3.12.

@typing.disjoint_base

Decorator to mark a class as a disjoint base.

Type checkers do not allow child classes of a disjoint base C to inherit from other disjoint bases that are not parent or child classes of C.

For example:

@disjoint_base
class Disjoint1: pass

@disjoint_base
class Disjoint2: pass

class Disjoint3(Disjoint1, Disjoint2): pass  # Type checker error

Type checkers can use knowledge of disjoint bases to detect unreachable code and determine when two types can overlap.

The corresponding runtime concept is a solid base (see Multiple inheritance). Classes that are solid bases at runtime can be marked with @disjoint_base in stub files. Users may also mark other classes as disjoint bases to indicate to type checkers that multiple inheritance with other disjoint bases should not be allowed.

Note that the concept of a solid base is a CPython implementation detail, and the exact set of standard library classes that are disjoint bases at runtime may change in future versions of Python.

Added in version 3.15.

@typing.type_check_only

Decorator to mark a class or function as unavailable at runtime.

This decorator is itself not available at runtime. It is mainly intended to mark classes that are defined in type stub files if an implementation returns an instance of a private class:

@type_check_only
class Response:  # private or not available at runtime
    code: int
    def get_header(self, name: str) -> str: ...

def fetch_response() -> Response: ...

Note that returning instances of private classes is not recommended. It is usually preferable to make such classes public.

Introspection helpers

typing.get_type_hints(obj, globalns=None, localns=None, include_extras=False, *, format=Format.VALUE)

Return a dictionary containing type hints for a function, method, module, class object, or other callable object.

This is often the same as annotationlib.get_annotations(), but this function makes the following changes to the annotations dictionary:

  • Forward references encoded as string literals or ForwardRef objects are handled by evaluating them in globalns, localns, and (where applicable) obj’s type parameter namespace. If globalns or localns is not given, appropriate namespace dictionaries are inferred from obj.

  • None is replaced with types.NoneType.

  • If @no_type_check has been applied to obj, an empty dictionary is returned.

  • If obj is a class C, the function returns a dictionary that merges annotations from C’s base classes with those on C directly. This is done by traversing C.__mro__ and iteratively combining annotations of each base class. Annotations on classes appearing earlier in the method resolution order always take precedence over annotations on classes appearing later in the method resolution order.

  • The function recursively replaces all occurrences of Annotated[T, ...], Required[T], NotRequired[T], and ReadOnly[T] with T, unless include_extras is set to True (see Annotated for more information).

Caution

This function may execute arbitrary code contained in annotations. See Security implications of introspecting annotations for more information.

Note

If Format.VALUE is used and any forward references in the annotations of obj are not resolvable, a NameError exception is raised. For example, this can happen with names imported under if TYPE_CHECKING. More generally, any kind of exception can be raised if an annotation contains invalid Python code.

Note

Calling get_type_hints() on an instance is not supported. To retrieve annotations for an instance, call get_type_hints() on the instance’s class instead (for example, get_type_hints(type(obj))).

Changed in version 3.9: Added include_extras parameter as part of PEP 593. See the documentation on Annotated for more information.

Changed in version 3.11: Previously, Optional[t] was added for function and method annotations if a default value equal to None was set. Now the annotation is returned unchanged.

Changed in version 3.14: Added the format parameter. See the documentation on annotationlib.get_annotations() for more information.

Changed in version 3.14: Calling get_type_hints() on instances is no longer supported. Some instances were accepted in earlier versions as an undocumented implementation detail.

typing.get_origin(tp)

Get the unsubscripted version of a type: for a typing object of the form X[Y, Z, ...] return X.

If X is a typing-module alias for a builtin or collections class, it will be normalized to the original class. If X is an instance of ParamSpecArgs or ParamSpecKwargs, return the underlying ParamSpec. Return None for unsupported objects.

Examples:

assert get_origin(str) is None
assert get_origin(Dict[str, int]) is dict
assert get_origin(Union[int, str]) is Union
assert get_origin(Annotated[str, "metadata"]) is Annotated
P = ParamSpec('P')
assert get_origin(P.args) is P
assert get_origin(P.kwargs) is P

Added in version 3.8.

typing.get_args(tp)

Get type arguments with all substitutions performed: for a typing object of the form X[Y, Z, ...] return (Y, Z, ...).

If X is a union or Literal contained in another generic type, the order of (Y, Z, ...) may be different from the order of the original arguments [Y, Z, ...] due to type caching. Return () for unsupported objects.

Examples:

assert get_args(int) == ()
assert get_args(Dict[int, str]) == (int, str)
assert get_args(Union[int, str]) == (int, str)

Added in version 3.8.

typing.get_protocol_members(tp)

Return the set of members defined in a Protocol.

>>> from typing import Protocol, get_protocol_members
>>> class P(Protocol):
...     def a(self) -> str: ...
...     b: int
>>> get_protocol_members(P) == frozenset({'a', 'b'})
True

Raise TypeError for arguments that are not Protocols.

Added in version 3.13.

typing.is_protocol(tp)

Determine if a type is a Protocol.

For example:

class P(Protocol):
    def a(self) -> str: ...
    b: int

assert is_protocol(P)
assert not is_protocol(int)

This function only returns true for Protocol classes, not for generic aliases of them:

class GenericP[T](Protocol):
    def a(self) -> T: ...
    b: int

assert not is_protocol(GenericP[int])

Added in version 3.13.

typing.is_typeddict(tp)

Check if a type is a TypedDict.

For example:

class Film(TypedDict):
    title: str
    year: int

assert is_typeddict(Film)
assert not is_typeddict(list | str)

# TypedDict is a factory for creating typed dicts,
# not a typed dict itself
assert not is_typeddict(TypedDict)

This function only returns true for TypedDict classes, not for generic aliases of them:

class GenericFilm[T](TypedDict):
    title: str
    year: T

assert not is_typeddict(GenericFilm[int])

Added in version 3.10.

class typing.ForwardRef

Class used for internal typing representation of string forward references.

For example, List["SomeClass"] is implicitly transformed into List[ForwardRef("SomeClass")]. ForwardRef should not be instantiated by a user, but may be used by introspection tools.

Note

PEP 585 generic types such as list["SomeClass"] will not be implicitly transformed into list[ForwardRef("SomeClass")] and thus will not automatically resolve to list[SomeClass].

Added in version 3.7.4.

Changed in version 3.14: This is now an alias for annotationlib.ForwardRef. Several undocumented behaviors of this class have been changed; for example, after a ForwardRef has been evaluated, the evaluated value is no longer cached.

typing.evaluate_forward_ref(forward_ref, *, owner=None, globals=None, locals=None, type_params=None, format=annotationlib.Format.VALUE)

Evaluate an annotationlib.ForwardRef as a type hint.

This is similar to calling annotationlib.ForwardRef.evaluate(), but unlike that method, evaluate_forward_ref() also recursively evaluates forward references nested within the type hint.

See the documentation for annotationlib.ForwardRef.evaluate() for the meaning of the owner, globals, locals, type_params, and format parameters.

Caution

This function may execute arbitrary code contained in annotations. See Security implications of introspecting annotations for more information.

Added in version 3.14.

typing.NoDefault

A sentinel object used to indicate that a type parameter has no default value. For example:

>>> T = TypeVar("T")
>>> T.__default__ is typing.NoDefault
True
>>> S = TypeVar("S", default=None)
>>> S.__default__ is None
True

Added in version 3.13.

typing.NoExtraItems

A sentinel object used to indicate that a TypedDict does not have the extra_items class argument.

>>> from typing import TypedDict, NoExtraItems
>>> class Point(TypedDict):
...     x: int
...     y: int
...
>>> Point.__extra_items__ is NoExtraItems
True

Constant

typing.TYPE_CHECKING

A special constant that is assumed to be True by static type checkers. It’s False at runtime.

A module which is expensive to import, and which only contain types used for typing annotations, can be safely imported inside an if TYPE_CHECKING: block. This prevents the module from actually being imported at runtime; annotations aren’t eagerly evaluated (see PEP 649) so using undefined symbols in annotations is harmless–as long as you don’t later examine them. Your static type analysis tool will set TYPE_CHECKING to True during static type analysis, which means the module will be imported and the types will be checked properly during such analysis.

Usage:

if TYPE_CHECKING:
    import expensive_mod

def fun(arg: expensive_mod.SomeType) -> None:
    local_var: expensive_mod.AnotherType = other_fun()

If you occasionally need to examine type annotations at runtime which may contain undefined symbols, use annotationlib.get_annotations() with a format parameter of annotationlib.Format.STRING or annotationlib.Format.FORWARDREF to safely retrieve the annotations without raising NameError.

Added in version 3.5.2.

Deprecated aliases

This module defines several deprecated aliases to pre-existing standard library classes. These were originally included in the typing module in order to support parameterizing these generic classes using []. However, the aliases became redundant in Python 3.9 when the corresponding pre-existing classes were enhanced to support [] (see PEP 585).

The redundant types are deprecated as of Python 3.9. However, while the aliases may be removed at some point, removal of these aliases is not currently planned. As such, no deprecation warnings are currently issued by the interpreter for these aliases.

If at some point it is decided to remove these deprecated aliases, a deprecation warning will be issued by the interpreter for at least two releases prior to removal. The aliases are guaranteed to remain in the typing module without deprecation warnings until at least Python 3.14.

Type checkers are encouraged to flag uses of the deprecated types if the program they are checking targets a minimum Python version of 3.9 or newer.

Aliases to built-in types

class typing.Dict(dict, MutableMapping[KT, VT])

Deprecated alias to dict.

Note that to annotate arguments, it is preferred to use an abstract collection type such as Mapping rather than to use dict or typing.Dict.

Deprecated since version 3.9: builtins.dict now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.List(list, MutableSequence[T])

Deprecated alias to list.

Note that to annotate arguments, it is preferred to use an abstract collection type such as Sequence or Iterable rather than to use list or typing.List.

Deprecated since version 3.9: builtins.list now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Set(set, MutableSet[T])

Deprecated alias to builtins.set.

Note that to annotate arguments, it is preferred to use an abstract collection type such as collections.abc.Set rather than to use set or typing.Set.

Deprecated since version 3.9: builtins.set now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.FrozenSet(frozenset, AbstractSet[T_co])

Deprecated alias to builtins.frozenset.

Deprecated since version 3.9: builtins.frozenset now supports subscripting ([]). See PEP 585 and Generic Alias Type.

typing.Tuple

Deprecated alias for tuple.

tuple and Tuple are special-cased in the type system; see Annotating tuples for more details.

Deprecated since version 3.9: builtins.tuple now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Type(Generic[CT_co])

Deprecated alias to type.

See The type of class objects for details on using type or typing.Type in type annotations.

Added in version 3.5.2.

Deprecated since version 3.9: builtins.type now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Aliases to types in collections

class typing.DefaultDict(collections.defaultdict, MutableMapping[KT, VT])

Deprecated alias to collections.defaultdict.

Added in version 3.5.2.

Deprecated since version 3.9: collections.defaultdict now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.OrderedDict(collections.OrderedDict, MutableMapping[KT, VT])

Deprecated alias to collections.OrderedDict.

Added in version 3.7.2.

Deprecated since version 3.9: collections.OrderedDict now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.ChainMap(collections.ChainMap, MutableMapping[KT, VT])

Deprecated alias to collections.ChainMap.

Added in version 3.6.1.

Deprecated since version 3.9: collections.ChainMap now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Counter(collections.Counter, Dict[T, int])

Deprecated alias to collections.Counter.

Added in version 3.6.1.

Deprecated since version 3.9: collections.Counter now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Deque(deque, MutableSequence[T])

Deprecated alias to collections.deque.

Added in version 3.6.1.

Deprecated since version 3.9: collections.deque now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Aliases to other concrete types

class typing.Pattern
class typing.Match

Deprecated aliases corresponding to the return types from re.compile() and re.search().

These types (and the corresponding functions) are generic over AnyStr. Pattern can be specialised as Pattern[str] or Pattern[bytes]; Match can be specialised as Match[str] or Match[bytes].

Deprecated since version 3.9: Classes Pattern and Match from re now support []. See PEP 585 and Generic Alias Type.

class typing.Text

Deprecated alias for str.

Text is provided to supply a forward compatible path for Python 2 code: in Python 2, Text is an alias for unicode.

Use Text to indicate that a value must contain a unicode string in a manner that is compatible with both Python 2 and Python 3:

def add_unicode_checkmark(text: Text) -> Text:
    return text + u' \u2713'

Added in version 3.5.2.

Deprecated since version 3.11: Python 2 is no longer supported, and most type checkers also no longer support type checking Python 2 code. Removal of the alias is not currently planned, but users are encouraged to use str instead of Text.

Aliases to container ABCs in collections.abc

class typing.AbstractSet(Collection[T_co])

Deprecated alias to collections.abc.Set.

Deprecated since version 3.9: collections.abc.Set now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.ByteString(Sequence[int])

Deprecated alias to collections.abc.ByteString.

Use isinstance(obj, collections.abc.Buffer) to test if obj implements the buffer protocol at runtime. For use in type annotations, either use Buffer or a union that explicitly specifies the types your code supports (e.g., bytes | bytearray | memoryview).

ByteString was originally intended to be an abstract class that would serve as a supertype of both bytes and bytearray. However, since the ABC never had any methods, knowing that an object was an instance of ByteString never actually told you anything useful about the object. Other common buffer types such as memoryview were also never understood as subtypes of ByteString (either at runtime or by static type checkers).

See PEP 688 for more details.

Deprecated since version 3.9, will be removed in version 3.17.

class typing.Collection(Sized, Iterable[T_co], Container[T_co])

Deprecated alias to collections.abc.Collection.

Added in version 3.6.

Deprecated since version 3.9: collections.abc.Collection now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Container(Generic[T_co])

Deprecated alias to collections.abc.Container.

Deprecated since version 3.9: collections.abc.Container now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.ItemsView(MappingView, AbstractSet[tuple[KT_co, VT_co]])

Deprecated alias to collections.abc.ItemsView.

Deprecated since version 3.9: collections.abc.ItemsView now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.KeysView(MappingView, AbstractSet[KT_co])

Deprecated alias to collections.abc.KeysView.

Deprecated since version 3.9: collections.abc.KeysView now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Mapping(Collection[KT], Generic[KT, VT_co])

Deprecated alias to collections.abc.Mapping.

Deprecated since version 3.9: collections.abc.Mapping now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.MappingView(Sized)

Deprecated alias to collections.abc.MappingView.

Deprecated since version 3.9: collections.abc.MappingView now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.MutableMapping(Mapping[KT, VT])

Deprecated alias to collections.abc.MutableMapping.

Deprecated since version 3.9: collections.abc.MutableMapping now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.MutableSequence(Sequence[T])

Deprecated alias to collections.abc.MutableSequence.

Deprecated since version 3.9: collections.abc.MutableSequence now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.MutableSet(AbstractSet[T])

Deprecated alias to collections.abc.MutableSet.

Deprecated since version 3.9: collections.abc.MutableSet now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Sequence(Reversible[T_co], Collection[T_co])

Deprecated alias to collections.abc.Sequence.

Deprecated since version 3.9: collections.abc.Sequence now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.ValuesView(MappingView, Collection[_VT_co])

Deprecated alias to collections.abc.ValuesView.

Deprecated since version 3.9: collections.abc.ValuesView now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Aliases to asynchronous ABCs in collections.abc

class typing.Coroutine(Awaitable[ReturnType], Generic[YieldType, SendType, ReturnType])

Deprecated alias to collections.abc.Coroutine.

See Annotating generators and coroutines for details on using collections.abc.Coroutine and typing.Coroutine in type annotations.

Added in version 3.5.3.

Deprecated since version 3.9: collections.abc.Coroutine now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.AsyncGenerator(AsyncIterator[YieldType], Generic[YieldType, SendType])

Deprecated alias to collections.abc.AsyncGenerator.

See Annotating generators and coroutines for details on using collections.abc.AsyncGenerator and typing.AsyncGenerator in type annotations.

Added in version 3.6.1.

Deprecated since version 3.9: collections.abc.AsyncGenerator now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Changed in version 3.13: The SendType parameter now has a default.

class typing.AsyncIterable(Generic[T_co])

Deprecated alias to collections.abc.AsyncIterable.

Added in version 3.5.2.

Deprecated since version 3.9: collections.abc.AsyncIterable now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.AsyncIterator(AsyncIterable[T_co])

Deprecated alias to collections.abc.AsyncIterator.

Added in version 3.5.2.

Deprecated since version 3.9: collections.abc.AsyncIterator now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Awaitable(Generic[T_co])

Deprecated alias to collections.abc.Awaitable.

Added in version 3.5.2.

Deprecated since version 3.9: collections.abc.Awaitable now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Aliases to other ABCs in collections.abc

class typing.Iterable(Generic[T_co])

Deprecated alias to collections.abc.Iterable.

Deprecated since version 3.9: collections.abc.Iterable now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Iterator(Iterable[T_co])

Deprecated alias to collections.abc.Iterator.

Deprecated since version 3.9: collections.abc.Iterator now supports subscripting ([]). See PEP 585 and Generic Alias Type.

typing.Callable

Deprecated alias to collections.abc.Callable.

See Annotating callable objects for details on how to use collections.abc.Callable and typing.Callable in type annotations.

Deprecated since version 3.9: collections.abc.Callable now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Changed in version 3.10: Callable now supports ParamSpec and Concatenate. See PEP 612 for more details.

class typing.Generator(Iterator[YieldType], Generic[YieldType, SendType, ReturnType])

Deprecated alias to collections.abc.Generator.

See Annotating generators and coroutines for details on using collections.abc.Generator and typing.Generator in type annotations.

Deprecated since version 3.9: collections.abc.Generator now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Changed in version 3.13: Default values for the send and return types were added.

class typing.Hashable

Deprecated alias to collections.abc.Hashable.

Deprecated since version 3.12: Use collections.abc.Hashable directly instead.

class typing.Reversible(Iterable[T_co])

Deprecated alias to collections.abc.Reversible.

Deprecated since version 3.9: collections.abc.Reversible now supports subscripting ([]). See PEP 585 and Generic Alias Type.

class typing.Sized

Deprecated alias to collections.abc.Sized.

Deprecated since version 3.12: Use collections.abc.Sized directly instead.

Aliases to contextlib ABCs

class typing.ContextManager(Generic[T_co, ExitT_co])

Deprecated alias to contextlib.AbstractContextManager.

The first type parameter, T_co, represents the type returned by the __enter__() method. The optional second type parameter, ExitT_co, which defaults to bool | None, represents the type returned by the __exit__() method.

Added in version 3.5.4.

Deprecated since version 3.9: contextlib.AbstractContextManager now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Changed in version 3.13: Added the optional second type parameter, ExitT_co.

class typing.AsyncContextManager(Generic[T_co, AExitT_co])

Deprecated alias to contextlib.AbstractAsyncContextManager.

The first type parameter, T_co, represents the type returned by the __aenter__() method. The optional second type parameter, AExitT_co, which defaults to bool | None, represents the type returned by the __aexit__() method.

Added in version 3.6.2.

Deprecated since version 3.9: contextlib.AbstractAsyncContextManager now supports subscripting ([]). See PEP 585 and Generic Alias Type.

Changed in version 3.13: Added the optional second type parameter, AExitT_co.

Deprecation Timeline of Major Features

Certain features in typing are deprecated and may be removed in a future version of Python. The following table summarizes major deprecations for your convenience. This is subject to change, and not all deprecations are listed.

Feature

Deprecated in

Projected removal

PEP/issue

typing versions of standard collections

3.9

Undecided (see Deprecated aliases for more information)

PEP 585

typing.ByteString

3.9

3.17

gh-91896

typing.Text

3.11

Undecided

gh-92332

typing.Hashable and typing.Sized

3.12

Undecided

gh-94309

typing.TypeAlias

3.12

Undecided

PEP 695

typing.AnyStr

3.13

3.18

gh-105578