Why follow conventions?

High quality Python code follows the conventions and best practices of the Python community outlined in PEP 8, which is the official style guide for Python code.

By following these conventions, you can ensure that your code is readable, maintainable, and consistent with the rest of the Python ecosystem.

TIP

The more your code follows the conventions, the better will be the output from LLMs when you use them to generate code.

How to ensure compliance with PEP 8

The easiest way to make sure your code is compliant with PEP 8 is by using a linter, and I strongly recommend using only ruff, it takes care of all the linting and formatting you need, and it’s fast.

Rules to follow

A linter doesn’t cover everything, there are some things that you need to be mindful of when writing or generating code, and these are the things that I consider the most important:

Naming conventions

Use snake_case for functions and variables, PascalCase for classes, and UPPER_SNAKE_CASE for constants.

Variables should be named for what they represent, while functions should be named for what they do or what they return. Avoid using abbreviations or acronyms unless they are widely known like id or url.

Type hints

Type hints signal to the reader what type of data is expected, they are very helpful in function signatures, so I recommend using them whenever possible.

def add(a: int, b: int) -> int:
    return a + b

Docstrings

Docstrings are the built-in way to document functions, classes, and modules in Python. They are very helpful to explain what a function does, what parameters it takes, and what it returns.

I recommend using the Google style for docstrings, but the most important thing is to be consistent with the style you choose.

def example() -> None:
    """Short description of the function.
 
    Longer description of the function, if necessary.
 
    Args:
        Describe the parameters of the function, if any.
 
    Returns:
        Describe the return value of the function, if any.
 
    Raises:
        Describe any exceptions that the function might raise, if any.
    """
    return

Don’t go overboard with docstrings, if a function is simple and self-explanatory, you don’t need to add a docstring for it, but if it’s complex or has some non-obvious behavior, a docstring can be very helpful.