6.3.3 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:

getcontext( )
Return the current context for the active thread.

setcontext( c)
Set the current context for the active thread to c.

Beginning with Python 2.5, you can also use the with statement and the localcontext() function to temporarily change the active context.

localcontext( [c])
Return a context manager that will set the current context for the active thread to a copy of c 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. New in version 2.5.

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

    from __future__ import with_statement
    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

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

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

class 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 trapped 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.

class 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 creating 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 precision=28, 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 Context( prec=None, rounding=None, traps=None, flags=None, Emin=None, Emax=None, capitals=1)
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.

The prec field is a positive integer that sets the precision for arithmetic operations in the context.

The rounding option is one of:

The traps and flags fields list any signals to be set. Generally, new contexts should only set traps and leave the flags clear.

The Emin and Emax fields are integers specifying the outer limits allowable for exponents.

The capitals field is 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').

The Context class defines several general purpose methods as well as a large number of methods for doing arithmetic directly in a given context.

clear_flags( )
Resets all of the flags to 0.

copy( )
Return a duplicate of the context.

create_decimal( num)
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")

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

compare( x, y)
Compares values numerically.

Like __cmp__() but returns a decimal instance:

        a or b is a NaN ==> Decimal("NaN")
        a < b           ==> Decimal("-1")
        a == b          ==> Decimal("0")
        a > b           ==> Decimal("1")

divide( x, y)
Return x divided by y.

divmod( x, y)
Divides two numbers and returns the integer part of the result.

max( x, y)
Compare two values numerically and return the maximum.

If they are numerically equal then the left-hand operand is chosen as the result.

min( x, y)
Compare two values numerically and return the minimum.

If they are numerically equal then the left-hand operand is chosen as the result.

minus( x)
Minus corresponds to the unary prefix minus operator in Python.

multiply( x, y)
Return the product of x and y.

normalize( x)
Normalize reduces an operand to its simplest form.

Essentially a plus operation with all trailing zeros removed from the result.

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])
Return "x ** y" to the modulo if given.

The right-hand operand must be a whole number whose integer part (after any exponent has been applied) has no more than 9 digits and whose fractional part (if any) is all zeros before any rounding. The operand may be positive, negative, or zero; if negative, the absolute value of the power is used, and the left-hand operand is inverted (divided into 1) before use.

If the increased precision needed for the intermediate calculations exceeds the capabilities of the implementation then an InvalidOperation condition is signaled.

If, when raising to a negative power, an underflow occurs during the division into 1, the operation is not halted at that point but continues.

quantize( x, y)
Returns a value equal to x after rounding and having the exponent of y.

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.

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)
Computed the modulo as either a positive or negative value depending on which is closest to zero. For instance, "Decimal(10).remainder_near(6)" returns Decimal("-2") which is closer to zero than Decimal("4").

If both are equally close, the one chosen will have the same sign as self.

same_quantum( x, y)
Test whether x and y have the same exponent or whether both are NaN.

sqrt( x)
Return the square root of x to full precision.

subtract( x, y)
Return the difference between x and y.

to_eng_string( )
Convert to engineering-type string.

Engineering notation has an exponent which is a multiple of 3, so there are up to 3 digits left of the decimal place. For example, converts Decimal('123E+1') to Decimal("1.23E+3")

to_integral( x)
Rounds to the nearest integer without signaling Inexact or Rounded.

to_sci_string( x)
Converts a number to a string using scientific notation.

See About this document... for information on suggesting changes.