Tips for debugging list comprehensions?

In Haskell I using something similar to:

def trcPV(prompt, value):
    print ("%s%s" % (prompt, str(value)))
    return value

xs = trcPV("xs=", [x for x in range(0,100) if trcPV("check=",(trcPV("x=",x) % 15) in [0,3,5])])

If it's complicated enough that it's not obvious at first glance, unpack it into multiple steps and/or for loops. It's clearly too complicated, and making it more explicit is the easiest way to go about debugging it. Added bonus: you can now step through with the debugger or add print statements!


It depends on the list comprehension. You can move a part of the code to another function. This should be a clean solution which is more easy to debug.

Example:

[1.0 / i for i in [0, 2, 5, 10]]

Can be divided into

[f(i) for i in [0, 2, 5, 10]] 

and a function

def f(i):         
    return 1.0 / i  

When you do the debugging you will find out it will crash because of a “division-by-zero” error at f for the value of i = 0.


I use a function that just prints and returns a value at the same time:

from pprint import pprint

def debug(msg, item):
    print('\n' + msg + ':')
    pprint(item)
    return item

It's very handy for debugging any part of a list/dict comprehension:

new_lines = [
    debug('CUR UPDATED LINE', change(line))
    for line
    in debug('ALL LINES', get_lines_from_file(filename))
    if debug('CUR LINE EMPTY?', not_empty(line))
    ]