[Edu-sig] reviewing the context manager construct

Kirby Urner kurner at oreillyschool.com
Wed Mar 5 04:23:29 CET 2014


"""
Just for Fun

A quick sketch of a Context Manager construct.

A context manager is a type instance with an
__enter__ and __exit__ protocol, and designed
to work with a suite indented under a "with statement"

(cc) Kirby Urner, MIT License
O'Reilly School of Technology
Sebastopol, CA

With thanks to:
http://www.greatplay.net/uselessia/articles/e2-1000.html
"""

import decimal

class Haunted_Castle:
    """
    Shows the workflow of a context manager
    """
    def __enter__(self):
        print("Welcome to my world...")
        return self

    def __exit__(self, *stuff):
        print("Sorry to see you leave.  Come back again soon.")
        return True # handled exception

    def __repr__(self):
        return "Context manager object at: {}".format(id(self))

print("Before the context scope...")
with Haunted_Castle() as ctx:
    print("This is the suite within the scope of the context")
    print("Available from inside:", repr(ctx))
    raise Exception  # raise a fuss

print("After context...")

# and now that we have introduced the concept, here is one way
# to use it in practice:  temporarily boost the precision of
# Decimal type objects beyond a default of 28 decimal digits
# of precision

print("Do a big decimal computation...")
print("Default precision is:", decimal.getcontext().prec)

with decimal.localcontext() as ctx:
    ctx.prec = 500
    print("Precision in suite:", decimal.getcontext().prec)
    n = decimal.Decimal("1"+"0"*300) # 100000....0 (300 zeros)
    result = str((1 + 1/n) ** n)  # converges to Euler's e

print("Default precision is:", decimal.getcontext().prec)


# as in math.e but to more digits (1000)

euler = """\
2.
7182818284 5904523536 0287471352 6624977572
4709369995 9574966967 6277240766 3035354759
4571382178 5251664274 2746639193 2003059921
8174135966 2904357290 0334295260 5956307381
3232862794 3490763233 8298807531 9525101901
1573834187 9307021540 8914993488 4167509244
7614606680 8226480016 8477411853 7423454424
3710753907 7744992069 5517027618 3860626133
1384583000 7520449338 2656029760 6737113200
7093287091 2744374704 7230696977 2093101416
9283681902 5515108657 4637721112 5238978442
5056953696 7707854499 6996794686 4454905987
9316368892 3009879312 7736178215 4249992295
7635148220 8269895193 6680331825 2886939849
6465105820 9392398294 8879332036 2509443117
3012381970 6841614039 7019837679 3206832823
7646480429 5311802328 7825098194 5581530175
6717361332 0698112509 9618188159 3041690351
5988885193 4580727386 6738589422 8792284998
9208680582 5749279610 4841984443 6346324496
8487560233 6248270419 7862320900 2160990235
3043699418 4914631409 3431738143 6405462531
5209618369 0888707016 7683964243 7814059271
4563549061 3031072085 1038375051 0115747704
1718986106 8739696552 1267154688 9570350354\
"""

#remove spaces and newlines
euler = euler.replace(" ", "")
euler = euler.replace("\n", "")


# the result of the computation matches the published value to how many
digits?
c=0
while True:
    if euler[c] != result[c]:
        print("Same to {} places".format(c))
        break
    c += 1

#show significant digits
#print(euler[:c])
#print(result[:c])
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/edu-sig/attachments/20140304/8e84c950/attachment.html>


More information about the Edu-sig mailing list