Skip to main content

Python Code in LaTeX

In A Student’s Guide to Python for Physical Modeling, we used the Listings package for LaTeX to format our code samples. In this post, we describe how we used the package and provide our style files for others to use.

Typesetting Computer Code

The listings package makes it easy to format code for typesetting in LaTeX. It allows the author to adjust virtually every aspect of how code is displayed. We used the package to develop our own syntax highlighting scheme.
  • All code is displayed in a monospace (typewriter) font.
  • Built-in functions and reserved words are bold and green.
  • Python exceptions are bold and red.
  • Modules and functions from NumPy and PyPlot are bold and black.
  • Modules and functions from other modules are bold and blue.
  • Strings are red.
  • Keyword arguments to functions are italic.
  • Comments are blue italic.
This scheme is similar to the one used in Spyder. It allows a reader to distinguish built-in functions and modules from variable names and user-defined functions at a glance.

How to Use the Style Files

The bulk of the work lies in setting up an environment to display code the way you want. We’ve already done that for you!
To start producing formatted code, just download one of the LaTeX files below. Put it somewhere LaTeX can find it, then add this line to the preamble of your document:
\include{listings_py34}
Somewhere after \begin{document} and before your first code sample, type
\pysetup
This will set all the style parameters and create the list of keywords to be displayed in different fonts and colors. Now you are ready to start adding code to your document.

Examples

The listings package provides three ways to add code to your document. In some ways, these environments are similar to LaTeX’s native verbatim environment: Every character you type will be printed, including spaces, tabs, and line breaks.

Inline Code

Very short fragments can be displayed inline. To do this, use the \lstinline command.
To plot the data, type \lstinline!plt.plot(x,y)! at the command line.
You do not have to use exclamation points to enclose the code fragment. You can use almost any set of special symbols that do not appear in the code fragment itself.
\lstinline!print(x)!,  \lstinline&print(x)&, and \lstinline$print(x)$ all
produce the same output.

Code Environment

For longer code samples, you can place the code inside of an lstlisting environment.
\begin{lstlisting}
def hello():
    print("Hello, world!")
    return 0
\end{lstlisting}
This will typeset a function definition.

Include Source Code

You can also directly import entire programs using the \lstinputlisting{} command. The program text will be formatted according to the style specifications and displayed exactly as typed.
\lstinputlisting{code/hello.py}
This will display the program hello.py, located in the code/ directory, in the typeset document.

Swapping Keywords Between Lists

Sometimes a word plays multiple roles in Python. For instance, dtype is an attribute of a NumPy array. It is also a keyword argument to the function `np.array’. To properly display the same word in different contexts using the listings package, it must be transferred between lists of keywords. We have provided a simple macro to do this.
\swapKeyword{keyword}{old_list}{new_list}
will delete keyword from old_list (if it is a member) and add it to new_list. For the dtype example, you might type something like
\swapKeyword{dtype}{3}{5}
To create an floating point array, type \lstinline!x = np.array([1,2,3], dtype='float')!.
\swapKeyword{dtype}{5}{3}
We can check the data type of the array: \lstinline!x.dtype!.
dtype is transferred from keyword list 3 (NumPy and PyPlot methods) to keyword list 5 (function keyword arguments) for the first inline code sample, then back its original list for the second. Thus, it appears in italics in the first instance and in bold in the second.

Download the Files

We have prepared two versions of the header file — one for Python 2.7 and one for Python 3.4. These differ only in a few reserved words and keywords that are unique to one version of Python or the other. For example, xrange and raw_input are built-in functions in Python 2.7, but they are not present in Python 3.4. Click on the appropriate link to download the version of the file you want. sample.tex is a short LaTeX document that illustrates the use of the listings package, and sample.pdf is the final output.
listings_py27.tex
listings_py34.tex
sample.tex
sample.pdf

More Information

The listings package maintained by Jobst Hoffman. You can download the User’s Guide for the listings package here.
We have only described a small fraction of what is possible with this package, but we hope that it is a useful fraction for those who wish to write about Python!

Comments

Popular posts from this blog

Paths in Python

How do you get your Python interpreter to find modules that are not located in your current working directory? The answer is … you tell it where to look. When you type something like from my_module import my_function Python searches a collection of directories (i.e., folders) on your computer. If the directory containing <my_module.py> is not in this collection, you will receive an ImportError . This can be frustrating if you know the file exists, and even more so if you know where it exists. In this post, we will take a brief look at how to add paths to the collection of directories searched by Python. Paths A path is essentially a set of directions to a file: /Users/username/modules/my_module.py [Mac OS X, Linux] C:\modules\my_module.py [Windows] It tells your operating system how to navigate from a fixed starting point — the “root directory” / in Unix-based systems, or C:\ in Windows — through a collection of folders to the de

Illuminating Surface Plots

Matplotlib provides functions for visualizing three-dimensional data sets. One useful tool is a surface plot. A surface plot is a two-dimensional projection of a three-dimensional object. Much like a sketch artist, Python uses techniques like perspective and shading to give the illusion of a three-dimensional object in space. In this post, I describe how you can control the lighting of a surface plot. Surface Plots First, let’s look at some of the options available with the default three-dimensional plotting tools. This script will create a surface plot of a Bessel function. Its ripples will emphasize the effects of lighting later. import numpy as np import matplotlib.pyplot as plt from mpl_toolkits.mplot3d import Axes3D # Import 3D plotting tools. from scipy.special import jn # Import Bessel function. # Define grid of points. points = np.linspace(-10, 10, 51) X, Y = np.meshgrid(points, points) R = np.sqrt(X**2 + Y**2) Z = jn(0,R) # Create 3D surface plo

Raising a Figure Window to the Foreground

This post describes a utility function that will raise a plot window to the foreground of your screen. The function will only work with the Qt graphics backend, so I will start with a brief overview of graphics backends. If you just want to use the function as a black box, you can do the following: Set the Graphics Backend to “Qt” in the Spyder preferences menu. Copy this function into your working directory. Graphics Backends You may have have written a script to produce precisely the data you need, but a lot of processing is required to transform these numbers into a figure. You need to create a plot window, draw a figure inside of it, and manage all of the attributes that control a figure’s appearance: title, axis labels, line widths, colors, tick marks, etc. All of this happens in the background when you type a command like plt.plot(x,y) . A graphics backend is the software that Python uses to physically draw a figure on your computer screen. If you have already import