3 Python Code Formatting
Complete Guide to
Clean & Beautiful Code
Tools, Tricks & Best Practices
Including: Ruff, Black, PEP 8, Watermark & More
Topics Covered:
¥ Code Formatters (Ruff, Black)
¥ Linters (Flake8, Pylint)
¥ PEP 8 Style Guide
¥ Watermark Extension
¥ Best Practices & Tricks
ª Author
Dr. Merwan Roudane
Version 1.0 — January 9, 2026
Ð Python Code Formatting Guide 1
Contents
1 Introduction to Code Formatting 2
2 PEP 8 — The Python Style Guide 2
2.1 Key PEP 8 Rules . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.2 Indentation Example . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 2
2.3 Import Organization . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3 Ruff — The Fastest Python Linter & Formatter 3
3.1 Why Choose Ruff? . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.2 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 3
3.3 Basic Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
3.4 Configuration ([Link]) . . . . . . . . . . . . . . . . . . . . . . . . . 4
4 Black — The Uncompromising Formatter 4
4.1 Installation & Usage . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 4
4.2 Before and After Example . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5 Watermark — IPython Magic Extension 5
5.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 5
5.2 Loading the Extension . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.3 Complete Options Reference . . . . . . . . . . . . . . . . . . . . . . . . . . 6
5.4 Usage Examples . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 6
6 Python Code Tricks for Clean Code 7
6.1 List Comprehensions . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 7
6.2 F-Strings (Formatted String Literals) . . . . . . . . . . . . . . . . . . . . . 7
6.3 Context Managers . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6.4 Enumerate and Zip . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8
6.5 Walrus Operator (Python 3.8+) . . . . . . . . . . . . . . . . . . . . . . . . 8
6.6 Unpacking . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
7 Tools Comparison 9
8 VS Code Configuration 9
8.1 [Link] . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9
8.2 Recommended Extensions . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9 Pre-commit Hooks 10
9.1 Installation . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 10
9.2 Configuration File . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 11
10 Summary & Quick Reference 11
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 2
1 Introduction to Code Formatting
Writing clean, readable code is essential for any Python developer. Good code formatting
makes your code easier to read, maintain, and debug.
ò Information
Why Code Formatting Matters:
• Readability: Clean code is easier to understand
• Maintenance: Well-formatted code is easier to modify
• Collaboration: Consistent style helps team members work together
• Bug Prevention: Good formatting helps catch errors early
2 PEP 8 — The Python Style Guide
PEP 8 is the official style guide for Python code. It provides conventions for formatting
and structuring your code.
2.1 Key PEP 8 Rules
Rule Description
Indentation Use 4 spaces per indentation level (not tabs)
Line Length Maximum 79 characters per line
Blank Lines 2 blank lines between top-level definitions
Imports Place imports at the top of the file
Whitespace Avoid extraneous whitespace
Comments Keep comments up-to-date with code
Naming Use descriptive, consistent naming conventions
Table 1: Essential PEP 8 Rules
2.2 Indentation Example
1 # Good - 4 spaces indentation
2 def calculate_sum ( numbers ) :
3 total = 0
4 for num in numbers :
5 if num > 0:
6 total += num
7 return total
8
9 # Bad - inconsistent indentation
10 def bad_function () :
11 x = 1 # 2 spaces - wrong !
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 3
12 y = 2 # 4 spaces - inconsistent !
Listing 1: Proper Indentation
2.3 Import Organization
1 # Standard library imports
2 import os
3 import sys
4
5 # Related third party imports
6 import numpy as np
7 import pandas as pd
8
9 # Local application imports
10 from myproject import utils
11 from myproject . models import User
Listing 2: Proper Import Organization
3 Ruff — The Fastest Python Linter & Formatter
[title=Ç Ruff Overview] Ruff is an extremely fast Python linter and code formatter,
written in Rust. It’s designed to be 10-100x faster than existing tools like Flake8,
Black, and isort.
3.1 Why Choose Ruff?
Feature Benefit
Ç Speed 10-100x faster than alternatives
Ô All-in-One Replaces Flake8, Black, isort, and more
800+ Rules Comprehensive code checking
Ð Editor Support First-party VS Code extension
¨ Monorepo Hierarchical configuration
Table 2: Ruff Features
3.2 Installation
1 # Using pip
2 pip install ruff
3
4 # Using conda
5 conda install -c conda - forge ruff
6
7 # Using homebrew ( macOS )
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 4
8 brew install ruff
Listing 3: Installing Ruff
3.3 Basic Usage
1 # Check all files in current directory
2 ruff check .
3
4 # Check and fix issues automatically
5 ruff check -- fix .
6
7 # Format code ( like Black )
8 ruff format .
9
10 # Watch for changes and re - lint
11 ruff check -- watch .
Listing 4: Ruff Commands
3.4 Configuration ([Link])
1 [ tool . ruff ]
2 line - length = 88
3 target - version = " py311 "
4
5 [ tool . ruff . lint ]
6 select = [ " E " , " W " , " F " , " I " , " N " , " UP " ]
7 ignore = [ " E501 " ]
8
9 [ tool . ruff . format ]
10 quote - style = " double "
11 indent - style = " space "
Listing 5: Ruff Configuration
Pro Tip: Start with Ruff’s default configuration and gradually add rules as needed.
This prevents overwhelming your codebase with too many changes at once.
B
4 Black — The Uncompromising Formatter
4.1 Installation & Usage
1 # Install
2 pip install black
3
4 # Format a file
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 5
5 black my_script . py
6
7 # Format a directory
8 black src /
9
10 # Check without modifying
11 black -- check .
12
13 # Show diff without modifying
14 black -- diff my_script . py
Listing 6: Black Commands
4.2 Before and After Example
1 # Messy code
2 def my_function ( arg1 , arg2 , arg3 , arg4 , arg5 ) :
3 result ={ ’ key1 ’: arg1 , ’ key2 ’: arg2 , ’ key3 ’: arg3 }
4 return result
Listing 7: Before Black Formatting
1 # Clean code
2 def my_function ( arg1 , arg2 , arg3 , arg4 , arg5 ) :
3 result = {
4 " key1 " : arg1 ,
5 " key2 " : arg2 ,
6 " key3 " : arg3 ,
7 }
8 return result
Listing 8: After Black Formatting
5 Watermark — IPython Magic Extension
[title=* Watermark Extension] The watermark extension is an IPython magic
function for printing date/time stamps, version numbers, and hardware information.
It’s essential for reproducibility in Jupyter notebooks.
5.1 Installation
1 # Using pip
2 pip install watermark
3
4 # Using conda
5 conda install -c conda - forge watermark
Listing 9: Installing Watermark
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 6
5.2 Loading the Extension
1 # Load the extension
2 % load_ext watermark
3
4 # Display basic information
5 % watermark
Listing 10: Loading Watermark in Jupyter
5.3 Complete Options Reference
Short Long Option Description
-a –author Prints author name
-gu –github_username Prints GitHub username
-e –email Prints author email
-ws –website Prints website URL
-d –date Prints current date (YYYY-mm-dd)
-n –datename Prints date with day/month names
-t –time Prints current time (HH-MM-SS)
-i –iso8601 Prints ISO 8601 datetime with time-
zone
-z –timezone Appends local time zone
-u –updated Prepends "Last updated: "
-c –custom_time Custom strftime() format
-v –python Prints Python & IPython version
-p –packages Prints versions of specified packages
-co –conda Prints current conda environment
-h –hostname Prints the host name
-m –machine Prints system & machine info
-g –githash Prints current Git commit hash
-r –gitrepo Prints Git remote URL
-b –gitbranch Prints Git branch name
-w –watermark Prints watermark version
-iv –iversions Prints versions of all imported packages
Table 3: Watermark Command Options
5.4 Usage Examples
1 # Author with date and time
2 % watermark -a " Your Name " -d -t
3 # Output : Your Name 2026 -01 -09 14:30:45
4
5 # Full system information
6 % watermark -v -m
7 # Output :
8 # Python implementation : CPython
9 # Python version : 3.11.5
10 # IPython version : 8.15.0
11 # Compiler : GCC 11.4.0
12 # OS : Linux
13 # CPU cores : 8
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 7
14 # Architecture : 64 bit
15
16 # Package versions
17 % watermark -p numpy , pandas , matplotlib
18 # Output :
19 # numpy : 1.24.3
20 # pandas : 2.0.3
21 # matplotlib : 3.7.2
22
23 # All imported packages
24 import numpy as np
25 import pandas as pd
26 % watermark - iv
27 # Output :
28 # numpy : 1.24.3
29 # pandas : 2.0.3
30
31 # Complete notebook header
32 % watermark -a " Your Name " -v - iv -d -t -z
Listing 11: Watermark Usage Examples
Best Practice: Add a watermark cell at the end of every Jupyter notebook for repro-
ducibility. This documents the exact environment used.
6 Python Code Tricks for Clean Code
6.1 List Comprehensions
bT
raditional loop (avoid) squares = [] for x in range(10): [Link](x ** 2)
List comprehension (preferred) squares = [x ** 2 for x in range(10)]
With condition evens quares = [x ∗ ∗2f orxinrange(10)if x
6.2 F-Strings (Formatted String Literals)
1 name = " Python "
2 version = 3.11
3
4 # Old way ( avoid )
5 msg = " Language : " + name + " , Version : " + str ( version )
6 msg = " Language : {} , Version : {} " . format ( name , version )
7
8 # F - string ( preferred )
9 msg = f " Language : { name } , Version : { version } "
10
11 # With expressions
12 msg = f " Next version : { version + 0.1:.1 f } "
13
14 # With formatting
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 8
15 price = 49.99
16 msg = f " Price : $ { price : ,.2 f } "
Listing 12: F-String Examples
6.3 Context Managers
1 # Without context manager ( risky )
2 f = open ( " file . txt " , " r " )
3 content = f . read ()
4 f . close () # May not execute if error occurs !
5
6 # With context manager ( safe )
7 with open ( " file . txt " , " r " ) as f :
8 content = f . read ()
9 # File automatically closed , even on error
10
11 # Multiple context managers
12 with open ( " input . txt " ) as fin , open ( " output . txt " , " w " ) as fout :
13 fout . write ( fin . read () . upper () )
Listing 13: Context Manager Usage
6.4 Enumerate and Zip
1 fruits = [ " apple " , " banana " , " cherry " ]
2
3 # Without enumerate ( avoid )
4 i = 0
5 for fruit in fruits :
6 print (i , fruit )
7 i += 1
8
9 # With enumerate ( preferred )
10 for i , fruit in enumerate ( fruits ) :
11 print (i , fruit )
12
13 # Starting from different index
14 for i , fruit in enumerate ( fruits , start =1) :
15 print (i , fruit )
16
17 # Zip for parallel iteration
18 names = [ " Alice " , " Bob " , " Charlie " ]
19 ages = [25 , 30 , 35]
20 for name , age in zip ( names , ages ) :
21 print ( f " { name } is { age } years old " )
Listing 14: Enumerate and Zip
6.5 Walrus Operator (Python 3.8+)
1 # Without walrus operator
2 data = get_data ()
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 9
3 if data :
4 process ( data )
5
6 # With walrus operator
7 if ( data := get_data () ) :
8 process ( data )
9
10 # In list comprehensions
11 results = [ y for x in data if ( y := e x p e n s i v e _ c o m p u t a t i o n ( x ) ) > 0]
12
13 # In while loops
14 while ( line := file . readline () ) :
15 process ( line )
Listing 15: Walrus Operator Examples
6.6 Unpacking
1 # Basic unpacking
2 a , b , c = [1 , 2 , 3]
3
4 # Extended unpacking
5 first , * rest = [1 , 2 , 3 , 4 , 5] # first =1 , rest =[2 ,3 ,4 ,5]
6 first , * middle , last = [1 , 2 , 3 , 4 , 5] # middle =[2 ,3 ,4]
7
8 # Swap variables
9 a, b = b, a
10
11 # Unpack in function calls
12 def func (a , b , c ) :
13 return a + b + c
14
15 args = [1 , 2 , 3]
16 result = func (* args ) # Unpacks list
17
18 kwargs = { " a " : 1 , " b " : 2 , " c " : 3}
19 result = func (** kwargs ) # Unpacks dict
Listing 16: Unpacking Techniques
7 Tools Comparison
8 VS Code Configuration
8.1 [Link]
1 {
2 " python . d e f a u l t I n t e r p r e t e r P a t h " : " ./ venv / bin / python " ,
3 " [ python ] " : {
4 " editor . defaultFormatter " : " charliermarsh . ruff " ,
5 " editor . formatOnSave " : true ,
6 " editor . co deAction sOnSave " : {
7 " source . organizeImports " : " explicit " ,
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 10
Feature Ruff Black Flake8 Pylint
Speed ÇÇÇ ÇÇ Ç
Formatting ¥ ¥ q q
Linting ¥ q ¥ ¥
Auto-fix ¥ ¥ q q
Rules 800+ N/A 100+ 400+
Config Low Minimal Medium High
Table 4: Code Tools Comparison
8 " source . fixAll " : " explicit "
9 }
10 },
11 " ruff . lint . enable " : true ,
12 " ruff . format . args " : [ " -- line - length " , " 88 " ]
13 }
Listing 17: VS Code Settings for Python
8.2 Recommended Extensions
• Ruff — [Link]
• Python — [Link]
• Pylance — [Link]-pylance
• Black Formatter — [Link]-formatter
9 Pre-commit Hooks
Pre-commit hooks run automatically before each commit to ensure code quality.
9.1 Installation
1 # Install pre - commit
2 pip install pre - commit
3
4 # Install the hooks
5 pre - commit install
6
7 # Run on all files
8 pre - commit run -- all - files
Listing 18: Setting Up Pre-commit
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code
Ð Python Code Formatting Guide 11
9.2 Configuration File
1 repos :
2 - repo : https :// github . com / astral - sh / ruff - pre - commit
3 rev : v0 .1.6
4 hooks :
5 - id : ruff
6 args : [ - - fix ]
7 - id : ruff - format
8
9 - repo : https :// github . com / pre - commit / pre - commit - hooks
10 rev : v4 .5.0
11 hooks :
12 - id : trailing - whitespace
13 - id : end - of - file - fixer
14 - id : check - yaml
15 - id : check - added - large - files
Listing 19: .[Link]
10 Summary & Quick Reference
¥ Quick Start Checklist
1. Install Ruff: pip install ruff
2. Format code: ruff format .
3. Check code: ruff check –fix .
4. Add pre-commit hooks
5. Configure VS Code
6. Use watermark in notebooks for reproducibility
.
Remember: Consistency is more important than perfection. Pick a style and stick
with it across your entire project.
(
Ð Python Code Formatting Guide 12
Dr. Merwan Roudane — Best Practices & Tools for Clean Python Code