Coding conventions

suggest change

Adhering to shared coding conventions makes code more readable, maintainable, and idiomatic ("Pythonic"). In the Python ecosystem, style conventions are governed primarily by PEP 8 (Style Guide for Python Code) and guided by the philosophical tenets of the Zen of Python (PEP 20).


1. The Zen of Python (PEP 20)

To view Python's guiding principles, run import this in an interactive Python shell:

import this

Key highlights:


2. Naming Conventions

Python adheres to strict naming conventions to differentiate classes, functions, constants, and internal variables:

Construct Convention Example
Modules / Packages Short lowercase, underscores only if needed os, http_server
Classes / Exceptions PascalCase (CapWords) UserAccount, NotFoundError
Functions & Methods snake_case (lowercase with underscores) calculate_tax(), get_by_id()
Variables & Attributes snake_case user_name, total_count
Constants ALL_CAPS_SNAKE_CASE MAX_RETRY_COUNT, DEFAULT_TIMEOUT
Protected Internals Single leading underscore _internal_cache, _helper()
Private (Name Mangles) Double leading underscore __private_attr
Special / Magic Dunder (double leading and trailing underscore) __init__, __repr__, __enter__
MAX_CONNECTIONS = 100  # Constant

class DatabasePool:  # PascalCase class
    def __init__(self, dsn: str):
        self.dsn = dsn                  # Public attribute
        self._active_connections = 0    # Protected attribute

    def acquire_connection(self):       # snake_case method
        self._active_connections += 1
        return f"Conn from {self.dsn}"

3. Code Layout and Formatting

Indentation

Line Length

Blank Lines


4. Organizing Imports

Imports should always be placed at the top of the file, immediately following any module docstrings and comments, and grouped into three distinct sections separated by a single blank line:

"""Module for processing financial invoices."""

# 1. Standard library imports
import os
import sys
from datetime import datetime, timezone

# 2. Related third-party library imports
import requests
from pydantic import BaseModel

# 3. Local application / library specific imports
from myproject.database import get_db_session
from myproject.models import Invoice

Import Rules


5. Whitespace in Expressions and Statements

Avoid Extraneous Whitespace

# Correct:
spam(ham[1], {eggs: 2})
foo = (0,)
if x == 4: print(x, y); x, y = y, x

# Wrong:
spam( ham[ 1 ], { eggs: 2 } )
foo = (0, )
if x == 4 : print(x , y) ; x , y = y , x

Operators and Assignments


6. Idiomatic Comparisons

Comparison to None

Always use is or is not when testing for None. Never use equality operators (== or !=):

# Correct
if value is None:
    print("Value is not set")

if value is not None:
    print("Value exists")

# Wrong
if value == None:
    pass

Truth Value Testing

Take advantage of Python's built-in truthiness for empty sequences (strings, lists, tuples, dicts):

items = []

# Correct (Pythonic)
if not items:
    print("List is empty")

# Unnecessary / Verbose
if len(items) == 0:
    print("List is empty")

7. Modern Tooling and Automated Enforcement

Modern Python workflows use automated tools in CI and pre-commit hooks to format and lint code automatically:

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:



Table Of Contents