Indent comprehensions in Python

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)
]
  1. Align the indentation of the parentheses on the outside of the inclusion notation, and indent one of the contents.
  2. Divide by element, for clause, (for clause) ..., (if clause).

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

Indent comprehensions in Python
Quadtree in Python --2
Python in optimization
Metaprogramming in Python
Python 3.3 in Anaconda
Geocoding in python
SendKeys in Python
Meta-analysis in Python
Unittest in python
Epoch in Python
Discord in Python
Sudoku in Python
nCr in python
N-Gram in Python
Programming in python
Plink in Python
Constant in python
Lifegame in Python.
FizzBuzz in Python
Sqlite in python
StepAIC in Python
N-gram in python
LINE-Bot [0] in Python
Csv in python
Disassemble in Python
Reflection in Python
Constant in python
nCr in Python.
format in python
Scons in Python3
Puyo Puyo in python
python in virtualenv
PPAP in Python
Quad-tree in Python
Reflection in Python
Chemistry in Python
Hashable in python
DirectLiNGAM in Python
LiNGAM in Python
Flatten in python
flatten in python
Sorted list in Python
Daily AtCoder # 36 in Python
Daily AtCoder # 2 in Python
Implement Enigma in python
Daily AtCoder # 32 in Python
Daily AtCoder # 18 in Python
Singleton pattern in Python
File operations in Python
Key input in Python
Daily AtCoder # 33 in Python
Logistic distribution in Python
Daily AtCoder # 7 in Python
LU decomposition in Python
One liner in Python
Daily AtCoder # 24 in Python
case class in python
RNN implementation in python
Daily AtCoder # 8 in Python
File processing in Python
Elasticsearch Reindex in Python