Re:Specific ways to write better Python (2017)
by dragonwriter on Saturday June 20, 2020 @07:08PM
(#23588204)
I think #7 would be clearer if it said “Use list comprehensions instead of map or filter where the latter would use lambda expressions, and in place of the combination of map and filter”. Map and filter where you are applying a function (including a function-returning expression) that doesn't require a lambda are, IMO, cleaner and avoiding an extra lambda or map/filter combo is explictly the basis of #7 (see #7.i., 7.ii.) I don't think this is bad writing, the author expects you to read the subpoints, but if you were to present the major points independently...
#8 is a little unclear as to which expressions it is counting (particularly, whether it counts the return expression, which I don't think it intends to.) I think it's referring to the two total “for” and “if” clauses, so either two “for” or one of each as the preferred limit, which seems to me to be a sensible guideline.
It think both #7 and #8, even with the additional clarification, need so to be considered in combination with #4: they set the rules as to what constitutes a complicated expression—either with comprehensions or map/filter/etc.—that calls for factoring part of it out into a helper function or named subexpression to avoid overly complex, code-golfy one-liners.
> Is it even true that comprehensions are faster than reduce and map?
While I'd love to see “accumulator comprehension” syntax* added to Python, in real current python comprehensions aren’t generally an alternative to reduce.
#8 is a little unclear as to which expressions it is counting (particularly, whether it counts the return expression, which I don't think it intends to.) I think it's referring to the two total “for” and “if” clauses, so either two “for” or one of each as the preferred limit, which seems to me to be a sensible guideline.
It think both #7 and #8, even with the additional clarification, need so to be considered in combination with #4: they set the rules as to what constitutes a complicated expression—either with comprehensions or map/filter/etc.—that calls for factoring part of it out into a helper function or named subexpression to avoid overly complex, code-golfy one-liners.
> Is it even true that comprehensions are faster than reduce and map?
While I'd love to see “accumulator comprehension” syntax* added to Python, in real current python comprehensions aren’t generally an alternative to reduce.
* something like: