This guide covers Python code conventions adopted from PEP 8. Following these conventions will help you write clean, consistent, and readable Python code.
- Naming Conventions
- 1.1 Variables
- 1.2 Functions
- 1.3 Classes
- 1.4 Constants
- 1.5 Modules and Packages
- Indentation and Spacing
- 2.1 Indentation
- 2.2 Spacing After Commas
- 2.3 Spacing Around Operators
- 2.4 Line Length
- Comments
- 3.1 Single-Line Comments
- 3.2 Multi-Line Comments
- 3.3 Docstrings
- Imports
- 4.1 Import Placement
- 4.2 Import Style
- Functions and Classes
- 5.1 Functions and Methods
- 5.2 Classes
- Exception Handling
- Other Best Practices
- 7.1 Avoid Code Duplication
- 7.2 Use Appropriate Data Types
- 7.3 Use Type Annotations
- Code Formatting
- 8.1 Separate Code Blocks
- 8.2 Clear Control Structures
- Data Structures and Control Flow
- Conclusion
- Use lowercase letters with words separated by underscores (
snake_case
).- Example:
my_variable
,user_age
- Example:
- Functions should use
snake_case
(lowercase letters with underscores).- Example:
calculate_total()
,get_user_input()
- Example:
- Use
PascalCase
(each word starts with an uppercase letter).- Example:
CustomerAccount
,UserProfile
- Example:
- Use uppercase letters with words separated by underscores (
UPPER_SNAKE_CASE
).- Example:
MAX_VALUE
,PI
- Example:
- Module names should be lowercase, with underscores used if necessary (
snake_case
).- Example:
math_utilities
,data_processor
- Example:
- Use 4 spaces per indentation level. Do not use tabs.
- Add a space after each comma in arguments or list elements.
- Example:
my_function(1, 2, 3)
,list_of_values = [1, 2, 3]
- Example:
- Add one space around operators like
+
,=
,-
,*
, etc.- Example:
x = 5 + 10
,result = a * b
- Example:
- Limit all lines to 79 characters for code, and 72 characters for docstrings.
- If a line is too long, break it into multiple lines using parentheses or backslashes (
\
).
- Use single-line comments for short explanations. Start with a capital letter and include a space after the
#
.- Example:
# This is a single-line comment
- Example:
- Use block comments for longer explanations, with a
#
at the beginning of each line.- Example:
# This is a multi-line comment # explaining the function below
- Example:
- Use docstrings to document modules, classes, functions, or methods. Enclose docstrings in triple quotes (
"""
).- Example:
def add(a, b): """ Adds two numbers and returns the result. Parameters: a (int): The first number b (int): The second number Returns: int: The sum of the two numbers """ return a + b
- Example:
- All imports should be placed at the top of the file, before other code.
- Group imports into three categories:
- Standard library imports
- Third-party imports
- Local application imports
- Prefer
import module
overfrom module import *
to avoid polluting the namespace.
- Functions and methods should be named descriptively using
snake_case
. - Functions should have docstrings describing what they do.
- Class names should use
PascalCase
. - Classes should also have docstrings that explain their purpose.
-
Use
try
andexcept
blocks for error handling. -
Avoid using
except:
without specifying the error type. -
If catching a specific type of error, mention the error type in the
except
clause.- Example:
try: value = int(input("Enter a number: ")) except ValueError: print("Invalid input.")
- Example:
- Avoid code duplication by breaking down the code into reusable functions or classes.
- Use the correct data types to improve code clarity and avoid errors.
- If using Python 3.5 or higher, consider using type annotations to describe the types of parameters and return values.
- Example:
def add_numbers(a: int, b: int) -> int: return a + b
- Example:
- Use blank lines to separate different code blocks, improving readability.
- Use control structures such as
if
,for
,while
clearly and avoid writing overly complicated code.
- Choose appropriate data structures for the task. Use
list
,tuple
,set
, ordict
as needed. - Consider using
list comprehensions
orgenerator expressions
for concise and efficient code.
Following these conventions will help you write cleaner, more consistent, and maintainable Python code. Make sure to always adhere to these standards for better collaboration in software development.