CodyKochmann
5/10/2017 - 9:07 PM

this is a small demo that we used to get a feel for how context managers work in python, apparently they work more like macros instead of fu

this is a small demo that we used to get a feel for how context managers work in python, apparently they work more like macros instead of functions in terms of scope

class pre_post():
    def __init__(self, pre, post,*args):
        self.pre = pre
        self.post = post
        #print('init',args)

    def __enter__(self, *args):
        ##print('enter',args)
        #print(inp,inp,inp,inp)
        self.pre()

    def __exit__(self, *args):
        ##print('exit',args)
        self.post()
        #print(inp,inp,inp)

import math

from random import random

def preconditions():
    assert isinstance(inp,(int,float)), 'need int or float, got: {}'.format(inp)
    assert inp>0, 'inp is too small'

def postconditions():
    assert isinstance(inp, float)

inp = random()

with pre_post(pre=preconditions,post=postconditions):
    inp = math.log(inp)

print(inp)