PythonIntroduction to PythonPython fundamentals
What is PEP 8, and why is it important?
Question 15 of 20 · Updated
On this page
- 1. Why is PEP 8 important?
- 2. Indentation: use four spaces per level
- 3. Maximum line length and wrapping
- 4. Naming conventions in Python
- 5. Whitespace around operators and punctuation
- 6. Blank lines and organisation
- 7. Imports: grouping and placement
- 8. Comments and docstrings
- 9. Programming recommendations beyond formatting
- 10. PEP 8 vs formatters, linters and type checkers
- 11. Practical example: a readable order calculation
- 12. Common mistakes when applying PEP 8
- Treating every recommendation as a syntax rule
- Renaming an established public interface without considering compatibility
- Assuming a formatter fixes logic
- Making style-only changes alongside unrelated feature work
- Enforcing one style everywhere regardless of the project
- 13. Frequently asked questions
- Is PEP 8 mandatory in Python?
- Is PEP 8 the same as PEP 257?
- Is PEP 8 the same as the Zen of Python?
- Does PEP 8 improve Python performance?
- Should I use 79 or 88 characters per line?
- 14. Interview-ready answer
- Key takeaways
- Official references
PEP 8 is Python's style guide for writing readable, consistent Python code. It provides recommendations for indentation, naming conventions, line length, imports, whitespace, comments and other aspects of code layout.
PEP stands for Python Enhancement Proposal. PEP 8, titled *Style Guide for Python Code*, was originally written for the Python standard library and has become a widely used reference for Python projects. Its central idea is that code is read much more often than it is written, so consistency and readability matter.
PEP 8 is a style guide, not a separate programming language specification. Valid Python code can violate PEP 8 and still execute successfully. Conversely, beautifully formatted code can contain logic errors. Good engineering requires readable code, correct behaviour and meaningful tests.
1. Why is PEP 8 important?#
Consider two functions that compute the same result.
Less readable:
PYTHONdef total(p,q): return p*q print(total(25,4))
More readable:
PYTHONdef calculate_total(price, quantity): return price * quantity print(calculate_total(25, 4))
Both programs print:
100The second example is easier to understand because the function and parameters describe their intent, indentation follows a consistent convention, operators have appropriate whitespace, and the function definition is visually separated from its use.
PEP 8 helps developers:
- Review code more quickly and understand unfamiliar modules.
- Collaborate without repeatedly debating basic formatting choices.
- Reduce distracting formatting changes in version control.
- Maintain code consistently as applications grow.
- Recognise common patterns and communicate intent through names and layout.
It does not automatically improve execution speed or guarantee correctness. Its primary benefit is human readability and maintainability.
2. Indentation: use four spaces per level#
Python uses indentation to define blocks. PEP 8 recommends four spaces per indentation level.
PYTHONitems = ["pen", "notebook", "pencil"] for item in items: print(item)
Output:
pen
notebook
pencilThe indented print statement belongs to the loop body. Removing that indentation would change the structure or cause a syntax error.
Spaces are preferred for indentation. Tabs should be used only to remain consistent with code already indented using tabs; Python can reject inconsistent mixing of tabs and spaces with a TabError.
Configure your editor to insert spaces when you press Tab. This is distinct from inserting literal tab characters into the source file.
For a long statement continued within parentheses, brackets or braces, use alignment or a hanging indent that clearly distinguishes the continuation from surrounding code. Parenthesised continuation is generally preferable to explicit backslash continuation.
3. Maximum line length and wrapping#
PEP 8 recommends:
- A maximum of 79 characters for ordinary code lines.
- A maximum of 72 characters for flowing text in comments and docstrings.
A team may agree to increase the code-line limit to 99 characters, while retaining the 72-character recommendation for comments and docstrings. Individual projects may adopt other conventions; for example, Black's default line length is 88 characters. That is a formatter configuration, not PEP 8's default recommendation.
When a long calculation is easier to read across several lines, use implicit line joining:
PYTHONsubtotal = 100 tax = 18 shipping = 5 total = ( subtotal + tax + shipping ) print(total)
Output:
123PEP 8 permits line breaks before or after binary operators when the convention is consistent locally, and suggests breaking before operators for new code where appropriate. The parentheses above make the calculation's structure explicit and avoid a trailing backslash.
Do not split a string or URL mechanically just to meet a line-length limit if doing so would damage readability or correctness. Choose a sensible structure and follow the project's agreed rules.
4. Naming conventions in Python#
Good names explain what a program represents or does. PEP 8 specifies several widely used naming conventions.
| Identifier type | Recommended convention | Example |
|---|---|---|
| Variable | Lowercase with underscores | total_price |
| Function | Lowercase with underscores | calculate_total |
| Method | Lowercase with underscores | add_item |
| Class | CapWords (PascalCase) | ShoppingCart |
| Module | Short lowercase name; underscores if useful | order_utils |
| Package | Short lowercase name; underscores discouraged | payments |
| Constant | Uppercase with underscores | MAX_RETRIES |
| Non-public attribute or method | Leading single underscore | _connection |
| Instance method first parameter | self | self.items |
| Class method first parameter | cls | cls.create |
For example:
PYTHONclass ShoppingCart: def __init__(self): self.items = [] def add_item(self, item): self.items.append(item) cart = ShoppingCart() cart.add_item("book") print(cart.items)
Output:
['book']The class uses CapWords, methods and attributes use descriptive lowercase names, and instance methods use self.
Constants are conventionally written in uppercase, but Python does not enforce immutability of a variable simply because its name is uppercase. A leading underscore indicates a non-public interface by convention, not a security boundary. A double leading underscore in a class triggers name mangling in applicable identifiers; it should not be confused with genuine access control.
Avoid creating custom double-leading-and-trailing-underscore names such as special methods unless they are documented Python interfaces. Also avoid single-letter names l, O and I because they can be difficult to distinguish from digits in some fonts. Short names such as i may still be reasonable for small, conventional loop indices.
5. Whitespace around operators and punctuation#
Use whitespace to make expressions visually understandable.
| Prefer | Avoid |
|---|---|
| total = price * quantity | total=price*quantity |
| print(a, b) | print(a,b) |
| items[0] | items[ 0 ] |
| calculate_total(25, 4) | calculate_total (25, 4) |
| result = func(x) | result = func( x ) |
Ordinary assignments and many binary operators use spaces around them. For expressions with different operator priorities, PEP 8 also allows grouping higher-priority operations more tightly when that improves readability. Unary operators, slices, keyword arguments and parameter defaults have their own spacing conventions.
Do not put spaces around the equals sign in an unannotated default parameter or keyword argument.
PYTHONdef calculate_discount(price, *, rate=0.10): return price * (1 - rate) print(f"{calculate_discount(200, rate=0.25):.2f}")
Output:
150.00When a parameter has both a type annotation and a default, use spaces around the equals sign, as in the signature def calculate_discount(price: float, *, rate: float = 0.10):.
Do not mechanically add or remove whitespace everywhere. For example, the spacing rules for slice colons depend on the surrounding expression, and the minus sign in a negative literal is not a binary subtraction operator.
6. Blank lines and organisation#
PEP 8 recommends two blank lines around top-level function and class definitions, and one blank line between method definitions within a class.
Within a function, use blank lines sparingly to separate logical stages. For instance, validation, computation and returning a result may be distinct steps. Excessive blank lines can make a simple function harder to follow, while too few can obscure its structure.
The aim is a clear visual hierarchy rather than filling every available line with code.
7. Imports: grouping and placement#
Imports normally appear near the top of a module, after any module docstring and before module-level globals and constants. Group imports in this order:
- Standard library imports.
- Related third-party imports.
- Local application or library imports.
Separate the groups with a blank line. Prefer separate import statements for different modules rather than combining unrelated imports on a single line. Importing several names from the same module with a from-import statement is acceptable.
A small standard-library example:
PYTHONfrom math import sqrt print(sqrt(81))
Output:
9.0A larger application's import groups might contain pathlib and logging from the standard library, an HTTP client from a third-party package, and a local configuration module. Keep the dependency groups distinct.
Prefer absolute imports where practical; explicit relative imports are also acceptable within packages. Avoid wildcard imports in normal application code because they make it unclear which names are available and where they originated.
PEP 8's placement guidance has intentional exceptions. A function may import a module locally for a specific reason, such as deferring optional dependencies or avoiding a carefully understood circular import. Do not rearrange imports in a way that changes required initialisation behaviour.
8. Comments and docstrings#
A comment should explain information that is not obvious from the code, such as why an operation is necessary, a business rule, or an implementation constraint. Keep comments accurate as the implementation changes.
A useful comment explains why a retry is safe or why a particular threshold exists, rather than merely restating that an assignment assigns a value.
Docstrings describe the purpose and interface of modules, functions, classes and methods. PEP 8 refers to PEP 257 for docstring conventions.
PYTHONdef calculate_total(prices): """Return the sum of all prices.""" return sum(prices) print(calculate_total([10, 20, 30]))
Output:
60This docstring is a short summary of the function's behaviour. Public interfaces with complex arguments, return values or failure modes benefit from fuller documentation using the project's chosen docstring style.
For inline comments, PEP 8 recommends at least two spaces before the comment marker and a space after it. Avoid unnecessary inline comments and do not use comments to conceal unclear naming or overly complicated logic.
9. Programming recommendations beyond formatting#
PEP 8 includes recommendations about common Python programming idioms, not only whitespace.
For singleton values such as None, use identity comparisons (is or is not) rather than equality comparisons.
PYTHONdef find_discount(customer): if customer is None: return 0 if customer["is_member"]: return 10 return 0 print(find_discount({"is_member": True})) print(find_discount(None))
Output:
10
0The first branch checks explicitly whether the customer is missing. Using a general falsiness check instead would also match values such as an empty dictionary, which is a different condition.
Additional recommendations:
- Use isinstance for type checks when subclass support is appropriate.
- Prefer a direct truth-value check for Boolean conditions instead of comparing a Boolean expression to True or False.
- Catch specific exceptions instead of catching every exception indiscriminately.
- Use a context manager when managing resources that support one.
- Keep function return behaviour consistent where possible.
- Avoid assigning a lambda expression directly to a name when an ordinary def function is clearer.
These guidelines must be applied with attention to semantics. For example, changing an equality comparison to an identity comparison for ordinary integers or strings is incorrect. Formatting and refactoring should not alter program behaviour unexpectedly.
10. PEP 8 vs formatters, linters and type checkers#
PEP 8 is a written set of recommendations. Tools can help enforce or automate a subset of those recommendations.
| Tool or concept | Primary purpose |
|---|---|
| PEP 8 | Describe recommended Python code style |
| Formatter (Black, Ruff formatter) | Automatically rewrite code layout according to configured formatting rules |
| Linter (Ruff, pycodestyle) | Detect configured style violations and, depending on the tool, other potential issues |
| Static type checker (mypy, Pyright) | Analyse type consistency using type annotations and inferred types |
| Test suite | Check whether program behaviour matches expectations |
A formatter does not know whether a variable name accurately communicates business meaning. A linter does not prove that every program result is correct. A type checker does not replace runtime tests or validation of external input.
A typical team chooses a formatter and linter, agrees on project settings, and runs both in continuous integration. For a project where Ruff is already installed, examples of check-only commands are:
BASHruff check . ruff format --check .
The first checks configured lint rules. The second checks whether files match Ruff's formatting rules without rewriting them. The results depend on the installed tool version, configuration and source files. These optional tool commands require Ruff; they are not Python built-ins, and were not exercised in the local example tests.
Avoid enabling two formatters with conflicting rules on the same files. Store shared configuration in version control, often in pyproject.toml, and document intentional deviations.
11. Practical example: a readable order calculation#
This example combines descriptive naming, four-space indentation, a docstring, a keyword-only argument, blank lines and a clear entry point.
Save it as order_total.py:
PYTHONdef calculate_order_total(prices, *, tax_rate=0.18): """Return the order total including tax.""" subtotal = sum(prices) return subtotal * (1 + tax_rate) def main(): prices = [100, 50, 25] total = calculate_order_total(prices) print(f"Order total: {total:.2f}") if __name__ == "__main__": main()
Run it with your chosen Python 3 interpreter:
BASHpython order_total.py
Expected output:
Order total: 206.50The calculation is separated from printing. Another module or a test can import calculate_order_total without automatically running main. The function name explains the purpose, and the keyword-only argument makes the tax-rate choice explicit.
For n prices, sum performs O(n) additions, and this function uses O(1) auxiliary space under the usual fixed-size numeric cost model. The input list is supplied by the caller. PEP 8 does not change that complexity.
This is an instructional example, not a complete financial application. Real billing systems should use a suitable decimal or integer-minor-unit representation, explicit currency and rounding rules, and validated inputs.
12. Common mistakes when applying PEP 8#
Treating every recommendation as a syntax rule#
A line over 79 characters can still be valid Python. PEP 8 recommendations and Python's grammatical requirements are different. Incorrect indentation can be a syntax problem; an agreed line-length exception is a style decision.
Renaming an established public interface without considering compatibility#
If existing users import a function by its original name, changing that name merely to improve style can break their applications. Preserve compatibility or introduce changes through an appropriate deprecation process.
Assuming a formatter fixes logic#
A formatter may rewrite the layout of a conditional expression, but it cannot establish that the business condition itself is correct. Keep tests and code review.
Making style-only changes alongside unrelated feature work#
Large formatting diffs can hide behavioural changes and complicate review. Where practical, isolate broad reformatting changes into their own commits.
Enforcing one style everywhere regardless of the project#
PEP 8 explicitly prioritises consistency within a project and recognises situations where a recommendation should not be followed. Follow documented project conventions when they differ, especially in an established codebase.
13. Frequently asked questions#
Is PEP 8 mandatory in Python?#
No. PEP 8 is a style guide. Teams can make parts of it mandatory in their own projects through lint rules, review guidelines or CI checks.
Is PEP 8 the same as PEP 257?#
No. PEP 8 addresses general Python code style. PEP 257 specifically describes docstring conventions. They complement one another.
Is PEP 8 the same as the Zen of Python?#
No. PEP 8 gives concrete style recommendations. PEP 20, the Zen of Python, describes broader design principles such as readability, simplicity and explicitness.
Does PEP 8 improve Python performance?#
Not directly. Whitespace and naming conventions normally target maintainability rather than algorithmic performance. Some programming recommendations affect behaviour, so changes should be checked for correctness.
Should I use 79 or 88 characters per line?#
79 is PEP 8's default recommendation for code. 88 is Black's default. Follow your team's agreed configuration; consistency is more useful than switching between limits within the same codebase.
14. Interview-ready answer#
PEP 8 is the official Python style guide, originally written for the standard library, that recommends readable and consistent code. It covers four-space indentation, a default 79-character code-line limit, descriptive snake_case names for functions and variables, CapWords for classes, uppercase constants, import organisation, whitespace and comments. Following it makes collaboration, code review and maintenance easier. It is not a syntax requirement or a guarantee of correctness. Teams often use formatters and linters to automate selected conventions, while respecting project-specific rules and preserving backward compatibility.
Key takeaways#
- PEP 8 promotes readability and consistency, not cosmetic uniformity at any cost.
- Use descriptive names, four spaces per indentation level and clear expression layout.
- Organise imports, comments and functions so readers can understand intent quickly.
- Use automated tools to support a shared style, but retain human review and tests.
- Do not break an existing public API or change semantics merely to satisfy a style preference.
Official references#
- PEP 8 — Style Guide for Python Code
- PEP 257 — Docstring Conventions
- PEP 20 — The Zen of Python
- Python Language Reference — Lexical Analysis
- Ruff documentation
- Black documentation — The Black code style
Verification note: All ten runnable Python examples were executed locally on Python 3.13.5 and their outputs checked. References are provided from established knowledge; live documentation was not checked.
References
- 1.PEP 8 — Style Guide for Python Codepeps.python.org
- 2.PEP 257 — Docstring Conventionspeps.python.org
- 3.PEP 20 — The Zen of Pythonpeps.python.org
- 4.Python Language Reference — Lexical Analysisdocs.python.org
- 5.Ruff documentationdocs.astral.sh
- 6.Black documentation — The Black code styleblack.readthedocs.io
Related questions
Explore other topics:Forward Deployed EngineeringMachine LearningSQL: Structured Query LanguageAI System Design