Saving up to 79 char line limit in Python with multiple indentation

I understand that in order to write good Python code, I have to keep my lines of no more than 79 characters.

This is normal in most cases, but if I have various nested for loops, and if the statements themselves are nested in a class, I can easily find that I have 5 or 6 indents (i.e. 20-24 characters if I indent 4 spaces at a time) before I start. Then the limit of 79 characters becomes quite complicated. I know of various tricks, such as implicit continuation in parentheses, and using parentheses to concatenate long strings, but even then it is a bit difficult.

So, what will the gurus advise you?

Indenting 2 spaces instead of 4 will help, but is this considered a good style? Not sure if this will help make my code more readable, and I note that PEP8 says to use 4 spaces.

If I find that I have several levels of indentation, maybe I sign that I write bad code? And if so, are there any useful tips or tricks for ways to avoid too much nesting?

Am I trying to stick to the 79 character recommendation first?

Or do I just need to get used to the many sayings, broken into several lines?

Thanks Adam

+7
python coding-style
source share
1 answer

1. Loops

You can often use itertools.product or itertools.combinations to convert nested loops into a single loop.

If the loops are independent, use product . For example, these nested loops:

 for x in range(3): for y in range(5): for z in range(7): print((x, y, z)) 

will become a single loop:

 from itertools import product for x, y, z in product(range(3), range(5), range(7)): print((x, y, z)) 

When loop indices should be different, you can use combinations . For example, these nested loops:

 for start in range(length - 1): for end in range(start + 1, length): print((start, end)) 

will become a single loop:

 from itertools import combinations for start, end in combinations(range(length), 2): print((start, end)) 

See here for a real-time example using product and here for an example using combinations .

2. Terms

When you have many if , you can often reorganize the code to preserve the indentation steps and at the same time make the code more understandable. The main idea is to eliminate the errors first, and then the cases in which you can return immediately, so that the main part of the condition should not be indented so far (or, in many cases, in general). For example, if you have code:

 if x >= 0: if x == 0: return 1 else: # ... main body here ... return result else: raise ValueError("Negative values not supported: {!r}".format(x)) 

Then you can reorganize the code as follows:

 if x < 0: raise ValueError("Negative values not supported: {!r}".format(x)) if x == 0: return 1 # ... main body here ... return result 

which will save you two levels of indentation for the main body.

+6
source share

All Articles