Photo by Priscilla Du Preez on Unsplash
If you have coded in Python for a while then you must have come across PEP 8 style guide. If not this article should give you some important tips to remember while writing your next Python code.
However, there isn’t a hard-fast rule that you must follow everything recommended as it, you need to use your best judgment when you are in doubt.
1. Indentation
Use 4 spaces per indentation level.
Spaces are preferred to tabs. Tabs should be used when it is already indented with tabs. Python dismisses the mixing of those two.
2. Enigmatic lambdas
Anonymous functions help you create inline Python code which is easily readable but eventually, they can become confusing if there’s more than one on a line or in an expression.
When using lambda in the middle of a line of code, the 80-character rule could easily be violated.
Lambda functions are also not reusable and also cannot be given a meaningful name that would express what’s going on.
3. Inarticulate Comprehension
A most beautiful feature of Python I like is list comprehension. But if any time comprehensions are nested it would be really painful to understand what’s happening:
If the comprehension is complex then it might be worth putting it into a separate function.
4. 80 Character rule
Every line of your Python code should be a maximum of 79 characters and for docstrings or comments, the line length should be limited to 72 characters.
The main purpose of this rule is to limit the required editor window width to have several files open side by side which might be helpful in code review.
Although you can prefer a longer line length, the Python standard library is conventional and requires the above-mentioned character rule.
5. To ante or post is the question
The preferable way according to PEP 8 is to break before binary operators and it follows the mathematicians and their publisher's way to display formulas which results in more readable code.
6. Trailing commas
Trailing commas are mandatory when making a tuple of one element. The pattern to remember is to put each value on a line by itself and add close parenthesis “)” on the next line.
Conclusion
Again to conclude these guidelines are from the PEP 8 official guide however there isn’t any hard fast rule to follow all of them, make your judgment about using them in your next Python code.
Reference
PEP 8 -- Style Guide for Python Code
The official home of the Python Programming Languagepython.org