HomepythonPEP 8: The Python Style Guide - Basics

PEP 8: The Python Style Guide – Basics

Introduction

PEP 8, short for Python Enhancement Proposal 8, is the style guide for writing clean, readable, and consistent Python code. Guido van Rossum, Barry Warsaw, and Nick Coghlan authored PEP 8 to ensure that Python code remains readable and maintainable, especially in collaborative environments. Following PEP 8 guidelines helps developers avoid common pitfalls and standardizes the look of Python code across projects. This article provides a detailed overview of PEP 8, covering its key recommendations and providing examples.

General Guidelines

PEP 8 emphasizes readability and simplicity. Here are some of the fundamental principles:

  1. Indentation:
  • Use 4 spaces per indentation level.
  • Never mix tabs and spaces. Spaces are the preferred indentation method.
 def function():
     if condition:
         do_something()
  1. Maximum Line Length:
  • Limit all lines to a maximum of 79 characters.
  • For lines that cannot be easily wrapped, limit them to 72 characters.
 def long_function_name(var_one, var_two, var_three, var_four):
     print(var_one, var_two, var_three, var_four)
  1. Blank Lines:
  • Separate top-level function and class definitions with two blank lines.
  • Method definitions inside a class are separated by a single blank line.
 class MyClass:
     def method_one(self):
         pass

     def method_two(self):
         pass

Imports

PEP 8 provides guidelines for importing modules to keep the code organized and readable:

  1. Import Statements:
  • Imports should usually be on separate lines.
 import os
 import sys
  • Group imports in the following order: standard library imports, related third-party imports, and local application/library-specific imports. Each group should be separated by a blank line.
 import os
 import sys

 import numpy as np

 import mymodule
  1. Wildcard Imports:
  • Avoid wildcard imports (from module import *) as they make it unclear which names are present in the namespace.

Naming Conventions

Consistent naming conventions enhance code readability and help avoid conflicts. PEP 8 specifies the following:

  1. Variable Names:
  • Use lowercase letters with words separated by underscores (snake_case).
my_variable = 10
  1. Function Names:
  • Use lowercase letters with words separated by underscores (snake_case).
 def my_function():
     pass
  1. Class Names:
  • Use CapitalizedWords (PascalCase).
class MyClass:
     pass
  1. Constants:
  • Use all uppercase letters with words separated by underscores.
MAX_SIZE = 100

String Quotes

PEP 8 allows both single (') and double (") quotes for string literals but recommends consistency within a project:

my_string = "Hello, World!"
another_string = 'Python is great!'

Comments

Comments are crucial for understanding the purpose and functionality of code. PEP 8 provides guidelines for writing clear and concise comments:

  1. Block Comments:
  • Block comments generally apply to some (or all) code that follows them and are indented to the same level as that code.
 def my_function():
     # This is a block comment.
     # It explains the code that follows.
     do_something()
  1. Inline Comments:
  • Use inline comments sparingly. They should be separated by at least two spaces from the statement.
 x = x + 1  # Increment x
  1. Documentation Strings (Docstrings):
  • Use docstrings to describe all public modules, functions, classes, and methods.
 def my_function():
     """This is a docstring.
     It describes the purpose of the function.
     """
     pass

Whitespace in Expressions and Statements

PEP 8 recommends the following practices to enhance readability:

  1. Avoid Extraneous Whitespace:
  • Avoid spaces immediately inside parentheses, brackets, or braces.
 my_list = [1, 2, 3]
  • Avoid spaces before a comma, semicolon, or colon.
 if x == 1:
     print(x, y)
  1. Use Spaces Around Operators:
  • Use a single space before and after assignment (=) and comparison (==, <, >, !=, <=, >=) operators.
 x = 1
 y = x + 1

Programming Recommendations

PEP 8 also provides best practices for writing Python code:

  1. Comparisons:
  • Use is and is not when comparing to None.
 if x is None:
     pass
  • Use == and != to compare values.
 if x == 42:
     pass
  1. Boolean Values:
  • Use the fact that empty sequences are false.
 if not my_list:
     pass
  • Avoid comparing directly to True, False, or None.
 if my_var:
     pass

Conclusion

PEP 8 is an essential guide for Python developers aiming to write clean, readable, and maintainable code. Adhering to these conventions ensures consistency across projects and teams, making codebases easier to navigate and understand. While some guidelines may be relaxed depending on the specific project or team preferences, striving to follow PEP 8 as closely as possible generally leads to better quality code.

By incorporating PEP 8 standards into your coding practices, you contribute to a more organized and professional Python development environment.

Subscribe
Notify of

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments

Popular