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

Naming Conventions

Formatting

def example_function(arg1, arg2):
    if arg1 and arg2:
        print("Hello, world!")

Imports

import os
import sys

from datetime import datetime
from flask import Flask, render_template

from my_project import utils

Whitespace and Indentation

Comments

# This function adds two numbers together
def add_numbers(a, b):
    return a + b

Documentation

def my_function(param1, param2):
    """
    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

try:
    result = my_function()
except ValueError as e:
    print(f"An error occurred: {e}")

Function and Method Arguments

def process_data(data, threshold=10):
    # Function implementation
    pass

String Formatting

name = "John"
age = 30
print(f"My name is {name} and I am {age} years old.")

Virtual Environments

# Create a virtual environment
python -m venv venv

# Activate the virtual environment
source venv/bin/activate  # On Unix or MacOS
venv\Scripts\activate  # On Windows

These guidelines aim to ensure code consistency and readability, fostering a collaborative and efficient development environment. Happy coding in Python!