Aquesta és una revisió antiga del document —-
3.1 PEP 8 – Introduction
As mentioned earlier, PEP 8 is a document that provides coding conventions (code style guide) for Python code.
PEP 8 is considered one of the most important PEPs and a must-read for every professional Python programmer, as it helps to make the code more consistent, more readable, and more efficient.
Even though some programming projects may adopt their own style guidelines (in which case such project-specific guidelines may be favored over the conventions provided for by PEP 8, especially in the case of any conflicts, or backwards-compatibility issues), the PEP 8 best practices are still highly recommended reading, as they help you to better understand the philosophy behind Python and become a more aware and proficient programmer.
PEP 8 is still evolving as new, additional conventions are being identified and included in it, and at the same time some old conventions are being identified as obsolete and discouraged from being followed.
The Hobgoblin of Little Minds
”A foolish consistency is the hobgoblin of little minds.” This is a quote from Ralph Waldo Emerson’s essay “Self-Reliance” where Emerson urges readers to be consistent in their beliefs and practices. In our case, it means we must not forget about one simple but important observation: our code will be read much more often than it will be written.
On the one hand, consistency is a crucial factor that determines code readability. On the other hand, inconsistency with PEP 8 may at times be a better option. If the style guides are not applicable to your project, it may be better to ignore them and decide for yourself what is best. As PEP 8 says:
A style guide is about consistency. Consistency with this style guide is important. Consistency within a project is more important. Consistency within one module or function is the most important. […] However, know when to be inconsistent […]. When in doubt, use your best judgement.
When should you ignore some specific PEP 8 guidelines (or at least consider doing so)?
- If following them will mean that you break backwards compatibility.
- If following them will have a negative effect on code readability.
- If following them will cause inconsistency with the rest of the code. (However, this may be a good opportunity to rewrite the code and make it PEP 8 compliant.)
- If there is no good reason for making the code PEP 8 compliant, or the code predates PEP 8.
PEP 8 is intended to improve code readability and “make it consistent across the wide spectrum of Python code.” Keeping your Python code compliant with PEP 8 is, therefore, a good idea, but you should never blindly adhere to these recommendations. You should always use your best judgement.