Python — PEP 8
- Page Contents
- Page Summary
Overview
Python has specific styling and formatting conventions that are outlined in the PEP 8 style guide. These conventions help maintain consistency and readability in your code. Here's a list of some important Python styling and formatting rules from PEP 8:
- Indentation and Whitespace:
- Use 4 spaces per indentation level.
- Never mix tabs and spaces.
- Limit all lines to a maximum of 79 characters.
- Break lines after binary operators and open parentheses.
- Use blank lines to separate functions, classes, and logical sections.
- Imports:
- Import modules individually, avoiding wildcard imports (
from module import *
).
- Place imports at the top of the file.
- Separate imports into standard library imports, related third-party imports, and local application/library imports.
- Naming Conventions:
- Use lowercase with underscores for function and variable names (
my_function
, variable_name
).
- Use CapWords (CamelCase) for class names (
MyClass
).
- Use uppercase for constants (
MY_CONSTANT
).
- Whitespace in Expressions and Statements:
- Avoid extraneous whitespace.
- Do not put spaces around list indexes, function/method calls, or keyword arguments.
- Comments:
- Use comments to explain code that might not be obvious.
- Comments should be complete sentences and follow a capitalization and punctuation pattern.
- Avoid unnecessary comments and keep them up-to-date.
- Docstrings:
- Use docstrings to document modules, classes, methods, and functions.
- Follow the conventions in PEP 257 for docstring formatting.
- Operators:
- Use a single space around operators (
=
, +
, ``, etc.) for improved readability.
- Function and Method Definitions:
- Separate function definitions with two blank lines.
- Use descriptive function and method names.
- Use the
def
keyword, followed by a space, and follow with an opening parenthesis.
- Strings:
- Use single quotes for string literals whenever possible.
- Triple-quoted strings are used for docstrings and multiline strings.
- Formatting Strings (f-strings):
- Use f-strings to format strings with variables and expressions.
- Example:
name = "Alice"; age = 30; print(f"My name is {name} and I am {age} years old.")
Remember, adhering to consistent styling and formatting helps improve code readability and collaboration. For more detailed examples and explanations, you can refer to the PEP 8 style guide.