PEP 8 & Pythonic Style
Code is read much more often than it is written. PEP 8 (Python Enhancement Proposal #8) is the definitive style guide for Python. Adhering to PEP 8 is not just about aesthetics; it’s about making your code accessible to the millions of other Python developers worldwide.
1. Key Structural Rules
Section titled “1. Key Structural Rules”Indentation & Spacing
Section titled “Indentation & Spacing”- Use 4 Spaces: Never use Tabs.
- Maximum Line Length: 79 characters for code, 72 for docstrings.
- Blank Lines:
- Two blank lines between top-level functions and classes.
- One blank line between methods inside a class.
Imports
Section titled “Imports”- Always put imports at the top of the file.
- Group them in this order:
- Standard library (e.g.,
os,sys). - Related third-party imports (e.g.,
django,requests). - Local application/library specific imports.
- Standard library (e.g.,
2. Naming Conventions
Section titled “2. Naming Conventions”| Type | Convention | Example |
|---|---|---|
| Variable | snake_case | user_id |
| Function | snake_case | calculate_total() |
| Class | PascalCase | UserAccount |
| Constant | UPPER_CASE | MAX_RETRIES |
| Package/Module | lowercase | utils |
3. The Zen of Python (PEP 20)
Section titled “3. The Zen of Python (PEP 20)”Beyond formatting, Python has a philosophy. You can read it by running import this in your terminal.
- Beautiful is better than ugly.
- Explicit is better than implicit.
- Simple is better than complex.
- Readability counts.
4. Modern Tooling: Ruff & Black
Section titled “4. Modern Tooling: Ruff & Black”In a professional setting, you don’t manually check for PEP 8. You use automation.
Ruff (The Linter)
Section titled “Ruff (The Linter)”Ruff is an extremely fast Python linter that checks for hundreds of style and logic errors.
pip install ruffruff check .Black (The Formatter)
Section titled “Black (The Formatter)”Black is an “uncompromising” code formatter. It takes your code and completely rewrites it to follow PEP 8 perfectly.
pip install blackblack my_script.py5. Summary Table
Section titled “5. Summary Table”| Feature | Guideline |
|---|---|
| Indentation | 4 Spaces (No Tabs). |
| Naming | snake_case for everything except Classes. |
| Quotes | Use single or double consistently (Black prefers double). |
| Whitespace | Avoid extra spaces inside parentheses or before commas. |