Python Coding Standards: Basic Rules of PEP and PEP 8 (Style Guide)

Python is a language designed with a focus on “readability.” To ensure that code looks consistent regardless of who writes it, the Python community follows a standard coding convention called “PEP 8”.

This article explains what PEP is and the main rules defined in PEP 8.


目次

What is PEP?

PEP stands for Python Enhancement Proposal.

These are official documents used to propose and manage new features, specification changes, and development processes for the Python language.

Each PEP is numbered and serves a specific role:

  • PEP 1: PEP Purpose and Guidelines
  • PEP 8: Style Guide for Python Code
  • PEP 20: The Zen of Python (Design Philosophy)
  • PEP 257: Docstring Conventions

What is PEP 8?

Among the many PEPs, PEP 8 is the most frequently referenced. It is a rulebook regarding the visual style of how Python code should be written.

The standard library code is written according to these rules, and Python developers around the world are generally recommended to follow them.


Major Rules of PEP 8

There are many rules in PEP 8, but here are the most important ones to keep in mind daily.

1. Indentation

  • Use 4 spaces.
  • Do not use tab characters.
# Good Example
def calculate_total(price, tax):
    if price > 0:
        return price * (1 + tax)

# Bad Example (Using 2 spaces or tabs)
def calculate_total(price, tax):
  if price > 0:
   return price * (1 + tax)

2. Line Length

  • Limit all lines to a maximum of 79 characters (72 characters for docstrings and comments).
  • If a line is too long, use parentheses () to wrap it and align the indentation.
# Good Example
total_value = (item_price_a + item_price_b + item_price_c +
               item_price_d + item_price_e)

3. Use of Whitespace

  • Put a space after commas ,, colons :, and semicolons ;. Do not put a space before them.
  • Put one space around binary operators (=, +, -, *, ==, etc.).
# Good Example
x = 10
y = x + 5
numbers = [1, 2, 3]

# Bad Example
x=10
y = x+5
numbers = [1,2,3]

However, do not use spaces around the = sign when specifying keyword arguments in functions.

# Good Example
def connect(host="localhost", port=8080):
    pass

# Bad Example
def connect(host = "localhost", port = 8080):
    pass

4. Naming Conventions

There are rules for how to name variables, functions, and classes.

TargetRuleExample
VariablesLowercase + Underscore (Snake Case)user_name, item_count
FunctionsLowercase + Underscore (Snake Case)calculate_tax, get_data
MethodsLowercase + Underscore (Snake Case)update_record
ClassesCapitalize first letter of words (Camel Case / CapWords)UserAccount, HttpRequest
ConstantsAll Uppercase + UnderscoreMAX_CONNECTIONS, DEFAULT_TIMEOUT

5. Import Order

Imports at the top of the file should be grouped in the following order, with a blank line between groups:

  1. Standard Library (e.g., os, sys)
  2. Third-Party Library (e.g., pandas, requests)
  3. Local Application/Library (Your own modules)
import os
import sys

import requests

import my_module

Using Automated Formatters

Following all these rules manually can be difficult. In modern Python development, it is common to use tools to automatically format code to comply with PEP 8.

  • Black: Currently the most popular formatter. It rewrites code into a unified, uncompromising style that complies with PEP 8.
  • autopep8: A tool that automatically fixes PEP 8 violations.
  • Flake8: A tool that checks for PEP 8 violations (does not fix them).

Summary

  • PEP is a document proposing Python specifications, and PEP 8 is the “Coding Style Guide.”
  • Basic rules include 4 spaces for indentation, snake_case for variables/functions, and CamelCase for classes.
  • Following these rules makes your code readable and maintainable for everyone.
  • It is recommended to use tools (Formatters) to automatically enforce these standards.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次