views:

90

answers:

5

Python list comprehensions are nice, but near impossible to debug. You guys have any good tips / tools for debugging them?

+4  A: 

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!

Steven Schlansker
+1: pythonic usage of list comprehensions are when the code actually gets clearer and easier to read
nosklo
+2  A: 

tip: Use list comprehension for simple tasks (1 or 2 levels). Otherwise, making it explicit is better for readability.

ghostdog74
A: 

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])])
ony
A: 

Use a debugger like pdb to walk through or break the list comprehension into a full for loop.

Mike Graham
A: 

Haskell list comprehensions at least can be (and that is what compilers do) rewritten in terms of map, concat and filter.

So this Haskell example:

[ x*x | x<-[1..25], even x]

Works out as:

map (\x-> x*x) (filter (even) [1..25])

I expect similar identities would continue to hold for Python, so similar decomposition should yield equivalent code in Python as well. The equivalent code should prove easier to debug (and run about as efficiently).