Crafting Useful Code Examples: From Basic Snippets to Real-World Scenarios
You know that feeling when you find a new library, and the first thing you do is scroll straight past all the carefully written prose to find the code examples? Yeah, me too. We developers are a predictable bunch - we learn best by example, and we’re always in a hurry to see the code in action.
That’s why, after years of maintaining Python libraries and watching users interact with documentation, I’ve learned that your code examples aren’t just supplementary material - they’re often the main course. In this post, I’ll share what I’ve learned about crafting code examples that users actually want to read and can easily use.
The Secret Sauce of Great Code Examples
Think of code examples like recipes in a cookbook. The best ones aren’t just technically correct - they’re easy to follow, show you what to expect, and help you avoid common mistakes. Here’s what makes a code example truly useful:
- It should run without surprises (include those imports!)
- It should be focused on one specific thing (like a good Unix tool)
- It should use clear, descriptive names (no
foo
orbar
unless you’re explicitly talking about metaprogramming) - It should show typical usage (save the edge cases for later)
- Ideally, it should be automatically tested (because we all know how quickly examples can get outdated)
The Three Flavors of Code Examples
1. The Quick Bite: Docstring Examples
These are your bite-sized examples, perfect for showing how to use a specific function or method. I love using Python’s built-in doctest
format for these - it’s like getting documentation and tests in one go:
def calculate_discount(price: float, percentage: float) -> float:
"""Calculate the discounted price of an item.
>>> calculate_discount(100.0, 20.0) # 20% off $100
80.0
>>> calculate_discount(50.0, 10.0) # 10% off $50
45.0
>>> calculate_discount(200.0, 0.0) # No discount
200.0
"""
if not 0 <= percentage <= 100:
raise ValueError("Percentage must be between 0 and 100")
return price * (1 - percentage / 100)
The beauty of this format is that it shows both the input and the expected output, and you can actually run these examples as tests using Python’s doctest
module. No more outdated examples!
2. The Step-by-Step: Tutorial Examples
When you’re writing a tutorial, your examples need to tell a story. Each piece builds on the last, guiding the user through a complete workflow. Here’s how I structure these:
# First, let's import what we need
import pandas as pd
from your_library import DataCleaner
# Start with some sample data
data = pd.DataFrame({
'name': ['John Smith', 'Jane Doe', 'Bob Johnson'],
'email': ['john@email.com', 'jane@email', 'bob@email.com'],
'age': ['25', '30', 'invalid']
})
# Now let's clean it up
cleaner = DataCleaner()
cleaner.validate_emails('email') # Finds invalid email formats
cleaner.convert_to_int('age') # Converts age to integers, handling errors
# Check our results
print(cleaner.validation_report())
Notice how each step flows naturally into the next, with comments explaining what we’re doing and why. This isn’t just a random collection of commands - it’s a guided tour through a real-world use case.
3. The Full Meal: Standalone Example Scripts
Sometimes you need to show something more complex - a complete application or an advanced feature. That’s where standalone example scripts come in. You can keep these in an examples/
directory and use sphinx-gallery
to turn them into beautiful documentation:
"""
Building a Custom Data Pipeline
=============================
This example shows how to build a complete data processing pipeline
using YourLibrary's components.
"""
import your_library as yl
import pandas as pd
import matplotlib.pyplot as plt
# Load and prepare our data
data = pd.read_csv('sample_data.csv')
# Create our pipeline
pipeline = yl.Pipeline([
yl.steps.CleanMissingValues(),
yl.steps.NormalizeFeatures(),
yl.steps.PredictOutliers()
])
# Fit and transform our data
results = pipeline.fit_transform(data)
# Visualize the results
plt.figure(figsize=(10, 6))
plt.scatter(results['feature1'], results['feature2'], c=results['outlier_score'])
plt.colorbar(label='Outlier Score')
plt.title('Outlier Detection Results')
plt.show()
Making Your Examples Maintainable
Here’s a pro tip I learned the hard way: examples are code too, and they need maintenance just like the rest of your codebase. Here’s my strategy:
Use
doctest
for simple examples in docstrings:python -m doctest -v your_module.py
For tutorials and larger examples, include them in your test suite:
def test_tutorial_example(): # Actually run the code from your tutorial result = run_tutorial_code() assert result.is_valid()
Use
sphinx-gallery
to automatically run and test your example scripts during documentation builds:# In conf.py extensions = [ 'sphinx_gallery.gen_gallery', ] sphinx_gallery_conf = { 'examples_dirs': '../examples', 'gallery_dirs': 'auto_examples', }
The Real Test
Want to know if your examples are good enough? Watch a new user try to use them. If they can copy, paste, and run your example without having to modify anything or look up additional information, you’ve nailed it.
Remember: every time you write an example, you’re not just showing how to use your code - you’re showing developers that your library is worth their time. Make those examples count.
And please, for the love of all things Pythonic, test your examples before you publish them. Nothing erodes trust faster than a code example that doesn’t work. Trust me, I’ve been there, and the GitHub issues that follow are not fun to deal with.
A Final Thought
The best code examples aren’t just demonstrations - they’re teaching tools. They should make your users think “Ah, now I get it!” not “Wait, what’s happening here?” When in doubt, err on the side of clarity over cleverness. Your future users (and your future self) will thank you.
Subscribe to the Newsletter
Get the latest posts and insights delivered straight to your inbox.