Sometimes, it’s okay to break PEP 8 rules if it makes the code easier to read. The goal is always readability.
What is PEP 8?
PEP stands for Python Enhancement Proposal. It’s a document that suggests changes and improvements to Python. PEP 8 is one of the most popular PEPs because it provides guidelines for writing clean and readable Python code. Created in 2001 by Guido van Rossum, Barry Warsaw, and Nick Coghlan, PEP 8 provides a detailed guide for writing clean and readable Python code.
This encapsulates the core philosophy of PEP 8: prioritizing clarity, which ultimately makes collaboration and maintenance easier.
Why do we need PEP 8?
The main goal of PEP 8 is to make Python code readable. Python code should be easy to understand. The easier it is to read, the easier it is to maintain, update, and share with others. Writing readable code also reduces bugs and errors.
Naming convention
Names in Python are important. PEP 8 recommends using meaningful and descriptive names for variables, functions, and classes.
Variables and functions: Use lowercase letters with words separated by underscores (
my_variable,calculate_total()).Classes: Use capitalized words without underscores (
MyClass,CustomerOrder).Constants: Use all uppercase letters, separating words with underscores (
MAX_SPEED,PI_VALUE).Functions: Use lowercase with underscores (
my_function())
Example:
def calculate_sum(numbers_list):total_sum = 0for number in numbers_list:total_sum += numberreturn total_sum
How to choose names
Names should be easy to understand. Avoid abbreviations. Use full words that describe what the variable or function does. For example, instead of calc(), use calculate().
Code layout
PEP 8 provides rules for organizing your code. Keep your lines short and use blank lines to separate sections of code.
Keep lines under 79 characters.
Use two blank lines before functions and classes.
Example:
class Car:def __init__(self, make, model):self.make = makeself.model = modeldef start_engine(self):print("Engine started!")
Indentation
Indentation shows the structure of the code. PEP 8 recommends using 4 spaces per indentation level.
Example:
if x > 5:print("x is greater than 5")
Tabs vs. spaces
PEP 8 says to use spaces, not tabs. Mixing tabs and spaces can cause errors.
Indentation following line breaks
If a line is too long, break it up. Indent the second line to line up with the first.
Example:
my_list = [1, 2, 3,4, 5, 6]
Where to put the closing bracket
When a line breaks, the closing bracket should line up with the first line of code or the indentation level.
Example:
my_list = [1, 2, 3,4, 5, 6]
Comments
Comments explain your code. Use them to make your code easier to understand.
Block comments
Block comments explain a section of code. They should be placed above the code.
Example:
# Calculate the total sum of the numbers in the list.total_sum = sum(numbers_list)
Inline comments
Inline comments explain a single line of code. Keep them short and simple.
Example:
x = x + 1 # Increase x by 1
Documentation strings
Use docstrings to explain what your functions and classes do.
Example:
def add(a, b):"""Return the sum of a and b."""return a + b
Whitespace in expressions and statements
Use whitespace to make your code clearer.
Whitespace around binary operators
Add a single space around operators like +, -, and =.
Example:
total = price + tax
When to avoid adding whitespace
Do not add extra spaces inside parentheses, brackets, or braces.
Example:
# Correctmy_list = [1, 2, 3]# Incorrectmy_list = [ 1, 2, 3 ]
Programming recommendations
PEP 8 also suggests some programming best practices:
Use
isoris notto compare withNone.Don’t use
==to compare Boolean values.
Example:
# Recommendedif my_var is None:print("my_var is None")
Let's solve the quiz below:
Which PEP 8 recommendation does this code violate?
myVariable = 10
This follows PEP 8.
Variable names should be written in snake_case.
The variable name should be more descriptive.
Tips and tricks to follow PEP 8
There are tools that can help you follow PEP 8:
Linters: Tools like
pylintandflake8can check your code for PEP 8 violations.Autoformatters: Tools like
blackandautopep8can automatically format your code to follow PEP 8.
PEP 8, Python's style guide for code, remains a resource for maintaining consistency and readability in Python codebases. It's updated periodically to reflect changes in the language and its evolving best practices. As Python continues to expand and introduce new features, PEP 8 adapts to ensure that its guidelines remain aligned with the latest developments in the language. Keeping up with these updates ensures that your code stays current and follows community-driven standards.
Key takeaways:
PEP 8: A Python guideline for writing clean, readable, and maintainable code.
Naming conventions: Use
lower_case_with_underscoresfor variables/functions,CamelCasefor classes, andALL_CAPSfor constants.Code layout: Keep lines under 79 characters, and use 2 blank lines before functions/classes.
Indentation: Use 4 spaces per level, no tabs.
Comments and docstrings: Use block comments for sections, inline comments for single lines, and docstrings to describe functions/classes.
Whitespace: Add spaces around operators; avoid spaces inside parentheses.
Best practices: Use
is/is notforNonecomparisons, avoid==for booleans.Tools: Use linters (e.g.,
pylint,flake8) and autoformatters (e.g.,black,autopep8) to enforce PEP 8.
Ready to deepen your Python knowledge? Start our Become a Python Developer path, beginning with Python's basic concepts and advancing to more complex topics, preparing you for a career as a Python developer.
Frequently asked questions
Haven’t found what you were looking for? Contact Us
When can we ignore PEP 8?
How to get PEP 8 in Python?
How to check for PEP 8?
What is PEP 8 in Python interview questions?
Free Resources