3 ms·
Any list comprehension that is 1. Longer than ~80-120 characters 2. Can't be explained in 1 comment line Should be written as a nested for loop IMO.
by eugenekolo2 11y ago
Any list comprehension that is
1. Longer than ~80-120 characters
2. Can't be explained in 1 comment line
Should be written as a nested for loop IMO.
- gbog 11y agoYep. But even more: as any piece of code may have to grow and become more complex, any list comprehension except in throwable scripts should be rewritten as a for loop. Of I think 95% of the list comprehensions I wrote have been refactored to for loop by myself while debugging or extension the code later. So now I just never use them anymore, except for throwaway code.
- iofj 11y agoI don't get this. The list comprehension is much clearer for me. Do you have a mathematical background ? If you can easily think about sets I would expect the list comprehension to be far clearer. List comprehensions are much easier to read just because they're so much shorter : there's less to remember while reading it. This is an issue one always hits when you try to implement stuff that's more complex. List comprehensions help because they let you talk directly about more complex sets. They raise the level of abstraction. It's hard to get comfortable with but it really helps.
- gbog 11y agoYes, I happend to have a strong mathematical background. the difference in our points of view might be that I work on a code base with some ten million lines of code. Anything in there that is not purely flat stupid python, anything clever in fact, will be an annoyance some day. For example, someone started to use a "clever" `template.render(locals())` 5 years ago, and now we have no way to tell where the variables come from. Inside a list comprehension, how do you print? branch? comment? emit logs? (I know you "can" do that, but then it becomes a mess not worth it). Moreover, if in you 5 line long-list comprehension, if there is an error, will the traceback tell you where it is?
- iofj 11y agoI understand that list comprehensions are only for simple list construction. So you don't print or branch. Comment is pretty simple though. My perspective is that in large codebases I have far more trouble remembering function names and what they do than I ever have trouble decoding statements. So the increased code size, long functions and ... that comes from those long list construction statements and loops always seems to take more out of me than difficult list or dictionary comprehensions. Also there are very much fewer places for bugs to hide. There's also the additional argument that list comprehensions are more efficient because they don't actually construct the list. They generate iterators. It is not a huge difference like in Haskell but it definitely helps. And there are special cases where you have to use list comprehensions : infinite lists can work as a comprehension, yet the equivalent code to generate them is pages long.