Manuel Graune wrote:
Manuel Graune <manuel.gra...@koeln.de> writes:
The use-case is acually fairly simple. The point is to use a python
source-file as subsitute for scrap-paper (with the opportunity to
edit what is already written and without illegible handwriting).
The output should  1) show manually selected python code and comments
(whatever I think is important), 2) show selected results (final and
intermediate) and 3) *not* show python code that for someone only
interested in the calculation and the results (and probably not
knowing python) would just be "noise" (e. g. "import"-statements,
actual "print()"-functions, etc.).

How about a decorator that turns your function into an object with the results? Your code would then look like this:

8<----------------------------------------------
#! /usr/bin/python3
from sp import ScratchPad
from math import pi as PI

@ScratchPad
def code1():
    d1= 3.0
    A1= d1**2 * PI / 4.0

print("Area of Circle 1:\t", code1.A1)

@ScratchPad
def code2():
    d2= 5.0
    A2= d2**2 * PI / 4.0

print("Area of Circle 2:\t", code2.A2)

Sum_Of_Areas= code1.A1 + code2.A2
print("Sum of areas:\t", Sum_Of_Areas)

8<----------------------------------------------

and the printout like so:

Python 3.1 (r31:73574, Jun 26 2009, 20:21:35) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import sp_test

d1= 3.0
A1= d1**2 * PI / 4.0

Area of Circle 1:        7.06858347058

d2= 5.0
A2= d2**2 * PI / 4.0

Area of Circle 2:        19.6349540849
Sum of areas:    26.7035375555

Here's the code for the decorator:

8<--------------------------------------------------------------
import inspect

class PropertyObj():
    """lookup using . notation"""

def ScratchPad(func):
    source = inspect.getsourcelines(func)[0][2:]
    lead_space = 0
    for char in source[0]:
        if char == ' ':
            lead_space += 1
        else:
            break
    source = ''.join([line[lead_space:] for line in source])
    print('\n' + source)
    intermed_result = {}
    final_result = PropertyObj()
    exec(source, func.__globals__, intermed_result)
    for key, value in intermed_result.items():
        setattr(final_result, key, value)
    return final_result
8<--------------------------------------------------------------

Hope this helps!

~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to