An Introduction to the Art of Computer Programming Using Python in the Age of Generative AI

XVI. Best Practices and Coding Conventions

Beautiful is better than ugly.
Tim Peters, Zen of Python

Introduction

When you begin programming, the primary challenge is writing code that a computer can execute without errors. But as applications grow larger, a new challenge emerges: writing code that people—including your future self—can understand and maintain. Achieving clarity, readability, and consistency is crucial for collaboration and reducing defects. Well-crafted code is not only functional but also elegant and maintainable, ensuring it can evolve over time.

Consistent Naming Conventions

Using clear, descriptive names for variables, functions, methods, and classes is one of the simplest yet most impactful ways to make your code more readable. Good naming conventions reduce cognitive load by clearly communicating the purpose of each piece of code. Follow consistent styles, such as using snake_case for functions and variables, PascalCase or CapWords for classes, and UPPER_CASE for constants.


# Good naming example
class Book:
    def __init__(self, title, author, isbn):
        self.title = title
        self.author = author
        self.isbn = isbn

# Bad naming example
class b:
    def __init__(self, t, a, i):
        self.t = t
        self.a = a
        self.i = i
        

Code Formatting and PEP 8

Python’s official style guide, PEP 8, offers guidelines for consistent code formatting such as indentation, line lengths, import order, and whitespace usage. Adhering to these standards makes your code appear clean and helps other Python developers read, understand, and review it more easily. You can use automated tools like flake8, black, or autopep8 to check and enforce PEP 8 rules.


# PEP 8 compliant code
class Book:
    def __init__(self, title, author, isbn):
        self.title = title
        self.author = author
        self.isbn = isbn

# Non-compliant code
class book: def __init__(self, title,author,isbn): self.title=title;self.author=author;self.isbn=isbn
        

Writing Docstrings

Well-written docstrings describe the purpose, parameters, and return values of functions, methods, and classes. This makes your code self-documenting and easier to maintain, especially for larger projects or open-source collaborations. Python docstrings often follow the reStructuredText or Google style conventions, which can be automatically parsed by documentation tools like Sphinx or pdoc.


class Book:
    """
    A class representing a book in a bookstore.

    Attributes:
        title (str): The title of the book.
        author (str): The author of the book.
        isbn (str): The ISBN number of the book.
    """
    def __init__(self, title, author, isbn):
        """
        The constructor for the Book class.

        Parameters:
            title (str): The title of the book.
            author (str): The author of the book.
            isbn (str): The ISBN number of the book.
        """
        self.title = title
        self.author = author
        self.isbn = isbn
        

Avoiding Global Variables

Global variables can lead to unintended side effects and unpredictable behavior, especially in larger programs. By scoping variables to classes, functions, or modules, you ensure that behavior is more predictable, debugging is less painful, and your design is more modular.


# Bad practice: Using a global variable
inventory = []

class BookStore:
    def add_book(self, book):
        global inventory
        inventory.append(book)

# Good practice: Avoiding global variables
class BookStore:
    def __init__(self):
        self.inventory = []

    def add_book(self, book):
        self.inventory.append(book)
        

Using Version Control Systems

For any project beyond trivial size, a version control system such as Git is essential. It allows you to track changes, revert to previous states when issues arise, and collaborate seamlessly with other developers. Practicing well-structured commits, clear commit messages, and frequent check-ins can significantly streamline your workflow.

Additional Best Practices

These practices will help you create more stable, comprehensible, and maintainable applications—ultimately making your job as a developer far easier in the long run.

Back to Home