Python's comprehensions are useful, but if you try to do something a little more complicated, you end up with multi-step nesting. And nesting significantly reduces readability. For this reason, I think that many people will rewrite it in block notation when the nesting hierarchy becomes deeper.
However, if you set rules and indent, nesting will not compromise readability. For example, it looks like this:
itemList = [
(item.name, item.price)
for item in record.items()
for purchase in purchases
if purchase.campaignName in {
campaign.name
for campaign in camapigns
} and purchase.date > datetime.date.today() - datetime.timedelta(days = 7)
]
It may take some getting used to, but once you get used to it, it will be much easier to read than block notation. Considering that the block notation increases unnecessary variables for saving lists and reduces readability, the merit of being able to nest unlimitedly in the comprehension notation is quite large.
Recommended Posts