PyDocs

PyDocs Example Guidelines

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.

General guidelines

Examples should be short, self-contained snippets that show one thing in the simplest way that works.

  • Decide what your example is about before you write it, and leave out everything else.
  • Assume the reader knows programming but is new to Python.
  • Short, complete, and correct beats clever.
  • Standard library only: no third-party packages.
  • It must run on the Python version these docs describe.

Include every import

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)]

Show results

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']

Broad or deep, not both

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.

Comments

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']

Formatting

  • Follow PEP 8. Indent with 4 spaces (the editor's Tab key inserts them).
  • Keep lines under 80 characters. The editor shows a guide.
  • Leave a blank line between separate ideas.

License

Examples, see-alsos, and notes on PyDocs are dedicated to the public domain under theCreative Commons CC0 license, so anyone can reuse them.