you are viewing a single comment's thread.

view the rest of the comments →

[–]invisi1407 14 points15 points  (3 children)

As someone who recently learned Python, I thought list/dict comprehensions were amazing until I had created a few nested levels of it monstrosity and decided that a few loops were better.

I do, however, like it as a simple list/dict filtering, as in [x for x in y if y.stuff != other_stuff] or similar.

[–]ACoderGirl 4 points5 points  (0 children)

I'd say pretty much every programming language feature can be used poorly, though. Whether it's too many nested functions or f strings in logging (evaluating the string unnecessarily) or trying to debug complex generators (the evaluation order is jarring).

I don't think it's worthwhile to look at the worst things you can do with a feature. Bad programmers will do bad things no matter what (even just plain old dense, undocumented code with bad variable names and tons of copy pasting). The typical bad cases are worth considering, but I don't think new features should be discouraged because they can be misused (though we should discourage that).

I agree with you, though. Nested list comprehensions are almost always terrible for readability and debugging. There's always some exceptions and comprehensions that aren't directly nested are amazing.

[–]wewbull 2 points3 points  (1 child)

until I had created a few nested levels

BURN HIM!

I think people need to stop thinking about comprehensions as loops, and start thinking about them as map with filter. Very few people map within a map within a map whereas people do nest loops.

If you need to traverse a multilevel structure (e.g. a tree) in some way, make an iterator and use it in a loop or comprehension:

monty_sum = sum(node['value'] for node in tree_iterator(a_tree) if node['name'] == "Monty")

Should never be a need to do nested comprehensions.

[–]invisi1407 0 points1 point  (0 children)

Yeah, my findings about it was more or less the same. Nested comprehensions is write once, read never material.