Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Tips for debugging list comprehensions?

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

like image 972
andylei Avatar asked Mar 29 '10 03:03

andylei


People also ask

Are list comprehensions good practice?

List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop.

Do list comprehensions run faster?

Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.

What are list comprehensions used for?

List comprehension is an elegant way to define and create lists based on existing lists. List comprehension is generally more compact and faster than normal functions and loops for creating list. However, we should avoid writing very long list comprehensions in one line to ensure that code is user-friendly.

What are list comprehensions in Python?

A Python list comprehension consists of brackets containing the expression, which is executed for each element along with the for loop to iterate over each element in the Python list. Python List comprehension provides a much more short syntax for creating a new list based on the values of an existing list.


1 Answers

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))
    ]
like image 100
Rotareti Avatar answered Oct 05 '22 22:10

Rotareti