Python Code Guidelines
Aug 08, 2021
Dec 20, 2023
Adhering to these standards will help maintain consistency, readability, and best practices across our Python projects.
Table of Contents
- Table of Contents
- Naming Conventions
- Formatting
- Imports
- Whitespace and Indentation
- Comments
- Documentation
- Error Handling
- Function and Method Arguments
- String Formatting
- Virtual Environments
Naming Conventions
- Use
snake_case
for function and variable names. - Use
CamelCase
for class names. - Use
UPPER_CASE
for constants.
Formatting
- Use four spaces for indentation.
- Limit lines to 79 characters.
- Prefer spaces over tabs.
Imports
- Import modules in separate lines.
- Use explicit imports over wildcard imports.
- Group imports in the following order: standard library, third-party libraries, local modules.
Whitespace and Indentation
- Avoid trailing whitespaces.
- Use blank lines to separate functions, classes, and blocks of code logically.
Comments
- Write comments to explain complex pieces of code or provide additional context.
- Avoid unnecessary comments that simply restate the code.
# This function adds two numbers together
return +
Documentation
- Document all public functions, classes, and modules using docstrings.
- Use triple double-quotes for multiline docstrings.
"""
This function does something awesome.
Args:
param1 (int): The first parameter.
param2 (str): The second parameter.
Returns:
bool: True if successful, False otherwise.
"""
# Function implementation here
pass
Error Handling
- Use
try
,except
blocks for handling exceptions. - Avoid using a bare
except
clause; be specific about the exceptions you catch.
=
Function and Method Arguments
- Use meaningful names for function and method arguments.
- Avoid using mutable types (e.g., lists) as default argument values.
# Function implementation
pass
String Formatting
- Prefer f-strings for string formatting.
=
= 30
Virtual Environments
- Use virtual environments to manage dependencies for each project.
# Create a virtual environment
# Activate the virtual environment
These guidelines aim to ensure code consistency and readability, fostering a collaborative and efficient development environment. Happy coding in Python!