[Python-Dev] Example for PEP 343

Michael Chermside mcherm at mcherm.com
Tue May 17 23:42:06 CEST 2005


In PEP 343 Guido writes:
>    8. Another use for this feature is the Decimal context.  It's left
>       as an exercise for the reader.  (Mail it to me if you'd like to
>       see it here.)

Here are two such examples. Pick your favorite for the PEP.

PS: Writing this helped convince me that allowing the use of generators
instead of classes with the "do_template" decorator is quite nice in
practice, even though it gets confusing (for beginners anyhow) if you
start to think about it too much.

-- Michael Chermside

# ===== SAMPLE #1: increasing precision during a sub-calculation =====

import decimal

@do_template
def with_extra_precision(places=2):
    "Performs nested computation with extra digits of precision."
    decimal.getcontext().prec += 2
    yield None
    decimal.getcontext().prec -= 2



# == SAMPLE USE of #1 ==
# (Sample taken from the Python Library Reference)

def sin(x):
    "Return the sine of x as measured in radians."
    do with_extra_precision():
        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
        return +s

# ===== SAMPLE #2: insisting on exact calculations only =====

import decimal

@do_template
def assert_exact():
    "Raises exception if nested computation is not exact."
    ctx = decimal.getcontext()
    was_inexact = ctx.traps[decimal.Inexact]
    ctx.traps[decimal.Inexact] = True
    yield None
    ctx.traps[decimal.Inexact] = was_inexact


# == SAMPLE USE of #2 ==

# Lemma 2 ensures us that each fraction will divide evenly
do assert_exact():
    total = decimal.Decimal(0)
    for n, d in zip(numerators, denominators):
        total += n / d



More information about the Python-Dev mailing list