Examples sit right under the docs for each function, class, and constant. Their job is to show how something is used, quickly and clearly. These guidelines help keep them that way.
Examples should be short, self-contained snippets that show one thing in the simplest way that works.
A reader should be able to paste your example into a fresh interpreter and run it.
Bad:
Counter("mississippi").most_common(2) # => [('i', 4), ('s', 4)]
Good:
from collections import Counter Counter("mississippi").most_common(2) # => [('i', 4), ('s', 4)]
Write the value of an expression in a # => comment, and printed output in a # prints: comment. The >>> interpreter style is fine too. Keeping to these forms means examples can be checked automatically later.
import os.path os.path.splitext("archive.tar.gz") # => ('archive.tar', '.gz') print(os.path.join("docs", "index.html")) # prints: docs/index.html
>>> "a,b,,c".split(",") ['a', 'b', '', 'c']
An example can show the range of inputs something accepts, like this one for round:
round(2.675, 2) # => 2.67 (floats are binary; 2.675 is stored as 2.67499...) round(0.5) # => 0 round(1.5) # => 2 (ties round to the even number) round(1234, -2) # => 1200
Or it can go deep on one use, like this one for functools.lru_cache:
from functools import lru_cache @lru_cache(maxsize=None) def fib(n): return n if n < 2 else fib(n - 1) + fib(n - 2) fib(80) # => 23416728348467685 # Each value was computed once and then served from the cache. fib.cache_info() # => CacheInfo(hits=78, misses=81, maxsize=None, currsize=81)
Please also point out any gotchas, about your example or about the function in general.
Use comments to explain what the next lines do, or to point out something a newcomer might miss. Don't repeat what the code already says.
Bad:
# call sorted on words sorted(words, key=len)
Good:
words = ["banana", "fig", "apple"] # Sort by length; sorted() is stable, so equal lengths keep their order. sorted(words, key=len) # => ['fig', 'apple', 'banana']
Examples, see-alsos, and notes on PyDocs are dedicated to the public domain under theCreative Commons CC0 license, so anyone can reuse them.