Python list comprehensions are nice, but near impossible to debug. You guys have any good tips / tools for debugging them?
List comprehensions are great because they require less lines of code, are easier to comprehend, and are generally faster than a for loop.
Because of differences in how Python implements for loops and list comprehension, list comprehensions are almost always faster than for loops when performing operations.
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.
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.
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))
]
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With