6.4 Showing Code Examples

Examples of Python source code or interactive sessions are represented as \verbatim environments. This environment is a standard part of LATEX. It is important to only use spaces for indentation in code examples since TEX drops tabs instead of converting them to spaces.

Representing an interactive session requires including the prompts and output along with the Python code. No special markup is required for interactive sessions. After the last line of input or output presented, there should not be an ``unused'' primary prompt; this is an example of what not to do:

>>> 1 + 1

Within the \verbatim environment, characters special to LATEX do not need to be specially marked in any way. The entire example will be presented in a monospaced font; no attempt at ``pretty-printing'' is made, as the environment must work for non-Python code and non-code displays. There should be no blank lines at the top or bottom of any \verbatim display.

Longer displays of verbatim text may be included by storing the example text in an external file containing only plain text. The file may be included using the standard \verbatiminput macro; this macro takes a single argument naming the file containing the text. For example, to include the Python source file example.py, use:


Use of \verbatiminput allows easier use of special editing modes for the included file. The file should be placed in the same directory as the LATEX files for the document.

The Python Documentation Special Interest Group has discussed a number of approaches to creating pretty-printed code displays and interactive sessions; see the Doc-SIG area on the Python Web site for more information on this topic.

See About this document... for information on suggesting changes.