Sometimes, it’s okay to break PEP 8 rules if it makes the code easier to read. The goal is always readability.
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.
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.
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
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()
.
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 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")
PEP 8 says to use spaces, not tabs. Mixing tabs and spaces can cause errors.
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]
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 explain your code. Use them to make your code easier to understand.
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 explain a single line of code. Keep them short and simple.
Example:
x = x + 1 # Increase x by 1
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
Use whitespace to make your code clearer.
Add a single space around operators like +
, -
, and =
.
Example:
total = price + tax
Do not add extra spaces inside parentheses, brackets, or braces.
Example:
# Correctmy_list = [1, 2, 3]# Incorrectmy_list = [ 1, 2, 3 ]
PEP 8 also suggests some programming best practices:
Use is
or is not
to compare with None
.
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.
There are tools that can help you follow PEP 8:
Linters: Tools like pylint
and flake8
can check your code for PEP 8 violations.
Autoformatters: Tools like black
and autopep8
can 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_underscores
for variables/functions, CamelCase
for classes, and ALL_CAPS
for 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 not
for None
comparisons, 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.
Haven’t found what you were looking for? Contact Us
Free Resources