Thursday, May 29, 2014

Another simple Python debugging function

By Vasudev Ram


I had written this little Python function for debugging, a while ago.

Then I forgot about it. Was reminded of it today by seeing by this Reddit Python post:

debug_print - A tiny package(file) for printf style debugging.

That author's debug_print function uses the Python eval function, which my function also does. That is what reminded me of my function. Here it is:
# eval_debug.py
# A program to implement and test ed(), a debugging function.
# Author: Vasudev Ram - http://www.dancingbison.com

def ed(item):
    print item + ": |" + repr(eval(item)) + "|"

# Integer
intt = 42
ed('intt')

# Floating point
flot = 1.0
ed('flot')

# String
strng = "foo"
ed('strng')

# Boolean
boolan = False
ed('boolan')

# Tuple
tupl = (1, "two", True)
ed('tupl')

# List
lis = [ 3, 4, 5 ]
ed('lis')

# Dict
dic = { "a": "apple", "b": "banana" }
ed('dic')

# Set
sett = set({ 2, 3, 5, 7, 9 })
ed('sett')

# Function
def funk():
    pass
ed('funk')

# Generator
def g():
    yield 1
gen = g()
ed('gen')

# Class
class klas:
    pass
ed('klas')

# EOF
The purpose of the ed() debugging function is simple: to be able to display a variable and its value without having to pass the name twice in the print statement, once with the variable name in quotes (to print its name) and once with the variable name not in quotes (to print its value). The function currently only works for some cases, though (*).

Here is the output of running python eval_debug.py :
$ python eval_debug.py
intt: |42|
flot: |1.0|
strng: |'foo'|
boolan: |False|
tupl: |(1, 'two', True)|
lis: |[3, 4, 5]|
dic: |{'a': 'apple', 'b': 'banana'}|
sett: |set([9, 2, 3, 5, 7])|
funk: ||
gen: ||
klas: ||

(*) So the debugging function has a bug :-)


Also check out my earlier post on the same topic, Python debugging:

A simple Python debugging function

And see other posts about debugging on my blog.


- Vasudev Ram - Dancing Bison Enterprises

Contact Page

No comments: