← Back to list

Writing Clean Python Code with PEP 8

PEP 8 is the official style guide for Python code. It provides conventions for writing readable and consistent code. Here are some key…

Allwin Raju · 2025-02-10 09:36 · 0 claps · 2.0 min read paywalled
#python #python-programming #python-pep8 #coding-standards-python #allwin-raju
Open on Medium ↗
Wiki topics: 💻 · Programming 👗 · Fashion

Writing Clean Python Code with PEP 8

Photo by James Harrison on Unsplash

Photo by James Harrison on Unsplash

PEP 8 is the official style guide for Python code. It provides conventions for writing readable and consistent code. Here are some key points:

Read for free: https://allwin-raju.medium.com/writing-clean-python-code-with-pep-8-f97b25e29843?sk=860ba3de96c8e18998622b822018f58f

1. Indentation

Use 4 spaces per indentation level (no tabs).

def my_function():
    print("Hello, world!")

2. Maximum Line Length

Limit lines to 79 characters (72 for docstrings/comments).

# Good
message = "This is a short line."

# Bad (too long)
message = "This is a very long line that exceeds the recommended character limit of 79."

3. Blank Lines

  • Use two blank lines to separate top-level functions and classes.
  • Use one blank line inside functions to separate logic.
def first_function():
    print("First function")

def second_function():
    print("Second function")

class MyClass:

    def method_one(self):
        print("Method one")

    def method_two(self):
        print("Method two")

4. Imports

Imports should be at the top of the file. Follow this order:

  1. Standard library imports
  2. Third-party imports
  3. Local application imports
import os
import sys

import numpy as np

from my_module import my_function

5. Spaces

  • No spaces inside parentheses, brackets, or braces.
  • Use a single space around operators and after commas.
# Good
x = (1, 2, 3)
y = x[1]
result = x + y

# Bad
x = ( 1, 2, 3 )
y=x[ 1 ]
result=x+y

6. Naming Conventions

  • Variables and functions: snake_case
  • Constants: UPPER_CASE
  • Classes: PascalCase
  • Private variables: _single_leading_underscore
  • “Magic” methods: __double_leading_underscore__
import os

# Constants
MAX_USERS = 100

class User:
    """A class to represent a user with a username and age."""

    def __init__(self, username, age):
        """Initialize a User object with a username and age."""
        self.username = username
        self.age = age
        self._id = self.__generate_id()

    def __generate_id(self):
        """Generate a unique user ID based on the username and age."""
        return f"{self.username.lower()}_{self.age}"

    def get_user_info(self):
        """Return user details as a dictionary."""
        return {"username": self.username, "age": self.age, "id": self._id}

    @staticmethod
    def is_valid_age(age):
        """Check if the provided age is a valid positive integer."""
        return isinstance(age, int) and age > 0

    def __str__(self):
        """Return a string representation of the user."""
        return f"User(username='{self.username}', age={self.age})"

# Example usage
if __name__ == "__main__":
    user = User("Alice", 25)
    print(user)
    print(user.get_user_info())
    print(User.is_valid_age(30))

7. Docstrings

Use triple quotes for functions, classes, and modules.

def add(a, b):
    """Return the sum of two numbers."""
    return a + b

8. Avoid Trailing Whitespace

No unnecessary spaces at the end of lines.

# Good
name = "Alice"

# Bad (extra spaces at the end)
name = "Alice"

9. Use is for None Comparisons

# Good
if my_var is None:
    pass

# Bad
if my_var == None:  # Don't do this
    pass

10. Avoid Using Mutable Defaults in Function Arguments

# Bad
def my_function(data=[]):  
    pass  

# Good
def my_function(data=None):
    if data is None:
        data = []

Final Thoughts

By following PEP 8, your Python code becomes more readable, maintainable, and professional. Whether you’re writing a simple script or contributing to a large project, adhering to PEP 8 ensures consistency across your codebase.


메타데이터
post_id
f97b25e29843
slug
writing-clean-python-code-with-pep-8-f97b25e29843
url
https://medium.com/@allwin-raju/writing-clean-python-code-with-pep-8-f97b25e29843
canonical_url
https://medium.com/@allwin-raju/writing-clean-python-code-with-pep-8-f97b25e29843
author_url
https://medium.com/@allwin-raju
status
ok
fetched_at
2026-07-13 11:39:10