Python Code Formatting Guide: PEP8
When writing Python code, it’s important to create readable, understandable, and maintainable code. But how can you ensure your code is truly easy to understand and adheres to best practices? This is where PEP8, the official Python coding style guide, comes in. It defines the rules for formatting and writing code. In this article, we’ll explore the key recommendations from PEP8 and learn how to apply them in practice to ensure your Python code not only fulfills its purpose but is also understandable to your colleagues (and to you in six months).
Indents
- Use 4 spaces for each indentation level.
- The extra lines should align the wrapped elements.Option 1 vertical:
foo = function_name(var_one, var_two, var_three, var_four)
Option 2 with indentation (then there should be no arguments in the first line):
foo = function_name(
var_one, var_two,
var_three, var_four)
- In multi-line constructions, it is better to place closing parentheses under the first non-space character of the last line:
my_list = [
1,2,3,
4,5,6,
]
- Also, closing parentheses can be aligned below the first character of the line that starts the multi-line construct:
my_list = [
1,2,3,
4,5,6,
]
Maximum line length
- Limit all lines to 79 characters.
- Lines containing text (documentation or comments) should be limited to 72 characters.
- Long lines can be broken into multiple lines by enclosing expressions in parentheses.
Blank lines
- Separate top-level function and class definitions with two blank lines.
- Separate methods within a class with one blank line.
- Additional blank lines may be used (in small numbers) to separate groups of related functions.
- There must be a blank line between each import group.
Import
- Imports must be on separate lines:
# Right:
import os
import sys
#Wrong:
import sys, os
Although it is also possible:
from subprocess import Popen, PIPE
- Imports are always placed at the top of the file, immediately after comments and docstrings, and before global variables and module constants.
- Imports should be grouped in the following order:
- Standard Import Library.
- Related third-party imports.
- Import for a local application or library.
Spaces
Avoid unnecessary spaces:
- Inside and before parentheses:
#Right:
spam(ham[1])
# Wrong:
spam ( ham[ 1 ] )
- Between the comma and the closing parenthesis:
# Right:
foo = (0,)
# Wrong:
bar = (0, )
- More than one space around an assignment (or other) operator:
# Right:
x = 1
y = 2
long_var = 3
# Wrong:
x = 1
y = 2
long_var = 3
Naming styles
The following naming styles are commonly distinguished:
- b (one lowercase letter)
- B (one capital letter)
- lowercase
- lower_case_with_underscores
- UPPERCASE
- UPPER_CASE_WITH_UNDERSCORES
- CapitalizedWords
- mixed case
- Capitalized_Words_With_Underscores
Names to Avoid
- ‘l’, ‘O’, or ‘I’ as single-character variable names
- __name__
- _name
- name_
Naming rules
- Packages and modules: lowercase, lower_with_underscores
- Classes: CapitalizedWords
- Global variables: lowercase, lower_with_underscores, __all__
- Functions and variables: lowercase, lower_with_underscores
- Function and method arguments: self is the first argument for instance methods, cls is the first argument for class methods
- Constants: UPPERCASE, UPPER_WITH_UNDERSCORES
Conclusion
Following these guidelines may not seem so important at first, especially when the code works without them. However, as practice shows, structured and neat code not only makes your work easier but also makes it easier for other developers to understand. Remember: good programming style is not just a matter of aesthetics; it’s a testament to your professionalism.
Explore More IT Terms
#
A
- A Guide to SQL Query Formatting
- A/B testing
- Agile
- Algorithm complexity in 5 minutes
- Algorithms and Data Structures in C#
- An overview of the C # programming language
- An overview of the Python programming language
- Anaconda Python
- Android
- Android App Bundle
- Android SDK
- Angular
- Ansible
- Apache
- Apache Airflow
- Apache Kafka
- Apache Tomcat
- App Store
- AppCode
- Array-based stack
- ArrayList
- ASCII
- ASP.NET
- Assembly Language Lessons
B
C
D
- Data Analytics: applications of data analysis in companies
- Data Engineer - Who is it, what does a data engineer do, and an overview of the profession
- Data modeling: what it is, types, and process steps.
- Data preprocessing: a complete guide for beginners and professionals.
- Data structure
- Data structures
- Defining Aliases
- Defining Arrays
- Deque
- Developing a Website from Scratch
- Digital data: understand the importance of this asset for businesses.
- Doubly linked lists
E
F
H
- Handling errors and exceptions
- How to effectively organize your workflow
- How to Learn Java: Tips for Beginner Developers
- How to Learn PHP: A Beginner's Guide
- How to Use S3 Storage in Kubernetes with CSI
- HTML
- HTML and CSS: Definition, Application, and Operating Principles
- HTML and CSS. Layout from Scratch: What to Learn, Where to Learn, and How Long Will It Take?
- HTML Frame Structure
- HTML Link Formatting
I
- if..else construction
- Inserting an Image
- Interactive Python Tutorial – Learn Programming from Scratch
- Interview Problem: Finding a Deleted Element in O(N)
- Interview Scare: The FizzBuzz Challenge
- Introduction to C++
- Introduction to Machine Learning
- Introduction to programming languages
- IT Specialist Resume (CV)
K
M
O
P
S
- SFML Graphics Library Tutorials
- SQL commands: see what they are, what the main ones are + examples
- SQL Interview Questions and Tasks
- SQL Lessons
- SQL Stored Procedures
- SQL Syntactic Sugar: The COALESCE Function
- Stack
- Start in analytics: Python or R
- Statistical analysis: importance for decision making.
- String formatting in Python
- Swift Lessons
- switch/match construct
T
W
- What are databases, and why do they need DBMS and SQL?
- What do Linux distributions consist of?
- What is .NET and what is it used for?
- What is a GPU in a computer, in simple terms?
- What is Big Data? Introduction, Types, Characteristics, and Examples
- What is Golang and what is it used for?
- What is Haskell and what is it used for?
- What is Kotlin and what is it used for?
- What is Linux? The History of Linux
- What is machine learning, and how does it work?
- What is Power BI: everything about the data analytics software
- What is the C++ programming language?
- What is the OSI Model: A Complete Explanation of the Seven Layers and Their Role in Networking
- Where to start learning the C programming language?
- Which Linux distribution should you choose? A Linux distribution overview
