Welcome, guest | Sign In | My Account | Store | Cart

The function printexpr() takes a Python expression, and prints it's value, and the filename and line from which printexpr() is called. This is useful when debugging programs. The code is based off a couple of Usenet postings that I merged into one.

Python, 28 lines
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
from sys import exc_info, stderr
import types, string
from traceback import *

def _caller_symbols():
    try:
        raise StandardError
    except StandardError:
        t = exc_info()[2].tb_frame
        return (t.f_back.f_back.f_globals,t.f_back.f_back.f_locals)


def printexpr(expr_string):
    """ printexpr(expr) - 
        print the value of the expression, along with linenumber and filename.
    """

    stack = extract_stack ( )[-2:][0]
    actualCall = stack[3]
    left = string.find ( actualCall, '(' )
    right = string.rfind ( actualCall, ')' )
    caller_globals,caller_locals = _caller_symbols()
    expr = eval(expr_string,caller_globals,caller_locals)
    varType = type( expr )
    stderr.write("%s:%d>  %s == %s  (%s)\n" % (
        stack[0], stack[1],
        string.strip( actualCall[left+1:right] )[1:-1],
        repr(expr), str(varType)[7:-2]))

2 comments

Michael Chermside 23 years, 1 month ago  # | flag

Useful little gadget. Michael Chermside

Olivier Dagenais 23 years ago  # | flag

Could use some sample output. I recognize some of the code I used in writing one of the Usenet posting the author mentions, however it lacks the sample output comments like I had in my code. I guess I'll just post my version and duke it out that way... :) Olivier Dagenais