blob: a92c7ff3ad15cd65366395d6d3d2a8dfa2f3aac6 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002
Guido van Rossum02455691997-07-17 16:21:52 +00003% Things to do:
4% Add a section on file I/O
5% Write a chapter entitled ``Some Useful Modules''
6% --regex, math+cmath
7% Should really move the Python startup file info to an appendix
Guido van Rossum02455691997-07-17 16:21:52 +00008
Guido van Rossumdccc2981997-12-30 04:40:25 +00009\title{Python Tutorial}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010
Guido van Rossum16cd7f91994-10-06 10:29:26 +000011\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +000012
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000013\begin{document}
14
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000015\maketitle
16
Guido van Rossum16cd7f91994-10-06 10:29:26 +000017\input{copyright}
18
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000019\begin{abstract}
20
21\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000022Python is an easy to learn, powerful programming language. It has
23efficient high-level data structures and a simple but effective
24approach to object-oriented programming. Python's elegant syntax and
25dynamic typing, together with its interpreted nature, make it an ideal
26language for scripting and rapid application development in many areas
27on most platforms.
28
29The Python interpreter and the extensive standard library are freely
30available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000031Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000032distributed. The same site also contains distributions of and
33pointers to many free third party Python modules, programs and tools,
34and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000035
Guido van Rossum4410c751991-06-04 20:22:18 +000036The Python interpreter is easily extended with new functions and data
Fred Drake3f205921998-01-13 18:56:38 +000037types implemented in \C{} or \Cpp{} (or other languages callable from \C{}).
Guido van Rossumdccc2981997-12-30 04:40:25 +000038Python is also suitable as an extension language for customizable
39applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000040
Guido van Rossum6fc178f1991-08-16 09:13:42 +000041This tutorial introduces the reader informally to the basic concepts
42and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000043Python interpreter handy for hands-on experience, but all examples are
44self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000045
Guido van Rossumdccc2981997-12-30 04:40:25 +000046For a description of standard objects and modules, see the
47\emph{Python Library Reference} document. The \emph{Python Reference
48Manual} gives a more formal definition of the language. To write
Fred Drake3f205921998-01-13 18:56:38 +000049extensions in \C{} or \Cpp{}, read the \emph{Extending and Embedding} and
50\emph{Python/\C{} API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000051Python in depth.
52
53This tutorial does not attempt to be comprehensive and cover every
54single feature, or even every commonly used feature. Instead, it
55introduces many of Python's most noteworthy features, and will give
56you a good idea of the language's flavor and style. After reading it,
57you will be able to read and write Python modules and programs, and
58you will be ready to learn more about the various Python library
59modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000060
61\end{abstract}
62
Fred Drake4d4f9e71998-01-13 22:25:02 +000063\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000064
Guido van Rossum5e0759d1992-08-07 16:06:24 +000065
Guido van Rossum6fc178f1991-08-16 09:13:42 +000066\chapter{Whetting Your Appetite}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000067
Fred Drake6c2176e1998-02-26 21:47:54 +000068%\section{Introduction}
69\label{intro}
Guido van Rossum3a26dd81996-10-24 22:12:48 +000070
Guido van Rossum6fc178f1991-08-16 09:13:42 +000071If you ever wrote a large shell script, you probably know this
72feeling: you'd love to add yet another feature, but it's already so
73slow, and so big, and so complicated; or the feature involves a system
Fred Drake3f205921998-01-13 18:56:38 +000074call or other function that is only accessible from \C{} \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000075the problem at hand isn't serious enough to warrant rewriting the
Fred Drake3f205921998-01-13 18:56:38 +000076script in \C{}; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000077other data types (like sorted lists of file names) that are easy in
Fred Drake3f205921998-01-13 18:56:38 +000078the shell but lots of work to implement in \C{}, or perhaps you're not
79sufficiently familiar with \C{}.
Guido van Rossum02455691997-07-17 16:21:52 +000080
Fred Drake3f205921998-01-13 18:56:38 +000081Another situation: perhaps you have to work with several \C{} libraries,
82and the usual \C{} write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000083need to develop software more quickly. Possibly perhaps you've
84written a program that could use an extension language, and you don't
85want to design a language, write and debug an interpreter for it, then
86tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000087
Guido van Rossum6fc178f1991-08-16 09:13:42 +000088In such cases, Python may be just the language for you. Python is
89simple to use, but it is a real programming language, offering much
90more structure and support for large programs than the shell has. On
Fred Drake3f205921998-01-13 18:56:38 +000091the other hand, it also offers much more error checking than \C{}, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000092being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000093built in, such as flexible arrays and dictionaries that would cost you
Fred Drake3f205921998-01-13 18:56:38 +000094days to implement efficiently in \C{}. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000095types Python is applicable to a much larger problem domain than
96\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
97in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000098
Guido van Rossum6fc178f1991-08-16 09:13:42 +000099Python allows you to split up your program in modules that can be
100reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000101standard modules that you can use as the basis of your programs --- or
102as examples to start learning to program in Python. There are also
103built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000104sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000105
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000106Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000107during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000108necessary. The interpreter can be used interactively, which makes it
109easy to experiment with features of the language, to write throw-away
110programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000111It is also a handy desk calculator.
112
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000113Python allows writing very compact and readable programs. Programs
Fred Drake3f205921998-01-13 18:56:38 +0000114written in Python are typically much shorter than equivalent \C{}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000115programs, for several reasons:
116\begin{itemize}
117\item
118the high-level data types allow you to express complex operations in a
119single statement;
120\item
121statement grouping is done by indentation instead of begin/end
122brackets;
123\item
124no variable or argument declarations are necessary.
125\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000126
Fred Drake3f205921998-01-13 18:56:38 +0000127Python is \emph{extensible}: if you know how to program in \C{} it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000128to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000129perform critical operations at maximum speed, or to link Python
130programs to libraries that may only be available in binary form (such
131as a vendor-specific graphics library). Once you are really hooked,
Fred Drake3f205921998-01-13 18:56:38 +0000132you can link the Python interpreter into an application written in \C{}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000133and use it as an extension or command language for that application.
134
Guido van Rossum02455691997-07-17 16:21:52 +0000135By the way, the language is named after the BBC show ``Monty Python's
136Flying Circus'' and has nothing to do with nasty reptiles. Making
137references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000138it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000139
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000140\section{Where From Here}
Fred Drake6c2176e1998-02-26 21:47:54 +0000141\label{where}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000142
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000143Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000144in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000145using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000146
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000147In the next chapter, the mechanics of using the interpreter are
148explained. This is rather mundane information, but essential for
149trying out the examples shown later.
150
Guido van Rossum4410c751991-06-04 20:22:18 +0000151The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000152language and system though examples, beginning with simple
153expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000154and finally touching upon advanced concepts like exceptions
155and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000156
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000157\chapter{Using the Python Interpreter}
Fred Drake6c2176e1998-02-26 21:47:54 +0000158\label{using}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000159
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000160\section{Invoking the Interpreter}
Fred Drake6c2176e1998-02-26 21:47:54 +0000161\label{invoking}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000162
Fred Drakeeee08cd1997-12-04 15:43:15 +0000163The Python interpreter is usually installed as \file{/usr/local/bin/python}
164on those machines where it is available; putting \file{/usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000165your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000166typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000167
Fred Drake8842e861998-02-13 07:16:30 +0000168\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000169python
Fred Drake8842e861998-02-13 07:16:30 +0000170\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000171
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000172to the shell. Since the choice of the directory where the interpreter
173lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000174your local Python guru or system administrator. (E.g.,
175\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000176
Guido van Rossum02455691997-07-17 16:21:52 +0000177Typing an EOF character (Control-D on \UNIX{}, Control-Z or F6 on DOS
178or Windows) at the primary prompt causes the interpreter to exit with
179a zero exit status. If that doesn't work, you can exit the
Fred Drake8842e861998-02-13 07:16:30 +0000180interpreter by typing the following commands: \samp{import sys;
Guido van Rossum02455691997-07-17 16:21:52 +0000181sys.exit()}.
182
183The interpreter's line-editing features usually aren't very
Fred Drake3f205921998-01-13 18:56:38 +0000184sophisticated. On \UNIX{}, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000185enabled support for the GNU readline library, which adds more
186elaborate interactive editing and history features. Perhaps the
187quickest check to see whether command line editing is supported is
188typing Control-P to the first Python prompt you get. If it beeps, you
189have command line editing; see Appendix A for an introduction to the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000190keys. If nothing appears to happen, or if \code{\^P} is echoed,
Guido van Rossum02455691997-07-17 16:21:52 +0000191command line editing isn't available; you'll only be able to use
192backspace to remove characters from the current line.
193
Fred Drake6dc2aae1996-12-13 21:56:03 +0000194The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000195with standard input connected to a tty device, it reads and executes
196commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000197a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000198that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000199
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000200A third way of starting the interpreter is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000201\samp{python -c command [arg] ...}, which
202executes the statement(s) in \code{command}, analogous to the shell's
203\code{-c} option. Since Python statements often contain spaces or other
204characters that are special to the shell, it is best to quote
205\code{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000206
Fred Drakeeee08cd1997-12-04 15:43:15 +0000207Note that there is a difference between \samp{python file} and
208\samp{python <file}. In the latter case, input requests from the
209program, such as calls to \code{input()} and \code{raw_input()}, are
210satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000211until the end by the parser before the program starts executing, the
212program will encounter EOF immediately. In the former case (which is
213usually what you want) they are satisfied from whatever file or device
214is connected to standard input of the Python interpreter.
215
Guido van Rossumb2c65561993-05-12 08:53:36 +0000216When a script file is used, it is sometimes useful to be able to run
217the script and enter interactive mode afterwards. This can be done by
Fred Drakeeee08cd1997-12-04 15:43:15 +0000218passing \code{-i} before the script. (This does not work if the script
Guido van Rossumb2c65561993-05-12 08:53:36 +0000219is read from standard input, for the same reason as explained in the
220previous paragraph.)
221
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000222\subsection{Argument Passing}
Fred Drake6c2176e1998-02-26 21:47:54 +0000223\label{argPassing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000224
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000225When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000226arguments thereafter are passed to the script in the variable
227\code{sys.argv}, which is a list of strings. Its length is at least
228one; when no script and no arguments are given, \code{sys.argv[0]} is
229an empty string. When the script name is given as \code{'-'} (meaning
230standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c
231command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options
232found after \code{-c command} are not consumed by the Python
233interpreter's option processing but left in \code{sys.argv} for the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000234command to handle.
235
236\subsection{Interactive Mode}
Fred Drake6c2176e1998-02-26 21:47:54 +0000237\label{interactive}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000238
Guido van Rossumdd010801991-06-07 14:31:11 +0000239When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000240\emph{interactive mode}. In this mode it prompts for the next command
241with the \emph{primary prompt}, usually three greater-than signs
Fred Drake8842e861998-02-13 07:16:30 +0000242(\samp{>>> }); for continuation lines it prompts with the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000243\emph{secondary prompt},
Fred Drake8842e861998-02-13 07:16:30 +0000244by default three dots (\samp{... }).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000245
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000246The interpreter prints a welcome message stating its version number
247and a copyright notice before printing the first prompt, e.g.:
248
Fred Drake8842e861998-02-13 07:16:30 +0000249\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000250python
Fred Drakeeee08cd1997-12-04 15:43:15 +0000251Python 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5
252Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000253>>>
Fred Drake8842e861998-02-13 07:16:30 +0000254\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000255
256\section{The Interpreter and its Environment}
Fred Drake6c2176e1998-02-26 21:47:54 +0000257\label{interp}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000258
259\subsection{Error Handling}
Fred Drake6c2176e1998-02-26 21:47:54 +0000260\label{error}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000261
262When an error occurs, the interpreter prints an error
263message and a stack trace. In interactive mode, it then returns to
264the primary prompt; when input came from a file, it exits with a
265nonzero exit status after printing
Fred Drakeeee08cd1997-12-04 15:43:15 +0000266the stack trace. (Exceptions handled by an \code{except} clause in a
267\code{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000268unconditionally fatal and cause an exit with a nonzero exit; this
269applies to internal inconsistencies and some cases of running out of
270memory. All error messages are written to the standard error stream;
271normal output from the executed commands is written to standard
272output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000273
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000274Typing the interrupt character (usually Control-C or DEL) to the
275primary or secondary prompt cancels the input and returns to the
276primary prompt.%
277\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000278 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000279}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000280Typing an interrupt while a command is executing raises the
281\code{KeyboardInterrupt} exception, which may be handled by a
282\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000283
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000284\subsection{Executable Python scripts}
Fred Drake6c2176e1998-02-26 21:47:54 +0000285\label{scripts}
Guido van Rossum4410c751991-06-04 20:22:18 +0000286
Fred Drake6dc2aae1996-12-13 21:56:03 +0000287On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000288executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000289
Fred Drake8842e861998-02-13 07:16:30 +0000290\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000291#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000292\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000293
Fred Drake391564f1998-04-01 23:11:56 +0000294(assuming that the interpreter is on the user's \envvar{PATH}) at the
295beginning of the script and giving the file an executable mode. The
296\samp{\#!} must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000297
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000298\subsection{The Interactive Startup File}
Fred Drake6c2176e1998-02-26 21:47:54 +0000299\label{startup}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000300
Fred Drake8842e861998-02-13 07:16:30 +0000301% XXX This should probably be dumped in an appendix, since most people
302% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000303
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000304When you use Python interactively, it is frequently handy to have some
305standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000306can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000307\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drakeeee08cd1997-12-04 15:43:15 +0000308commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000309shells.
310
311This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000312commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000313explicit source of commands (which otherwise behaves like an
314interactive session). It is executed in the same name space where
315interactive commands are executed, so that objects that it defines or
316imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000317You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000318this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000319
320If you want to read an additional start-up file from the current
321directory, you can program this in the global start-up file, e.g.
Fred Drake8842e861998-02-13 07:16:30 +0000322\samp{execfile('.pythonrc')}. If you want to use the startup file
323in a script, you must write this explicitly in the script:
324
325\begin{verbatim}
326import os
327execfile(os.environ['PYTHONSTARTUP'])
328\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000329
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000330\chapter{An Informal Introduction to Python}
Fred Drake6c2176e1998-02-26 21:47:54 +0000331\label{informal}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000332
333In the following examples, input and output are distinguished by the
Fred Drake8842e861998-02-13 07:16:30 +0000334presence or absence of prompts (\samp{>>> } and \samp{... }): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000335the example, you must type everything after the prompt, when the
336prompt appears; lines that do not begin with a prompt are output from
337the interpreter.%
Guido van Rossum02455691997-07-17 16:21:52 +0000338%\footnote{
339% I'd prefer to use different fonts to distinguish input
340% from output, but the amount of LaTeX hacking that would require
341% is currently beyond my ability.
342%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000343Note that a secondary prompt on a line by itself in an example means
344you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000345
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000346\section{Using Python as a Calculator}
Fred Drake6c2176e1998-02-26 21:47:54 +0000347\label{calculator}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000348
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000349Let's try some simple Python commands. Start the interpreter and wait
Fred Drake8842e861998-02-13 07:16:30 +0000350for the primary prompt, \samp{>>> }. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000351
352\subsection{Numbers}
Fred Drake6c2176e1998-02-26 21:47:54 +0000353\label{numbers}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000354
355The interpreter acts as a simple calculator: you can type an
356expression at it and it will write the value. Expression syntax is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000357straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/}
Fred Drake3f205921998-01-13 18:56:38 +0000358work just like in most other languages (e.g., Pascal or \C{}); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000359can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000360
Fred Drake8842e861998-02-13 07:16:30 +0000361\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000362>>> 2+2
3634
Guido van Rossum6938f061994-08-01 12:22:53 +0000364>>> # This is a comment
365... 2+2
3664
367>>> 2+2 # and a comment on the same line as code
3684
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000369>>> (50-5*6)/4
3705
Guido van Rossum6938f061994-08-01 12:22:53 +0000371>>> # Integer division returns the floor:
372... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003732
Guido van Rossum6938f061994-08-01 12:22:53 +0000374>>> 7/-3
375-3
Fred Drake8842e861998-02-13 07:16:30 +0000376\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000377
Fred Drake391564f1998-04-01 23:11:56 +0000378Like in \C{}, the equal sign (\character{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000379variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000380
Fred Drake8842e861998-02-13 07:16:30 +0000381\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000382>>> width = 20
383>>> height = 5*9
384>>> width * height
385900
Fred Drake8842e861998-02-13 07:16:30 +0000386\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000387%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000388A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000389
Fred Drake8842e861998-02-13 07:16:30 +0000390\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000391>>> x = y = z = 0 # Zero x, y and z
392>>> x
3930
394>>> y
3950
396>>> z
3970
Fred Drake8842e861998-02-13 07:16:30 +0000398\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000399%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000400There is full support for floating point; operators with mixed type
401operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000402
Fred Drake8842e861998-02-13 07:16:30 +0000403\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000404>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004053.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000406>>> 7.0 / 2
4073.5
Fred Drake8842e861998-02-13 07:16:30 +0000408\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000409%
410Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000411a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
412real component are written as \samp{(\var{real}+\var{imag}j)}, or can
413be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000414
Fred Drake8842e861998-02-13 07:16:30 +0000415\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000416>>> 1j * 1J
417(-1+0j)
418>>> 1j * complex(0,1)
419(-1+0j)
420>>> 3+1j*3
421(3+3j)
422>>> (3+1j)*3
423(9+3j)
424>>> (1+2j)/(1+1j)
425(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000426\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000427%
428Complex numbers are always represented as two floating point numbers,
429the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000430number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000431
Fred Drake8842e861998-02-13 07:16:30 +0000432\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000433>>> a=1.5+0.5j
434>>> a.real
4351.5
436>>> a.imag
4370.5
Fred Drake8842e861998-02-13 07:16:30 +0000438\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000439%
440The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000441(\function{float()}, \function{int()} and \function{long()}) don't
442work for complex numbers --- there is no one correct way to convert a
443complex number to a real number. Use \code{abs(\var{z})} to get its
444magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000445
Fred Drake8842e861998-02-13 07:16:30 +0000446\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000447>>> a=1.5+0.5j
448>>> float(a)
449Traceback (innermost last):
450 File "<stdin>", line 1, in ?
451TypeError: can't convert complex to float; use e.g. abs(z)
452>>> a.real
4531.5
454>>> abs(a)
4551.58113883008
Fred Drake8842e861998-02-13 07:16:30 +0000456\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000457%
458In interactive mode, the last printed expression is assigned to the
459variable \code{_}. This means that when you are using Python as a
460desk calculator, it is somewhat easier to continue calculations, for
461example:
462
463\begin{verbatim}
464>>> tax = 17.5 / 100
465>>> price = 3.50
466>>> price * tax
4670.6125
468>>> price + _
4694.1125
470>>> round(_, 2)
4714.11
472\end{verbatim}
473
474This variable should be treated as read-only by the user. Don't
475explicitly assign a value to it --- you would create an independent
476local variable with the same name masking the built-in variable with
477its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000478
479\subsection{Strings}
Fred Drake6c2176e1998-02-26 21:47:54 +0000480\label{strings}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000481
Guido van Rossum02455691997-07-17 16:21:52 +0000482Besides numbers, Python can also manipulate strings, which can be
483expressed in several ways. They can be enclosed in single quotes or
484double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000485
Fred Drake8842e861998-02-13 07:16:30 +0000486\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000487>>> 'spam eggs'
488'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000489>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000490"doesn't"
491>>> "doesn't"
492"doesn't"
493>>> '"Yes," he said.'
494'"Yes," he said.'
495>>> "\"Yes,\" he said."
496'"Yes," he said.'
497>>> '"Isn\'t," she said.'
498'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000499\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000500
Fred Drake8842e861998-02-13 07:16:30 +0000501String literals can span multiple lines in several ways. Newlines can
502be escaped with backslashes, e.g.:
Guido van Rossum02455691997-07-17 16:21:52 +0000503
504\begin{verbatim}
505hello = "This is a rather long string containing\n\
506several lines of text just as you would do in C.\n\
507 Note that whitespace at the beginning of the line is\
508 significant.\n"
509print hello
510\end{verbatim}
511
512which would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000513
Guido van Rossum02455691997-07-17 16:21:52 +0000514\begin{verbatim}
515This is a rather long string containing
516several lines of text just as you would do in C.
517 Note that whitespace at the beginning of the line is significant.
518\end{verbatim}
519
520Or, strings can be surrounded in a pair of matching triple-quotes:
521\code{"""} or \code {'''}. End of lines do not need to be escaped
522when using triple-quotes, but they will be included in the string.
523
524\begin{verbatim}
525print """
526Usage: thingy [OPTIONS]
527 -h Display this usage message
528 -H hostname Hostname to connect to
529"""
530\end{verbatim}
531
532produces the following output:
533
Fred Drake8842e861998-02-13 07:16:30 +0000534\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000535Usage: thingy [OPTIONS]
536 -h Display this usage message
537 -H hostname Hostname to connect to
Fred Drake8842e861998-02-13 07:16:30 +0000538\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000539
Guido van Rossum02455691997-07-17 16:21:52 +0000540The interpreter prints the result of string operations in the same way
541as they are typed for input: inside quotes, and with quotes and other
542funny characters escaped by backslashes, to show the precise
543value. The string is enclosed in double quotes if the string contains
544a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000545quotes. (The \keyword{print} statement, described later, can be used
546to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000547
Fred Drakeeee08cd1997-12-04 15:43:15 +0000548Strings can be concatenated (glued together) with the \code{+}
549operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000550
Fred Drake8842e861998-02-13 07:16:30 +0000551\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000552>>> word = 'Help' + 'A'
553>>> word
554'HelpA'
555>>> '<' + word*5 + '>'
556'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000557\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000558
Guido van Rossum02455691997-07-17 16:21:52 +0000559Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000560the first line above could also have been written \samp{word = 'Help'
Guido van Rossum02455691997-07-17 16:21:52 +0000561'A'}; this only works with two literals, not with arbitrary string expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000562
Fred Drake3f205921998-01-13 18:56:38 +0000563Strings can be subscripted (indexed); like in \C{}, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000564of a string has subscript (index) 0. There is no separate character
565type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000566substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000567separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000568
Fred Drake8842e861998-02-13 07:16:30 +0000569\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000570>>> word[4]
571'A'
572>>> word[0:2]
573'He'
574>>> word[2:4]
575'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000576\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000577
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000578Slice indices have useful defaults; an omitted first index defaults to
579zero, an omitted second index defaults to the size of the string being
580sliced.
581
Fred Drake8842e861998-02-13 07:16:30 +0000582\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000583>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000584'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000585>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000586'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000587\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000588
Fred Drakeeee08cd1997-12-04 15:43:15 +0000589Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
590equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000591
Fred Drake8842e861998-02-13 07:16:30 +0000592\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000593>>> word[:2] + word[2:]
594'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000595>>> word[:3] + word[3:]
596'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000597\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000598
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000599Degenerate slice indices are handled gracefully: an index that is too
600large is replaced by the string size, an upper bound smaller than the
601lower bound returns an empty string.
602
Fred Drake8842e861998-02-13 07:16:30 +0000603\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000604>>> word[1:100]
605'elpA'
606>>> word[10:]
607''
608>>> word[2:1]
609''
Fred Drake8842e861998-02-13 07:16:30 +0000610\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000611
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000612Indices may be negative numbers, to start counting from the right.
613For example:
614
Fred Drake8842e861998-02-13 07:16:30 +0000615\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000616>>> word[-1] # The last character
617'A'
618>>> word[-2] # The last-but-one character
619'p'
620>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000621'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000622>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000623'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000624\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000625
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000626But note that -0 is really the same as 0, so it does not count from
627the right!
628
Fred Drake8842e861998-02-13 07:16:30 +0000629\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000630>>> word[-0] # (since -0 equals 0)
631'H'
Fred Drake8842e861998-02-13 07:16:30 +0000632\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000633
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000634Out-of-range negative slice indices are truncated, but don't try this
635for single-element (non-slice) indices:
636
Fred Drake8842e861998-02-13 07:16:30 +0000637\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000638>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000639'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000640>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000641Traceback (innermost last):
642 File "<stdin>", line 1
643IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000644\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000645
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000646The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000647pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000648character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000649string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000650
Fred Drake8842e861998-02-13 07:16:30 +0000651\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000652 +---+---+---+---+---+
653 | H | e | l | p | A |
654 +---+---+---+---+---+
655 0 1 2 3 4 5
656-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000657\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000658
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000659The first row of numbers gives the position of the indices 0...5 in
660the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000661The slice from \var{i} to \var{j} consists of all characters between
662the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000663
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000664For nonnegative indices, the length of a slice is the difference of
665the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000666\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000667
Fred Drake8842e861998-02-13 07:16:30 +0000668The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000669
Fred Drake8842e861998-02-13 07:16:30 +0000670\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000671>>> s = 'supercalifragilisticexpialidocious'
672>>> len(s)
67334
Fred Drake8842e861998-02-13 07:16:30 +0000674\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000675
676\subsection{Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +0000677\label{lists}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000678
Fred Drakeeee08cd1997-12-04 15:43:15 +0000679Python knows a number of \emph{compound} data types, used to group
680together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000681can be written as a list of comma-separated values (items) between
682square brackets. List items need not all have the same type.
683
Fred Drake8842e861998-02-13 07:16:30 +0000684\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000685>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000686>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000687['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000688\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000689
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000690Like string indices, list indices start at 0, and lists can be sliced,
691concatenated and so on:
692
Fred Drake8842e861998-02-13 07:16:30 +0000693\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000694>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000695'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000696>>> a[3]
6971234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000698>>> a[-2]
699100
700>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000701['eggs', 100]
702>>> a[:2] + ['bacon', 2*2]
703['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000704>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000705['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000706\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000707
Fred Drakeeee08cd1997-12-04 15:43:15 +0000708Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000709individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000710
Fred Drake8842e861998-02-13 07:16:30 +0000711\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000712>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000713['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000714>>> a[2] = a[2] + 23
715>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000716['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000717\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000718
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000719Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000720of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000721
Fred Drake8842e861998-02-13 07:16:30 +0000722\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000723>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000724... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000725>>> a
726[1, 12, 123, 1234]
727>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000728... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000729>>> a
730[123, 1234]
731>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000732... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000733>>> a
734[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000735>>> a[:0] = a # Insert (a copy of) itself at the beginning
736>>> a
737[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000738\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000739
Fred Drake8842e861998-02-13 07:16:30 +0000740The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000741
Fred Drake8842e861998-02-13 07:16:30 +0000742\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000743>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007448
Fred Drake8842e861998-02-13 07:16:30 +0000745\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000746
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000747It is possible to nest lists (create lists containing other lists),
748for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000749
Fred Drake8842e861998-02-13 07:16:30 +0000750\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000751>>> q = [2, 3]
752>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000753>>> len(p)
7543
755>>> p[1]
756[2, 3]
757>>> p[1][0]
7582
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000759>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000760>>> p
761[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000762>>> q
763[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000764\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000765
Fred Drakeeee08cd1997-12-04 15:43:15 +0000766Note that in the last example, \code{p[1]} and \code{q} really refer to
767the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000768
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000769\section{First Steps Towards Programming}
Fred Drake6c2176e1998-02-26 21:47:54 +0000770\label{firstSteps}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000771
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000772Of course, we can use Python for more complicated tasks than adding
773two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000774subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000775
Fred Drake8842e861998-02-13 07:16:30 +0000776\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000777>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000778... # the sum of two elements defines the next
779... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000780>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000781... print b
782... a, b = b, a+b
783...
7841
7851
7862
7873
7885
7898
Fred Drake8842e861998-02-13 07:16:30 +0000790\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000791
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000792This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000793
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000794\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000795
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000796\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000797The first line contains a \emph{multiple assignment}: the variables
798\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000799last line this is used again, demonstrating that the expressions on
800the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000801assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000802
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000803\item
Fred Drake8842e861998-02-13 07:16:30 +0000804The \keyword{while} loop executes as long as the condition (here:
805\code{b < 10}) remains true. In Python, like in \C{}, any non-zero
806integer value is true; zero is false. The condition may also be a
807string or list value, in fact any sequence; anything with a non-zero
808length is true, empty sequences are false. The test used in the
809example is a simple comparison. The standard comparison operators are
810written the same as in \C{}: \code{<}, \code{>}, \code{==}, \code{<=},
811\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000812
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000813\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000814The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000815way of grouping statements. Python does not (yet!) provide an
816intelligent input line editing facility, so you have to type a tab or
817space(s) for each indented line. In practice you will prepare more
818complicated input for Python with a text editor; most text editors have
819an auto-indent facility. When a compound statement is entered
820interactively, it must be followed by a blank line to indicate
821completion (since the parser cannot guess when you have typed the last
822line).
823
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000824\item
Fred Drake8842e861998-02-13 07:16:30 +0000825The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000826given. It differs from just writing the expression you want to write
827(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000828multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000829and a space is inserted between items, so you can format things nicely,
830like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000831
Fred Drake8842e861998-02-13 07:16:30 +0000832\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000833>>> i = 256*256
834>>> print 'The value of i is', i
835The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000836\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000837
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000838A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000839
Fred Drake8842e861998-02-13 07:16:30 +0000840\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000841>>> a, b = 0, 1
842>>> while b < 1000:
843... print b,
844... a, b = b, a+b
845...
8461 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000847\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000848
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000849Note that the interpreter inserts a newline before it prints the next
850prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000851
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000852\end{itemize}
853
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000854
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000855\chapter{More Control Flow Tools}
Fred Drake6c2176e1998-02-26 21:47:54 +0000856\label{moreControl}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000857
Fred Drake8842e861998-02-13 07:16:30 +0000858Besides the \keyword{while} statement just introduced, Python knows
859the usual control flow statements known from other languages, with
860some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000861
Fred Drake391564f1998-04-01 23:11:56 +0000862\section{\keyword{if} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +0000863\label{if}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000864
Fred Drake8842e861998-02-13 07:16:30 +0000865Perhaps the most well-known statement type is the \keyword{if}
866statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000867
Fred Drake8842e861998-02-13 07:16:30 +0000868\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000869>>> if x < 0:
870... x = 0
871... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000872... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000873... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000874... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000875... print 'Single'
876... else:
877... print 'More'
878...
Fred Drake8842e861998-02-13 07:16:30 +0000879\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000880
Fred Drake8842e861998-02-13 07:16:30 +0000881There can be zero or more \keyword{elif} parts, and the \keyword{else}
882part is optional. The keyword `\keyword{elif}' is short for `else
883if', and is useful to avoid excessive indentation. An
884\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif}
885\ldots\ sequence is a substitute for the \emph{switch} or
886% ^^^^
887% Weird spacings happen here if the wrapping of the source text
888% gets changed in the wrong way.
889\emph{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000890
Fred Drake391564f1998-04-01 23:11:56 +0000891\section{\keyword{for} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +0000892\label{for}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000893
Fred Drake8842e861998-02-13 07:16:30 +0000894The \keyword{for} statement in Python differs a bit from what you may be
Fred Drake3f205921998-01-13 18:56:38 +0000895used to in \C{} or Pascal. Rather than always iterating over an
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000896arithmetic progression of numbers (like in Pascal), or leaving the user
Fred Drake3f205921998-01-13 18:56:38 +0000897completely free in the iteration test and step (as \C{}), Python's
Fred Drake8842e861998-02-13 07:16:30 +0000898\keyword{for} statement iterates over the items of any sequence (e.g., a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000899list or a string), in the order that they appear in the sequence. For
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000900example (no pun intended):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000901
Fred Drake8842e861998-02-13 07:16:30 +0000902\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000903>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000904... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000905>>> for x in a:
906... print x, len(x)
907...
908cat 3
909window 6
910defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000911\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000912
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000913It is not safe to modify the sequence being iterated over in the loop
914(this can only happen for mutable sequence types, i.e., lists). If
915you need to modify the list you are iterating over, e.g., duplicate
916selected items, you must iterate over a copy. The slice notation
917makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000918
Fred Drake8842e861998-02-13 07:16:30 +0000919\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000920>>> for x in a[:]: # make a slice copy of the entire list
921... if len(x) > 6: a.insert(0, x)
922...
923>>> a
924['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000925\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000926
Fred Drakeeee08cd1997-12-04 15:43:15 +0000927\section{The \sectcode{range()} Function}
Fred Drake6c2176e1998-02-26 21:47:54 +0000928\label{range}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000929
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000930If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000931function \function{range()} comes in handy. It generates lists
932containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000933
Fred Drake8842e861998-02-13 07:16:30 +0000934\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000935>>> range(10)
936[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000937\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000938
Fred Drake8842e861998-02-13 07:16:30 +0000939The given end point is never part of the generated list;
940\code{range(10)} generates a list of 10 values, exactly the legal
941indices for items of a sequence of length 10. It is possible to let
942the range start at another number, or to specify a different increment
943(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000944
Fred Drake8842e861998-02-13 07:16:30 +0000945\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000946>>> range(5, 10)
947[5, 6, 7, 8, 9]
948>>> range(0, 10, 3)
949[0, 3, 6, 9]
950>>> range(-10, -100, -30)
951[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000952\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000953
Fred Drake8842e861998-02-13 07:16:30 +0000954To iterate over the indices of a sequence, combine \function{range()}
955and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000956
Fred Drake8842e861998-02-13 07:16:30 +0000957\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000958>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000959>>> for i in range(len(a)):
960... print i, a[i]
961...
9620 Mary
9631 had
9642 a
9653 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009664 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000967\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000968
Fred Drake391564f1998-04-01 23:11:56 +0000969\section{\keyword{break} and \keyword{continue} Statements, and
970 \keyword{else} Clauses on Loops}
Fred Drake6c2176e1998-02-26 21:47:54 +0000971\label{break}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000972
Fred Drake8842e861998-02-13 07:16:30 +0000973The \keyword{break} statement, like in \C{}, breaks out of the smallest
974enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000975
Fred Drake8842e861998-02-13 07:16:30 +0000976The \keyword{continue} statement, also borrowed from \C{}, continues
977with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000978
Fred Drake8842e861998-02-13 07:16:30 +0000979Loop statements may have an \code{else} clause; it is executed when
980the loop terminates through exhaustion of the list (with
981\keyword{for}) or when the condition becomes false (with
982\keyword{while}), but not when the loop is terminated by a
983\keyword{break} statement. This is exemplified by the following loop,
984which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000985
Fred Drake8842e861998-02-13 07:16:30 +0000986\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000987>>> for n in range(2, 10):
988... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000989... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000990... print n, 'equals', x, '*', n/x
991... break
992... else:
993... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000994...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00009952 is a prime number
9963 is a prime number
9974 equals 2 * 2
9985 is a prime number
9996 equals 2 * 3
10007 is a prime number
10018 equals 2 * 4
10029 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +00001003\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001004
Fred Drake391564f1998-04-01 23:11:56 +00001005\section{\keyword{pass} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +00001006\label{pass}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001007
Fred Drake8842e861998-02-13 07:16:30 +00001008The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001009It can be used when a statement is required syntactically but the
1010program requires no action.
1011For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001012
Fred Drake8842e861998-02-13 07:16:30 +00001013\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001014>>> while 1:
1015... pass # Busy-wait for keyboard interrupt
1016...
Fred Drake8842e861998-02-13 07:16:30 +00001017\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001018
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001019\section{Defining Functions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001020\label{functions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001021
1022We can create a function that writes the Fibonacci series to an
1023arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001024
Fred Drake8842e861998-02-13 07:16:30 +00001025\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001026>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001027... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001028... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001029... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001030... print b,
1031... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001032...
1033>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001034... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010351 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001036\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001037
Fred Drake8842e861998-02-13 07:16:30 +00001038The keyword \keyword{def} introduces a function \emph{definition}. It
1039must be followed by the function name and the parenthesized list of
1040formal parameters. The statements that form the body of the function
1041start at the next line, indented by a tab stop. The first statement
1042of the function body can optionally be a string literal; this string
1043literal is the function's documentation string, or \dfn{docstring}.
1044There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001045documentation, or to let the user interactively browse through code;
1046it's good practice to include docstrings in code that you write, so
1047try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001048
Fred Drakeeee08cd1997-12-04 15:43:15 +00001049The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001050for the local variables of the function. More precisely, all variable
1051assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001052whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001053in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001054Thus, global variables cannot be directly assigned a value within a
1055function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001056they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001057
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001058The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001059the local symbol table of the called function when it is called; thus,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001060arguments are passed using \emph{call by value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001061\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001062 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001063 description, since if a mutable object is passed, the caller
1064 will see any changes the callee makes to it (e.g., items
1065 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001066}
1067When a function calls another function, a new local symbol table is
1068created for that call.
1069
Fred Drake8842e861998-02-13 07:16:30 +00001070A function definition introduces the function name in the current
1071symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001072has a type that is recognized by the interpreter as a user-defined
1073function. This value can be assigned to another name which can then
1074also be used as a function. This serves as a general renaming
1075mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001076
Fred Drake8842e861998-02-13 07:16:30 +00001077\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001078>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001079<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001080>>> f = fib
1081>>> f(100)
10821 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001083\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001084
Fred Drakeeee08cd1997-12-04 15:43:15 +00001085You might object that \code{fib} is not a function but a procedure. In
Fred Drake3f205921998-01-13 18:56:38 +00001086Python, like in \C{}, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001087value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001088albeit a rather boring one. This value is called \code{None} (it's a
1089built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001090the interpreter if it would be the only value written. You can see it
1091if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001092
Fred Drake8842e861998-02-13 07:16:30 +00001093\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001094>>> print fib(0)
1095None
Fred Drake8842e861998-02-13 07:16:30 +00001096\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001097
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001098It is simple to write a function that returns a list of the numbers of
1099the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001100
Fred Drake8842e861998-02-13 07:16:30 +00001101\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001102>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001103... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001104... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001105... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001106... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001107... result.append(b) # see below
1108... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001109... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001110...
1111>>> f100 = fib2(100) # call it
1112>>> f100 # write the result
1113[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001114\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001115%
Guido van Rossum4410c751991-06-04 20:22:18 +00001116This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001117
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001118\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001119
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001120\item
Fred Drake8842e861998-02-13 07:16:30 +00001121The \keyword{return} statement returns with a value from a function.
1122\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001123the middle of a procedure (falling off the end also returns from a
1124procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001125
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001126\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001127The statement \code{result.append(b)} calls a \emph{method} of the list
1128object \code{result}. A method is a function that `belongs' to an
1129object and is named \code{obj.methodname}, where \code{obj} is some
1130object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001131of a method that is defined by the object's type. Different types
1132define different methods. Methods of different types may have the
1133same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001134own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001135in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001136The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001137list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001138example it is equivalent to \samp{result = result + [b]}, but more
1139efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001140
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001141\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001142
Guido van Rossum02455691997-07-17 16:21:52 +00001143\section{More on Defining Functions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001144\label{defining}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001145
Guido van Rossum02455691997-07-17 16:21:52 +00001146It is also possible to define functions with a variable number of
1147arguments. There are three forms, which can be combined.
1148
1149\subsection{Default Argument Values}
Fred Drake6c2176e1998-02-26 21:47:54 +00001150\label{defaultArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001151
1152The most useful form is to specify a default value for one or more
1153arguments. This creates a function that can be called with fewer
1154arguments than it is defined, e.g.
1155
1156\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001157def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1158 while 1:
1159 ok = raw_input(prompt)
1160 if ok in ('y', 'ye', 'yes'): return 1
1161 if ok in ('n', 'no', 'nop', 'nope'): return 0
1162 retries = retries - 1
1163 if retries < 0: raise IOError, 'refusenik user'
1164 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001165\end{verbatim}
1166
1167This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001168\code{ask_ok('Do you really want to quit?')} or like this:
1169\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001170
1171The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001172in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001173
1174\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001175i = 5
1176def f(arg = i): print arg
1177i = 6
1178f()
Guido van Rossum02455691997-07-17 16:21:52 +00001179\end{verbatim}
1180
Fred Drakeeee08cd1997-12-04 15:43:15 +00001181will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001182
1183\subsection{Keyword Arguments}
Fred Drake6c2176e1998-02-26 21:47:54 +00001184\label{keywordArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001185
1186Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001187keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001188instance, the following function:
1189
1190\begin{verbatim}
1191def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1192 print "-- This parrot wouldn't", action,
1193 print "if you put", voltage, "Volts through it."
1194 print "-- Lovely plumage, the", type
1195 print "-- It's", state, "!"
1196\end{verbatim}
1197
1198could be called in any of the following ways:
1199
1200\begin{verbatim}
1201parrot(1000)
1202parrot(action = 'VOOOOOM', voltage = 1000000)
1203parrot('a thousand', state = 'pushing up the daisies')
1204parrot('a million', 'bereft of life', 'jump')
1205\end{verbatim}
1206
1207but the following calls would all be invalid:
1208
1209\begin{verbatim}
1210parrot() # required argument missing
1211parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1212parrot(110, voltage=220) # duplicate value for argument
1213parrot(actor='John Cleese') # unknown keyword
1214\end{verbatim}
1215
1216In general, an argument list must have any positional arguments
1217followed by any keyword arguments, where the keywords must be chosen
1218from the formal parameter names. It's not important whether a formal
1219parameter has a default value or not. No argument must receive a
1220value more than once --- formal parameter names corresponding to
1221positional arguments cannot be used as keywords in the same calls.
1222
1223When a final formal parameter of the form \code{**\var{name}} is
1224present, it receives a dictionary containing all keyword arguments
1225whose keyword doesn't correspond to a formal parameter. This may be
1226combined with a formal parameter of the form \code{*\var{name}}
1227(described in the next subsection) which receives a tuple containing
1228the positional arguments beyond the formal parameter list.
1229(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1230example, if we define a function like this:
1231
1232\begin{verbatim}
1233def cheeseshop(kind, *arguments, **keywords):
1234 print "-- Do you have any", kind, '?'
1235 print "-- I'm sorry, we're all out of", kind
1236 for arg in arguments: print arg
1237 print '-'*40
1238 for kw in keywords.keys(): print kw, ':', keywords[kw]
1239\end{verbatim}
1240
1241It could be called like this:
1242
1243\begin{verbatim}
1244cheeseshop('Limburger', "It's very runny, sir.",
1245 "It's really very, VERY runny, sir.",
1246 client='John Cleese',
1247 shopkeeper='Michael Palin',
1248 sketch='Cheese Shop Sketch')
1249\end{verbatim}
1250
1251and of course it would print:
1252
1253\begin{verbatim}
1254-- Do you have any Limburger ?
1255-- I'm sorry, we're all out of Limburger
1256It's very runny, sir.
1257It's really very, VERY runny, sir.
1258----------------------------------------
1259client : John Cleese
1260shopkeeper : Michael Palin
1261sketch : Cheese Shop Sketch
1262\end{verbatim}
1263
1264\subsection{Arbitrary Argument Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +00001265\label{arbitraryArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001266
1267Finally, the least frequently used option is to specify that a
1268function can be called with an arbitrary number of arguments. These
1269arguments will be wrapped up in a tuple. Before the variable number
1270of arguments, zero or more normal arguments may occur.
1271
1272\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001273def fprintf(file, format, *args):
1274 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001275\end{verbatim}
1276
1277\chapter{Data Structures}
Fred Drake6c2176e1998-02-26 21:47:54 +00001278\label{structures}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001279
1280This chapter describes some things you've learned about already in
1281more detail, and adds some new things as well.
1282
1283\section{More on Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +00001284\label{moreLists}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001285
1286The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001287of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001288
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001289\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001290
Fred Drakeeee08cd1997-12-04 15:43:15 +00001291\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001292Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001293the element before which to insert, so \code{a.insert(0, x)} inserts at
1294the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1295\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001296
Fred Drakeeee08cd1997-12-04 15:43:15 +00001297\item[\code{append(x)}]
1298Equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001299
Fred Drakeeee08cd1997-12-04 15:43:15 +00001300\item[\code{index(x)}]
1301Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001302It is an error if there is no such item.
1303
Fred Drakeeee08cd1997-12-04 15:43:15 +00001304\item[\code{remove(x)}]
1305Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001306It is an error if there is no such item.
1307
Fred Drakeeee08cd1997-12-04 15:43:15 +00001308\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001309Sort the items of the list, in place.
1310
Fred Drakeeee08cd1997-12-04 15:43:15 +00001311\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001312Reverse the elements of the list, in place.
1313
Fred Drakeeee08cd1997-12-04 15:43:15 +00001314\item[\code{count(x)}]
1315Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001316
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001317\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001318
1319An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001320
Fred Drake8842e861998-02-13 07:16:30 +00001321\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001322>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001323>>> print a.count(333), a.count(66.6), a.count('x')
13242 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001325>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001326>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001327>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001328[66.6, 333, -1, 333, 1, 1234.5, 333]
1329>>> a.index(333)
13301
1331>>> a.remove(333)
1332>>> a
1333[66.6, -1, 333, 1, 1234.5, 333]
1334>>> a.reverse()
1335>>> a
1336[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001337>>> a.sort()
1338>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001339[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001340\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001341
Guido van Rossum02455691997-07-17 16:21:52 +00001342\subsection{Functional Programming Tools}
Fred Drake6c2176e1998-02-26 21:47:54 +00001343\label{functional}
Guido van Rossum02455691997-07-17 16:21:52 +00001344
1345There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001346lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001347
Fred Drake8842e861998-02-13 07:16:30 +00001348\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1349the same type, if possible) consisting of those items from the
1350sequence for which \code{\var{function}(\var{item})} is true. For
1351example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001352
1353\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001354>>> def f(x): return x%2 != 0 and x%3 != 0
1355...
1356>>> filter(f, range(2, 25))
1357[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001358\end{verbatim}
1359
Fred Drake8842e861998-02-13 07:16:30 +00001360\samp{map(\var{function}, \var{sequence})} calls
1361\code{\var{function}(\var{item})} for each of the sequence's items and
1362returns a list of the return values. For example, to compute some
1363cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001364
1365\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001366>>> def cube(x): return x*x*x
1367...
1368>>> map(cube, range(1, 11))
1369[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001370\end{verbatim}
1371
1372More than one sequence may be passed; the function must then have as
1373many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001374corresponding item from each sequence (or \code{None} if some sequence
1375is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001376a function returning its argument(s) is substituted.
1377
1378Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001379\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1380turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001381
1382\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001383>>> seq = range(8)
1384>>> def square(x): return x*x
1385...
1386>>> map(None, seq, map(square, seq))
1387[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001388\end{verbatim}
1389
Fred Drake8842e861998-02-13 07:16:30 +00001390\samp{reduce(\var{func}, \var{sequence})} returns a single value
1391constructed by calling the binary function \var{func} on the first two
1392items of the sequence, then on the result and the next item, and so
1393on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001394
1395\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001396>>> def add(x,y): return x+y
1397...
1398>>> reduce(add, range(1, 11))
139955
Guido van Rossum02455691997-07-17 16:21:52 +00001400\end{verbatim}
1401
1402If there's only one item in the sequence, its value is returned; if
1403the sequence is empty, an exception is raised.
1404
1405A third argument can be passed to indicate the starting value. In this
1406case the starting value is returned for an empty sequence, and the
1407function is first applied to the starting value and the first sequence
1408item, then to the result and the next item, and so on. For example,
1409
1410\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001411>>> def sum(seq):
1412... def add(x,y): return x+y
1413... return reduce(add, seq, 0)
1414...
1415>>> sum(range(1, 11))
141655
1417>>> sum([])
14180
Guido van Rossum02455691997-07-17 16:21:52 +00001419\end{verbatim}
1420
Fred Drakeeee08cd1997-12-04 15:43:15 +00001421\section{The \sectcode{del} statement}
Fred Drake6c2176e1998-02-26 21:47:54 +00001422\label{del}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001423
1424There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001425of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001426remove slices from a list (which we did earlier by assignment of an
1427empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001428
Fred Drake8842e861998-02-13 07:16:30 +00001429\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001430>>> a
1431[-1, 1, 66.6, 333, 333, 1234.5]
1432>>> del a[0]
1433>>> a
1434[1, 66.6, 333, 333, 1234.5]
1435>>> del a[2:4]
1436>>> a
1437[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001438\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001439
1440\keyword{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001441
Fred Drake8842e861998-02-13 07:16:30 +00001442\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001443>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001444\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001445
Fred Drakeeee08cd1997-12-04 15:43:15 +00001446Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001447another value is assigned to it). We'll find other uses for
1448\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001449
1450\section{Tuples and Sequences}
Fred Drake6c2176e1998-02-26 21:47:54 +00001451\label{tuples}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001452
1453We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001454indexing and slicing operations. They are two examples of
1455\emph{sequence} data types. Since Python is an evolving language,
1456other sequence data types may be added. There is also another
1457standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001458
1459A tuple consists of a number of values separated by commas, for
1460instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001461
Fred Drake8842e861998-02-13 07:16:30 +00001462\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001463>>> t = 12345, 54321, 'hello!'
1464>>> t[0]
146512345
1466>>> t
1467(12345, 54321, 'hello!')
1468>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001469... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001470>>> u
1471((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001472\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001473
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001474As you see, on output tuples are alway enclosed in parentheses, so
1475that nested tuples are interpreted correctly; they may be input with
1476or without surrounding parentheses, although often parentheses are
1477necessary anyway (if the tuple is part of a larger expression).
1478
1479Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1480from a database, etc. Tuples, like strings, are immutable: it is not
1481possible to assign to the individual items of a tuple (you can
1482simulate much of the same effect with slicing and concatenation,
1483though).
1484
1485A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001486items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001487tuples are constructed by an empty pair of parentheses; a tuple with
1488one item is constructed by following a value with a comma
1489(it is not sufficient to enclose a single value in parentheses).
1490Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001491
Fred Drake8842e861998-02-13 07:16:30 +00001492\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001493>>> empty = ()
1494>>> singleton = 'hello', # <-- note trailing comma
1495>>> len(empty)
14960
1497>>> len(singleton)
14981
1499>>> singleton
1500('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001501\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001502
Fred Drakeeee08cd1997-12-04 15:43:15 +00001503The statement \code{t = 12345, 54321, 'hello!'} is an example of
1504\emph{tuple packing}: the values \code{12345}, \code{54321} and
1505\code{'hello!'} are packed together in a tuple. The reverse operation
1506is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001507
Fred Drake8842e861998-02-13 07:16:30 +00001508\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001509>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001510\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001511
Fred Drakeeee08cd1997-12-04 15:43:15 +00001512This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001513unpacking requires that the list of variables on the left has the same
1514number of elements as the length of the tuple. Note that multiple
1515assignment is really just a combination of tuple packing and tuple
1516unpacking!
1517
Fred Drakeeee08cd1997-12-04 15:43:15 +00001518Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001519unpacking}. This is supported by enclosing the list of variables in
1520square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001521
Fred Drake8842e861998-02-13 07:16:30 +00001522\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001523>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001524>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001525\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001526
1527\section{Dictionaries}
Fred Drake6c2176e1998-02-26 21:47:54 +00001528\label{dictionaries}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001529
Fred Drakeeee08cd1997-12-04 15:43:15 +00001530Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001531Dictionaries are sometimes found in other languages as ``associative
1532memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001533indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001534which can be any non-mutable type; strings and numbers can always be
1535keys. Tuples can be used as keys if they contain only strings,
1536numbers, or tuples. You can't use lists as keys, since lists can be
1537modified in place using their \code{append()} method.
1538
Guido van Rossum6938f061994-08-01 12:22:53 +00001539It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001540\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001541(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001542A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001543Placing a comma-separated list of key:value pairs within the
1544braces adds initial key:value pairs to the dictionary; this is also the
1545way dictionaries are written on output.
1546
1547The main operations on a dictionary are storing a value with some key
1548and extracting the value given the key. It is also possible to delete
1549a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001550with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001551If you store using a key that is already in use, the old value
1552associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001553value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001554
Fred Drakeeee08cd1997-12-04 15:43:15 +00001555The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001556keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001557just apply the \code{sort()} method to the list of keys). To check
1558whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001559method of the dictionary.
1560
1561Here is a small example using a dictionary:
1562
Fred Drake8842e861998-02-13 07:16:30 +00001563\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001564>>> tel = {'jack': 4098, 'sape': 4139}
1565>>> tel['guido'] = 4127
1566>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001567{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001568>>> tel['jack']
15694098
1570>>> del tel['sape']
1571>>> tel['irv'] = 4127
1572>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001573{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001574>>> tel.keys()
1575['guido', 'irv', 'jack']
1576>>> tel.has_key('guido')
15771
Fred Drake8842e861998-02-13 07:16:30 +00001578\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001579
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001580\section{More on Conditions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001581\label{conditions}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001582
Fred Drakeeee08cd1997-12-04 15:43:15 +00001583The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001584contain other operators besides comparisons.
1585
Fred Drakeeee08cd1997-12-04 15:43:15 +00001586The comparison operators \code{in} and \code{not in} check whether a value
1587occurs (does not occur) in a sequence. The operators \code{is} and
1588\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001589only matters for mutable objects like lists. All comparison operators
1590have the same priority, which is lower than that of all numerical
1591operators.
1592
Fred Drakeeee08cd1997-12-04 15:43:15 +00001593Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a}
1594is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001595
Fred Drakeeee08cd1997-12-04 15:43:15 +00001596Comparisons may be combined by the Boolean operators \code{and} and
1597\code{or}, and the outcome of a comparison (or of any other Boolean
1598expression) may be negated with \code{not}. These all have lower
1599priorities than comparison operators again; between them, \code{not} has
1600the highest priority, and \code{or} the lowest, so that
1601\code{A and not B or C} is equivalent to \code{(A and (not B)) or C}. Of
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001602course, parentheses can be used to express the desired composition.
1603
Fred Drakeeee08cd1997-12-04 15:43:15 +00001604The Boolean operators \code{and} and \code{or} are so-called
1605\emph{shortcut} operators: their arguments are evaluated from left to
1606right, and evaluation stops as soon as the outcome is determined.
1607E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1608and B and C} does not evaluate the expression C. In general, the
1609return value of a shortcut operator, when used as a general value and
1610not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001611
1612It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001613expression to a variable. For example,
1614
Fred Drake8842e861998-02-13 07:16:30 +00001615\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001616>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1617>>> non_null = string1 or string2 or string3
1618>>> non_null
1619'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001620\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001621
Fred Drake3f205921998-01-13 18:56:38 +00001622Note that in Python, unlike \C{}, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001623
1624\section{Comparing Sequences and Other Types}
Fred Drake6c2176e1998-02-26 21:47:54 +00001625\label{comparing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001626
1627Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001628sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001629first the first two items are compared, and if they differ this
1630determines the outcome of the comparison; if they are equal, the next
1631two items are compared, and so on, until either sequence is exhausted.
1632If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001633the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001634items of two sequences compare equal, the sequences are considered
1635equal. If one sequence is an initial subsequence of the other, the
1636shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001637strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001638examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001639
Fred Drake8842e861998-02-13 07:16:30 +00001640\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001641(1, 2, 3) < (1, 2, 4)
1642[1, 2, 3] < [1, 2, 4]
1643'ABC' < 'C' < 'Pascal' < 'Python'
1644(1, 2, 3, 4) < (1, 2, 4)
1645(1, 2) < (1, 2, -1)
1646(1, 2, 3) = (1.0, 2.0, 3.0)
1647(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001648\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001649
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001650Note that comparing objects of different types is legal. The outcome
1651is deterministic but arbitrary: the types are ordered by their name.
1652Thus, a list is always smaller than a string, a string is always
1653smaller than a tuple, etc. Mixed numeric types are compared according
1654to their numeric value, so 0 equals 0.0, etc.%
1655\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001656 The rules for comparing objects of different types should
1657 not be relied upon; they may change in a future version of
1658 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001659}
1660
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001661
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001662\chapter{Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001663\label{modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001664
Guido van Rossum4410c751991-06-04 20:22:18 +00001665If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001666definitions you have made (functions and variables) are lost.
1667Therefore, if you want to write a somewhat longer program, you are
1668better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001669and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001670\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001671into several files for easier maintenance. You may also want to use a
1672handy function that you've written in several programs without copying
1673its definition into each program.
1674
Guido van Rossum4410c751991-06-04 20:22:18 +00001675To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001676them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001677Such a file is called a \emph{module}; definitions from a module can be
1678\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001679collection of variables that you have access to in a script
1680executed at the top level
1681and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001682
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001683A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001684file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001685a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001686the global variable \code{__name__}. For instance, use your favorite text
1687editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001688with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001689
Fred Drake8842e861998-02-13 07:16:30 +00001690\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001691# Fibonacci numbers module
1692
1693def fib(n): # write Fibonacci series up to n
1694 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001695 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001696 print b,
1697 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001698
1699def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001700 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001701 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001702 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001703 result.append(b)
1704 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001705 return result
Fred Drake8842e861998-02-13 07:16:30 +00001706\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001707
Guido van Rossum4410c751991-06-04 20:22:18 +00001708Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001709following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001710
Fred Drake8842e861998-02-13 07:16:30 +00001711\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001712>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001713\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001714
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001715This does not enter the names of the functions defined in
Fred Drakeeee08cd1997-12-04 15:43:15 +00001716\code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001717directly in the current symbol table; it only enters the module name
Fred Drakeeee08cd1997-12-04 15:43:15 +00001718\code{fibo}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001719there.
1720Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001721
Fred Drake8842e861998-02-13 07:16:30 +00001722\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001723>>> fibo.fib(1000)
17241 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1725>>> fibo.fib2(100)
1726[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001727>>> fibo.__name__
1728'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001729\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001730%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001731If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001732
Fred Drake8842e861998-02-13 07:16:30 +00001733\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001734>>> fib = fibo.fib
1735>>> fib(500)
17361 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001737\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001738
Guido van Rossum02455691997-07-17 16:21:52 +00001739
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001740\section{More on Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001741\label{moreModules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001742
1743A module can contain executable statements as well as function
1744definitions.
1745These statements are intended to initialize the module.
1746They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001747\emph{first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001748time the module is imported somewhere.%
1749\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001750 In fact function definitions are also `statements' that are
1751 `executed'; the execution enters the function name in the
1752 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001753}
1754
1755Each module has its own private symbol table, which is used as the
1756global symbol table by all functions defined in the module.
1757Thus, the author of a module can use global variables in the module
1758without worrying about accidental clashes with a user's global
1759variables.
1760On the other hand, if you know what you are doing you can touch a
1761module's global variables with the same notation used to refer to its
1762functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001763\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001764
1765Modules can import other modules.
1766It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001767\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001768statements at the beginning of a module (or script, for that matter).
1769The imported module names are placed in the importing module's global
1770symbol table.
1771
1772There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001773\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001774statement that imports names from a module directly into the importing
1775module's symbol table.
1776For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001777
Fred Drake8842e861998-02-13 07:16:30 +00001778\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001779>>> from fibo import fib, fib2
1780>>> fib(500)
17811 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001782\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001783
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001784This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001785in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001786defined).
1787
1788There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001789
Fred Drake8842e861998-02-13 07:16:30 +00001790\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001791>>> from fibo import *
1792>>> fib(500)
17931 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001794\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001795
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001796This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001797(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001798
Guido van Rossum02455691997-07-17 16:21:52 +00001799\subsection{The Module Search Path}
Fred Drake6c2176e1998-02-26 21:47:54 +00001800\label{searchPath}
Guido van Rossum02455691997-07-17 16:21:52 +00001801
Fred Drake391564f1998-04-01 23:11:56 +00001802\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00001803When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001804for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001805and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00001806the environment variable \envvar{PYTHONPATH}. This has the same syntax as
1807the shell variable \envvar{PATH}, i.e., a list of
1808directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001809is not found there, the search continues in an installation-dependent
Fred Drake391564f1998-04-01 23:11:56 +00001810default path; on \UNIX{}, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001811
1812Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001813variable \code{sys.path} which is initialized from the directory
1814containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00001815\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001816Python programs that know what they're doing to modify or replace the
1817module search path. See the section on Standard Modules later.
1818
1819\subsection{``Compiled'' Python files}
1820
1821As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001822use a lot of standard modules, if a file called \file{spam.pyc} exists
1823in the directory where \file{spam.py} is found, this is assumed to
Fred Drake8842e861998-02-13 07:16:30 +00001824contain an already-``compiled'' version of the module \module{spam}.
1825The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001826\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1827ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001828
Fred Drakeeee08cd1997-12-04 15:43:15 +00001829Normally, you don't need to do anything to create the \file{spam.pyc} file.
1830Whenever \file{spam.py} is successfully compiled, an attempt is made to
1831write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001832this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001833completely, the resulting \file{spam.pyc} file will be recognized as
1834invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001835file is platform independent, so a Python module directory can be
1836shared by machines of different architectures. (Tip for experts:
Fred Drake391564f1998-04-01 23:11:56 +00001837the module \module{compileall}\refstmodindex{compileall} creates
1838\file{.pyc} files for all modules.)
Guido van Rossum02455691997-07-17 16:21:52 +00001839
Fred Drake8842e861998-02-13 07:16:30 +00001840% XXX Should optimization with -O be covered here?
Guido van Rossum02455691997-07-17 16:21:52 +00001841
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001842\section{Standard Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001843\label{standardModules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001844
Guido van Rossum4410c751991-06-04 20:22:18 +00001845Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001846document, the \emph{Python Library Reference} (``Library Reference''
1847hereafter). Some modules are built into the interpreter; these
1848provide access to operations that are not part of the core of the
1849language but are nevertheless built in, either for efficiency or to
1850provide access to operating system primitives such as system calls.
1851The set of such modules is a configuration option; e.g., the
1852\module{amoeba} module is only provided on systems that somehow
1853support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00001854attention: \module{sys}\refstmodindex{sys}, which is built into every
1855Python interpreter. The variables \code{sys.ps1} and \code{sys.ps2}
1856define the strings used as primary and secondary prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001857
Fred Drake8842e861998-02-13 07:16:30 +00001858\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001859>>> import sys
1860>>> sys.ps1
1861'>>> '
1862>>> sys.ps2
1863'... '
1864>>> sys.ps1 = 'C> '
1865C> print 'Yuck!'
1866Yuck!
1867C>
Fred Drake8842e861998-02-13 07:16:30 +00001868\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001869
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001870These two variables are only defined if the interpreter is in
1871interactive mode.
1872
1873The variable
Fred Drakeeee08cd1997-12-04 15:43:15 +00001874\code{sys.path}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001875is a list of strings that determine the interpreter's search path for
1876modules.
1877It is initialized to a default path taken from the environment variable
Fred Drake391564f1998-04-01 23:11:56 +00001878\envvar{PYTHONPATH}, or from a built-in default if \envvar{PYTHONPATH}
1879is not set. You can modify it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001880
Fred Drake8842e861998-02-13 07:16:30 +00001881\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001882>>> import sys
1883>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00001884\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001885
Fred Drakeeee08cd1997-12-04 15:43:15 +00001886\section{The \sectcode{dir()} function}
Fred Drake6c2176e1998-02-26 21:47:54 +00001887\label{dir}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001888
Fred Drake8842e861998-02-13 07:16:30 +00001889The built-in function \function{dir()} is used to find out which names
1890a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001891
Fred Drake8842e861998-02-13 07:16:30 +00001892\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001893>>> import fibo, sys
1894>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00001895['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001896>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00001897['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
1898'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
1899'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00001900\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001901
Fred Drake8842e861998-02-13 07:16:30 +00001902Without arguments, \function{dir()} lists the names you have defined
1903currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001904
Fred Drake8842e861998-02-13 07:16:30 +00001905\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001906>>> a = [1, 2, 3, 4, 5]
1907>>> import fibo, sys
1908>>> fib = fibo.fib
1909>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00001910['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00001911\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001912
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001913Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001914
Fred Drake8842e861998-02-13 07:16:30 +00001915\function{dir()} does not list the names of built-in functions and
1916variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00001917standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001918
Fred Drake8842e861998-02-13 07:16:30 +00001919\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00001920>>> import __builtin__
1921>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00001922['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
1923'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
1924'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
1925'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
1926'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
1927'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
1928'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
1929'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
1930'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00001931\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001932
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001933
Guido van Rossum02455691997-07-17 16:21:52 +00001934\chapter{Input and Output}
Fred Drake6c2176e1998-02-26 21:47:54 +00001935\label{io}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001936
Guido van Rossum02455691997-07-17 16:21:52 +00001937There are several ways to present the output of a program; data can be
1938printed in a human-readable form, or written to a file for future use.
1939This chapter will discuss some of the possibilities.
1940
1941\section{Fancier Output Formatting}
Fred Drakeeee08cd1997-12-04 15:43:15 +00001942So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00001943statements} and the \keyword{print} statement. (A third way is using
1944the \method{write()} method of file objects; the standard output file
1945can be referenced as \code{sys.stdout}. See the Library Reference for
1946more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001947
1948Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00001949simply printing space-separated values. There are two ways to format
1950your output; the first way is to do all the string handling yourself;
1951using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00001952lay-out you can imagine. The standard module
1953\module{string}\refstmodindex{string} contains some useful operations
1954for padding strings to a given column width;
Guido van Rossum02455691997-07-17 16:21:52 +00001955these will be discussed shortly. The second way is to use the
1956\code{\%} operator with a string as the left argument. \code{\%}
Fred Drake8842e861998-02-13 07:16:30 +00001957interprets the left argument as a \C{} \cfunction{sprintf()}-style
1958format string to be applied to the right argument, and returns the
1959string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001960
1961One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00001962Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00001963the \function{repr()} function, or just write the value between
1964reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001965
Fred Drake8842e861998-02-13 07:16:30 +00001966\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001967>>> x = 10 * 3.14
1968>>> y = 200*200
1969>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
1970>>> print s
1971The value of x is 31.4, and y is 40000...
1972>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00001973... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00001974>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001975>>> ps
1976'[31.4, 40000]'
1977>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00001978... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001979>>> hellos = `hello`
1980>>> print hellos
1981'hello, world\012'
1982>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00001983... `x, y, ('spam', 'eggs')`
1984"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00001985\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001986
Guido van Rossum6938f061994-08-01 12:22:53 +00001987Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001988
Fred Drake8842e861998-02-13 07:16:30 +00001989\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001990>>> import string
1991>>> for x in range(1, 11):
1992... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
1993... # Note trailing comma on previous line
1994... print string.rjust(`x*x*x`, 4)
1995...
1996 1 1 1
1997 2 4 8
1998 3 9 27
1999 4 16 64
2000 5 25 125
2001 6 36 216
2002 7 49 343
2003 8 64 512
2004 9 81 729
200510 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002006>>> for x in range(1,11):
2007... print '%2d %3d %4d' % (x, x*x, x*x*x)
2008...
2009 1 1 1
2010 2 4 8
2011 3 9 27
2012 4 16 64
2013 5 25 125
2014 6 36 216
2015 7 49 343
2016 8 64 512
2017 9 81 729
201810 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002019\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002020
Fred Drake8842e861998-02-13 07:16:30 +00002021(Note that one space between each column was added by the way
2022\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002023
Fred Drake8842e861998-02-13 07:16:30 +00002024This example demonstrates the function \function{string.rjust()},
2025which right-justifies a string in a field of a given width by padding
2026it with spaces on the left. There are similar functions
2027\function{string.ljust()} and \function{string.center()}. These
2028functions do not write anything, they just return a new string. If
2029the input string is too long, they don't truncate it, but return it
2030unchanged; this will mess up your column lay-out but that's usually
2031better than the alternative, which would be lying about a value. (If
2032you really want truncation you can always add a slice operation, as in
2033\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002034
Fred Drake8842e861998-02-13 07:16:30 +00002035There is another function, \function{string.zfill()}, which pads a
2036numeric string on the left with zeros. It understands about plus and
2037minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002038
Fred Drake8842e861998-02-13 07:16:30 +00002039\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002040>>> string.zfill('12', 5)
2041'00012'
2042>>> string.zfill('-3.14', 7)
2043'-003.14'
2044>>> string.zfill('3.14159265359', 5)
2045'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002046\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002047%
2048Using the \code{\%} operator looks like this:
2049
2050\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002051>>> import math
2052>>> print 'The value of PI is approximately %5.3f.' % math.pi
2053The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002054\end{verbatim}
2055
2056If there is more than one format in the string you pass a tuple as
2057right operand, e.g.
2058
2059\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002060>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2061>>> for name, phone in table.items():
2062... print '%-10s ==> %10d' % (name, phone)
2063...
2064Jack ==> 4098
2065Dcab ==> 8637678
2066Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002067\end{verbatim}
2068
Fred Drake3f205921998-01-13 18:56:38 +00002069Most formats work exactly as in \C{} and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002070type; however, if you don't you get an exception, not a core dump.
2071The \verb\%s\ format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002072not a string object, it is converted to string using the
2073\function{str()} built-in function. Using \code{*} to pass the width
2074or precision in as a separate (integer) argument is supported. The
2075\C{} formats \verb\%n\ and \verb\%p\ are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002076
2077If you have a really long format string that you don't want to split
2078up, it would be nice if you could reference the variables to be
2079formatted by name instead of by position. This can be done by using
Fred Drake3f205921998-01-13 18:56:38 +00002080an extension of \C{} formats using the form \verb\%(name)format\, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002081
2082\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002083>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2084>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2085Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002086\end{verbatim}
2087
2088This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002089\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002090local variables.
2091
2092\section{Reading and Writing Files}
Fred Drake6c2176e1998-02-26 21:47:54 +00002093\label{files}
2094
Guido van Rossum02455691997-07-17 16:21:52 +00002095% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002096\function{open()}\bifuncindex{open} returns a file
2097object\obindex{file}, and is most commonly used with two arguments:
2098\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002099
Fred Drake8842e861998-02-13 07:16:30 +00002100\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002101>>> f=open('/tmp/workfile', 'w')
2102>>> print f
2103<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002104\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002105
Guido van Rossum02455691997-07-17 16:21:52 +00002106The first argument is a string containing the filename. The second
2107argument is another string containing a few characters describing the
2108way in which the file will be used. \var{mode} can be \code{'r'} when
2109the file will only be read, \code{'w'} for only writing (an existing
2110file with the same name will be erased), and \code{'a'} opens the file
2111for appending; any data written to the file is automatically added to
2112the end. \code{'r+'} opens the file for both reading and writing.
2113The \var{mode} argument is optional; \code{'r'} will be assumed if
2114it's omitted.
2115
Fred Drake391564f1998-04-01 23:11:56 +00002116On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00002117mode opens the file in binary mode, so there are also modes like
2118\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2119distinction between text and binary files; the end-of-line characters
2120in text files are automatically altered slightly when data is read or
2121written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002122\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2123\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00002124writing such files. (Note that the precise semantics of text mode on
2125the Macintosh depends on the underlying \C{} library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00002126
2127\subsection{Methods of file objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002128\label{fileMethods}
Guido van Rossum02455691997-07-17 16:21:52 +00002129
2130The rest of the examples in this section will assume that a file
2131object called \code{f} has already been created.
2132
2133To read a file's contents, call \code{f.read(\var{size})}, which reads
2134some quantity of data and returns it as a string. \var{size} is an
2135optional numeric argument. When \var{size} is omitted or negative,
2136the entire contents of the file will be read and returned; it's your
2137problem if the file is twice as large as your machine's memory.
2138Otherwise, at most \var{size} bytes are read and returned. If the end
2139of the file has been reached, \code{f.read()} will return an empty
2140string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002141\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002142>>> f.read()
2143'This is the entire file.\012'
2144>>> f.read()
2145''
Fred Drake8842e861998-02-13 07:16:30 +00002146\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002147
Guido van Rossum02455691997-07-17 16:21:52 +00002148\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002149character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002150omitted on the last line of the file if the file doesn't end in a
2151newline. This makes the return value unambiguous; if
2152\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002153been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002154string containing only a single newline.
2155
Fred Drake8842e861998-02-13 07:16:30 +00002156\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002157>>> f.readline()
2158'This is the first line of the file.\012'
2159>>> f.readline()
2160'Second line of the file\012'
2161>>> f.readline()
2162''
Fred Drake8842e861998-02-13 07:16:30 +00002163\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002164
Fred Drakeeee08cd1997-12-04 15:43:15 +00002165\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002166a list containing all the lines of data in the file.
2167
Fred Drake8842e861998-02-13 07:16:30 +00002168\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002169>>> f.readlines()
2170['This is the first line of the file.\012', 'Second line of the file\012']
Fred Drake8842e861998-02-13 07:16:30 +00002171\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002172
Guido van Rossum02455691997-07-17 16:21:52 +00002173\code{f.write(\var{string})} writes the contents of \var{string} to
2174the file, returning \code{None}.
2175
Fred Drake8842e861998-02-13 07:16:30 +00002176\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002177>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002178\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002179
Guido van Rossum02455691997-07-17 16:21:52 +00002180\code{f.tell()} returns an integer giving the file object's current
2181position in the file, measured in bytes from the beginning of the
2182file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002183\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002184computed from adding \var{offset} to a reference point; the reference
2185point is selected by the \var{from_what} argument. A \var{from_what}
2186value of 0 measures from the beginning of the file, 1 uses the current
2187file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002188\var{from_what} can be omitted and defaults to 0, using the beginning
2189of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002190
Fred Drake8842e861998-02-13 07:16:30 +00002191\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002192>>> f=open('/tmp/workfile', 'r+')
2193>>> f.write('0123456789abcdef')
2194>>> f.seek(5) # Go to the 5th byte in the file
2195>>> f.read(1)
2196'5'
2197>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2198>>> f.read(1)
2199'd'
Fred Drake8842e861998-02-13 07:16:30 +00002200\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002201
Guido van Rossum02455691997-07-17 16:21:52 +00002202When you're done with a file, call \code{f.close()} to close it and
2203free up any system resources taken up by the open file. After calling
2204\code{f.close()}, attempts to use the file object will automatically fail.
2205
Fred Drake8842e861998-02-13 07:16:30 +00002206\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002207>>> f.close()
2208>>> f.read()
2209Traceback (innermost last):
2210 File "<stdin>", line 1, in ?
2211ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002212\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002213
Fred Drake8842e861998-02-13 07:16:30 +00002214File objects have some additional methods, such as \method{isatty()}
2215and \method{truncate()} which are less frequently used; consult the
2216Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002217
Fred Drake391564f1998-04-01 23:11:56 +00002218\subsection{The \module{pickle} module}
Fred Drake6c2176e1998-02-26 21:47:54 +00002219\label{pickle}
Fred Drake391564f1998-04-01 23:11:56 +00002220\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00002221
2222Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002223bit more effort, since the \method{read()} method only returns
2224strings, which will have to be passed to a function like
2225\function{string.atoi()}, which takes a string like \code{'123'} and
2226returns its numeric value 123. However, when you want to save more
2227complex data types like lists, dictionaries, or class instances,
2228things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002229
2230Rather than have users be constantly writing and debugging code to
2231save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002232\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002233any Python object (even some forms of Python code!), and convert it to
2234a string representation; this process is called \dfn{pickling}.
2235Reconstructing the object from the string representation is called
2236\dfn{unpickling}. Between pickling and unpickling, the string
2237representing the object may have been stored in a file or data, or
2238sent over a network connection to some distant machine.
2239
2240If you have an object \code{x}, and a file object \code{f} that's been
2241opened for writing, the simplest way to pickle the object takes only
2242one line of code:
2243
Fred Drake8842e861998-02-13 07:16:30 +00002244\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002245pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002246\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002247
Fred Drake8842e861998-02-13 07:16:30 +00002248To unpickle the object again, if \code{f} is a file object which has
2249been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002250
Fred Drake8842e861998-02-13 07:16:30 +00002251\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002252x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002253\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002254
Guido van Rossum02455691997-07-17 16:21:52 +00002255(There are other variants of this, used when pickling many objects or
2256when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002257complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002258
Fred Drake8842e861998-02-13 07:16:30 +00002259\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002260stored and reused by other programs or by a future invocation of the
2261same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002262object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002263write Python extensions take care to ensure that new data types such
2264as matrices, XXX more examples needed XXX, can be properly pickled and
2265unpickled.
2266
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002267
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002268
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002269\chapter{Errors and Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002270\label{errors}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002271
2272Until now error messages haven't been more than mentioned, but if you
2273have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002274(at least) two distinguishable kinds of errors: \emph{syntax errors}
2275and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002276
2277\section{Syntax Errors}
Fred Drake6c2176e1998-02-26 21:47:54 +00002278\label{syntaxErrors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002279
2280Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002281kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002282
Fred Drake8842e861998-02-13 07:16:30 +00002283\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002284>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002285 File "<stdin>", line 1
2286 while 1 print 'Hello world'
2287 ^
2288SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002289\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002290
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002291The parser repeats the offending line and displays a little `arrow'
2292pointing at the earliest point in the line where the error was detected.
2293The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002294\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002295the arrow: in the example, the error is detected at the keyword
Fred Drake391564f1998-04-01 23:11:56 +00002296\keyword{print}, since a colon (\character{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002297File name and line number are printed so you know where to look in case
2298the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002299
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002300\section{Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002301\label{exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002302
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002303Even if a statement or expression is syntactically correct, it may
2304cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002305Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002306not unconditionally fatal: you will soon learn how to handle them in
2307Python programs. Most exceptions are not handled by programs,
2308however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002309
Fred Drake8842e861998-02-13 07:16:30 +00002310\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002311>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002312Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002313 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002314ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002315>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002316Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002317 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002318NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002319>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002320Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002321 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002322TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002323\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002324
Guido van Rossumb2c65561993-05-12 08:53:36 +00002325The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002326Exceptions come in different types, and the type is printed as part of
2327the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002328\exception{ZeroDivisionError},
2329\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002330and
Fred Drake8842e861998-02-13 07:16:30 +00002331\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002332The string printed as the exception type is the name of the built-in
2333name for the exception that occurred. This is true for all built-in
2334exceptions, but need not be true for user-defined exceptions (although
2335it is a useful convention).
2336Standard exception names are built-in identifiers (not reserved
2337keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002338
Guido van Rossumb2c65561993-05-12 08:53:36 +00002339The rest of the line is a detail whose interpretation depends on the
2340exception type; its meaning is dependent on the exception type.
2341
2342The preceding part of the error message shows the context where the
2343exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002344In general it contains a stack backtrace listing source lines; however,
2345it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002346
Fred Drake8842e861998-02-13 07:16:30 +00002347The Library Reference lists the built-in exceptions and their
2348meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002349
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002350\section{Handling Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002351\label{handling}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002352
2353It is possible to write programs that handle selected exceptions.
2354Look at the following example, which prints a table of inverses of
2355some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002356
Fred Drake8842e861998-02-13 07:16:30 +00002357\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002358>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002359>>> for x in numbers:
2360... print x,
2361... try:
2362... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002363... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002364... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002365...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023660.3333 3.00030003
23672.5 0.4
23680 *** has no inverse ***
236910 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002370\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002371
Fred Drake8842e861998-02-13 07:16:30 +00002372The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002373\begin{itemize}
2374\item
Fred Drake8842e861998-02-13 07:16:30 +00002375First, the \emph{try clause}
2376(the statement(s) between the \keyword{try} and \keyword{except}
2377keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002378\item
2379If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002380\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002381is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002382\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002383If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002384the rest of the clause is skipped. Then if its type matches the
2385exception named after the \keyword{except} keyword, the rest of the
2386try clause is skipped, the except clause is executed, and then
2387execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002388\item
2389If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002390except clause, it is passed on to outer \keyword{try} statements; if
2391no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002392and execution stops with a message as shown above.
2393\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002394A \keyword{try} statement may have more than one except clause, to
2395specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002396At most one handler will be executed.
2397Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002398clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002399An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002400e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002401
Fred Drake8842e861998-02-13 07:16:30 +00002402\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002403... except (RuntimeError, TypeError, NameError):
2404... pass
Fred Drake8842e861998-02-13 07:16:30 +00002405\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002406
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002407The last except clause may omit the exception name(s), to serve as a
2408wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002409Use this with extreme caution, since it is easy to mask a real
2410programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002411
Fred Drake8842e861998-02-13 07:16:30 +00002412The \keyword{try} \ldots\ \keyword{except} statement has an optional
2413\emph{else clause}, which must follow all except clauses. It is
2414useful to place code that must be executed if the try clause does not
2415raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002416
2417\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002418for arg in sys.argv:
2419 try:
2420 f = open(arg, 'r')
2421 except IOError:
2422 print 'cannot open', arg
2423 else:
2424 print arg, 'has', len(f.readlines()), 'lines'
2425 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002426\end{verbatim}
2427
2428
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002429When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002430the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002431The presence and type of the argument depend on the exception type.
2432For exception types which have an argument, the except clause may
2433specify a variable after the exception name (or list) to receive the
2434argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002435
Fred Drake8842e861998-02-13 07:16:30 +00002436\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002437>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002438... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002439... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002440... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002441...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002442name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002443\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002444
Guido van Rossumb2c65561993-05-12 08:53:36 +00002445If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002446(`detail') of the message for unhandled exceptions.
2447
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002448Exception handlers don't just handle exceptions if they occur
2449immediately in the try clause, but also if they occur inside functions
2450that are called (even indirectly) in the try clause.
2451For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002452
Fred Drake8842e861998-02-13 07:16:30 +00002453\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002454>>> def this_fails():
2455... x = 1/0
2456...
2457>>> try:
2458... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002459... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002460... print 'Handling run-time error:', detail
2461...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002462Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002463\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002464
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002465
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002466\section{Raising Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002467\label{raising}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002468
Fred Drake8842e861998-02-13 07:16:30 +00002469The \keyword{raise} statement allows the programmer to force a
2470specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002471For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002472
Fred Drake8842e861998-02-13 07:16:30 +00002473\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002474>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002475Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002476 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002477NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002478\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002479
Fred Drake8842e861998-02-13 07:16:30 +00002480The first argument to \keyword{raise} names the exception to be
2481raised. The optional second argument specifies the exception's
2482argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002483
Guido van Rossum02455691997-07-17 16:21:52 +00002484
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002485\section{User-defined Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002486\label{userExceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002487
2488Programs may name their own exceptions by assigning a string to a
2489variable.
2490For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002491
Fred Drake8842e861998-02-13 07:16:30 +00002492\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002493>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002494>>> try:
2495... raise my_exc, 2*2
2496... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002497... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002498...
Guido van Rossum6938f061994-08-01 12:22:53 +00002499My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002500>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002501Traceback (innermost last):
2502 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002503my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002504\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002505
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002506Many standard modules use this to report errors that may occur in
2507functions they define.
2508
Guido van Rossum02455691997-07-17 16:21:52 +00002509
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002510\section{Defining Clean-up Actions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002511\label{cleanup}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002512
Fred Drake8842e861998-02-13 07:16:30 +00002513The \keyword{try} statement has another optional clause which is
2514intended to define clean-up actions that must be executed under all
2515circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002516
Fred Drake8842e861998-02-13 07:16:30 +00002517\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002518>>> try:
2519... raise KeyboardInterrupt
2520... finally:
2521... print 'Goodbye, world!'
2522...
2523Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002524Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002525 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002526KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002527\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002528
Fred Drake8842e861998-02-13 07:16:30 +00002529A \emph{finally clause} is executed whether or not an exception has
2530occurred in the try clause. When an exception has occurred, it is
2531re-raised after the finally clause is executed. The finally clause is
2532also executed ``on the way out'' when the \keyword{try} statement is
2533left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002534
Fred Drake8842e861998-02-13 07:16:30 +00002535A \keyword{try} statement must either have one or more except clauses
2536or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002537
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002538\chapter{Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00002539\label{classes}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002540
2541Python's class mechanism adds classes to the language with a minimum
2542of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002543found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002544do not put an absolute barrier between definition and user, but rather
2545rely on the politeness of the user not to ``break into the
2546definition.'' The most important features of classes are retained
2547with full power, however: the class inheritance mechanism allows
2548multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00002549base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002550same name. Objects can contain an arbitrary amount of private data.
2551
Guido van Rossum16d6e711994-08-08 12:30:22 +00002552In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002553\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002554no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002555shorthands for referencing the object's members from its methods: the
2556method function is declared with an explicit first argument
2557representing the object, which is provided implicitly by the call. As
2558in Smalltalk, classes themselves are objects, albeit in the wider
2559sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002560provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002561or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002562extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002563built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00002564subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002565
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002566\section{A word about terminology}
Fred Drake6c2176e1998-02-26 21:47:54 +00002567\label{terminology}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002568
Fred Drake391564f1998-04-01 23:11:56 +00002569Lacking universally accepted terminology to talk about classes, I will
2570make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002571terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002572Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002573
2574I also have to warn you that there's a terminological pitfall for
2575object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002576necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2577unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00002578built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00002579exotic types like files aren't. However, \emph{all} Python types
2580share a little bit of common semantics that is best described by using
2581the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002582
2583Objects have individuality, and multiple names (in multiple scopes)
2584can be bound to the same object. This is known as aliasing in other
2585languages. This is usually not appreciated on a first glance at
2586Python, and can be safely ignored when dealing with immutable basic
2587types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002588(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002589objects such as lists, dictionaries, and most types representing
2590entities outside the program (files, windows, etc.). This is usually
2591used to the benefit of the program, since aliases behave like pointers
2592in some respects. For example, passing an object is cheap since only
2593a pointer is passed by the implementation; and if a function modifies
2594an object passed as an argument, the caller will see the change --- this
2595obviates the need for two different argument passing mechanisms as in
2596Pascal.
2597
2598
2599\section{Python scopes and name spaces}
Fred Drake6c2176e1998-02-26 21:47:54 +00002600\label{scopes}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002601
2602Before introducing classes, I first have to tell you something about
2603Python's scope rules. Class definitions play some neat tricks with
2604name spaces, and you need to know how scopes and name spaces work to
2605fully understand what's going on. Incidentally, knowledge about this
2606subject is useful for any advanced Python programmer.
2607
2608Let's begin with some definitions.
2609
Fred Drakeeee08cd1997-12-04 15:43:15 +00002610A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002611spaces are currently implemented as Python dictionaries, but that's
2612normally not noticeable in any way (except for performance), and it
2613may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002614built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002615names); the global names in a module; and the local names in a
2616function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002617also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002618spaces is that there is absolutely no relation between names in
2619different name spaces; for instance, two different modules may both
2620define a function ``maximize'' without confusion --- users of the
2621modules must prefix it with the module name.
2622
Fred Drakeeee08cd1997-12-04 15:43:15 +00002623By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002624dot --- for example, in the expression \code{z.real}, \code{real} is
2625an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002626names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002627\code{modname.funcname}, \code{modname} is a module object and
2628\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002629be a straightforward mapping between the module's attributes and the
2630global names defined in the module: they share the same name space!%
2631\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002632 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002633 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002634 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002635 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002636 Obviously, using this violates the abstraction of name space
2637 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002638 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002639}
2640
2641Attributes may be read-only or writable. In the latter case,
2642assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002643you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drake391564f1998-04-01 23:11:56 +00002644also be deleted with the \keyword{del} statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002645\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002646
2647Name spaces are created at different moments and have different
2648lifetimes. The name space containing the built-in names is created
2649when the Python interpreter starts up, and is never deleted. The
2650global name space for a module is created when the module definition
2651is read in; normally, module name spaces also last until the
2652interpreter quits. The statements executed by the top-level
2653invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002654interactively, are considered part of a module called
2655\module{__main__}, so they have their own global name space. (The
2656built-in names actually also live in a module; this is called
2657\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002658
2659The local name space for a function is created when the function is
2660called, and deleted when the function returns or raises an exception
2661that is not handled within the function. (Actually, forgetting would
2662be a better way to describe what actually happens.) Of course,
2663recursive invocations each have their own local name space.
2664
Fred Drakeeee08cd1997-12-04 15:43:15 +00002665A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002666is directly accessible. ``Directly accessible'' here means that an
2667unqualified reference to a name attempts to find the name in the name
2668space.
2669
2670Although scopes are determined statically, they are used dynamically.
2671At any time during execution, exactly three nested scopes are in use
2672(i.e., exactly three name spaces are directly accessible): the
2673innermost scope, which is searched first, contains the local names,
2674the middle scope, searched next, contains the current module's global
2675names, and the outermost scope (searched last) is the name space
2676containing built-in names.
2677
2678Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00002679current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002680the same name space as the global scope: the module's name space.
2681Class definitions place yet another name space in the local scope.
2682
2683It is important to realize that scopes are determined textually: the
2684global scope of a function defined in a module is that module's name
2685space, no matter from where or by what alias the function is called.
2686On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00002687run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002688static name resolution, at ``compile'' time, so don't rely on dynamic
2689name resolution! (In fact, local variables are already determined
2690statically.)
2691
2692A special quirk of Python is that assignments always go into the
2693innermost scope. Assignments do not copy data --- they just
2694bind names to objects. The same is true for deletions: the statement
Fred Drake391564f1998-04-01 23:11:56 +00002695\samp{del x} removes the binding of \code{x} from the name space
2696referenced by the local scope. In fact, all operations that introduce
2697new names use the local scope: in particular, import statements and
2698function definitions bind the module or function name in the local
2699scope. (The \keyword{global} statement can be used to indicate that
2700particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002701
2702
2703\section{A first look at classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00002704\label{firstClasses}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002705
2706Classes introduce a little bit of new syntax, three new object types,
2707and some new semantics.
2708
2709
2710\subsection{Class definition syntax}
Fred Drake6c2176e1998-02-26 21:47:54 +00002711\label{classDefinition}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002712
2713The simplest form of class definition looks like this:
2714
2715\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002716class ClassName:
2717 <statement-1>
2718 .
2719 .
2720 .
2721 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002722\end{verbatim}
2723
Fred Drake8842e861998-02-13 07:16:30 +00002724Class definitions, like function definitions (\keyword{def}
2725statements) must be executed before they have any effect. (You could
2726conceivably place a class definition in a branch of an \keyword{if}
2727statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002728
2729In practice, the statements inside a class definition will usually be
2730function definitions, but other statements are allowed, and sometimes
2731useful --- we'll come back to this later. The function definitions
2732inside a class normally have a peculiar form of argument list,
2733dictated by the calling conventions for methods --- again, this is
2734explained later.
2735
2736When a class definition is entered, a new name space is created, and
2737used as the local scope --- thus, all assignments to local variables
2738go into this new name space. In particular, function definitions bind
2739the name of the new function here.
2740
Fred Drakeeee08cd1997-12-04 15:43:15 +00002741When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002742object} is created. This is basically a wrapper around the contents
2743of the name space created by the class definition; we'll learn more
2744about class objects in the next section. The original local scope
2745(the one in effect just before the class definitions was entered) is
2746reinstated, and the class object is bound here to class name given in
Fred Drake8842e861998-02-13 07:16:30 +00002747the class definition header (\code{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002748
2749
2750\subsection{Class objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002751\label{classObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002752
2753Class objects support two kinds of operations: attribute references
2754and instantiation.
2755
Fred Drakeeee08cd1997-12-04 15:43:15 +00002756\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00002757attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002758names are all the names that were in the class's name space when the
2759class object was created. So, if the class definition looked like
2760this:
2761
2762\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002763class MyClass:
2764 "A simple example class"
2765 i = 12345
2766 def f(x):
2767 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002768\end{verbatim}
2769
Fred Drake8842e861998-02-13 07:16:30 +00002770then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002771references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00002772Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00002773of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00002774attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00002775the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002776
Fred Drakeeee08cd1997-12-04 15:43:15 +00002777Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002778the class object is a parameterless function that returns a new
2779instance of the class. For example, (assuming the above class):
2780
2781\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002782x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002783\end{verbatim}
2784
Fred Drakeeee08cd1997-12-04 15:43:15 +00002785creates a new \emph{instance} of the class and assigns this object to
2786the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002787
2788
2789\subsection{Instance objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002790\label{instanceObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002791
2792Now what can we do with instance objects? The only operations
2793understood by instance objects are attribute references. There are
2794two kinds of valid attribute names.
2795
Fred Drakeeee08cd1997-12-04 15:43:15 +00002796The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00002797``instance variables'' in Smalltalk, and to ``data members'' in
2798\Cpp{}. Data attributes need not be declared; like local variables,
2799they spring into existence when they are first assigned to. For
2800example, if \code{x} is the instance of \class{MyClass} created above,
2801the following piece of code will print the value \code{16}, without
2802leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002803
2804\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002805x.counter = 1
2806while x.counter < 10:
2807 x.counter = x.counter * 2
2808print x.counter
2809del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002810\end{verbatim}
2811
2812The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00002813are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002814object. (In Python, the term method is not unique to class instances:
2815other object types can have methods as well, e.g., list objects have
2816methods called append, insert, remove, sort, and so on. However,
2817below, we'll use the term method exclusively to mean methods of class
2818instance objects, unless explicitly stated otherwise.)
2819
2820Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00002821definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002822objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00002823example, \code{x.f} is a valid method reference, since
2824\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00002825\code{MyClass.i} is not. But \code{x.f} is not the same thing as
2826\code{MyClass.f} --- it is a \emph{method object}, not a function
2827object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002828
2829
2830\subsection{Method objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002831\label{methodObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002832
2833Usually, a method is called immediately, e.g.:
2834
2835\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002836x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002837\end{verbatim}
2838
Fred Drake8842e861998-02-13 07:16:30 +00002839In our example, this will return the string \code{'hello world'}.
2840However, it is not necessary to call a method right away: \code{x.f}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002841is a method object, and can be stored away and called at a later
2842moment, for example:
2843
2844\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002845xf = x.f
2846while 1:
2847 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002848\end{verbatim}
2849
Fred Drake8842e861998-02-13 07:16:30 +00002850will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002851
2852What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00002853that \code{x.f()} was called without an argument above, even though
2854the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002855happened to the argument? Surely Python raises an exception when a
2856function that requires an argument is called without any --- even if
2857the argument isn't actually used...
2858
2859Actually, you may have guessed the answer: the special thing about
2860methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00002861function. In our example, the call \code{x.f()} is exactly equivalent
2862to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00002863\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002864with an argument list that is created by inserting the method's object
2865before the first argument.
2866
2867If you still don't understand how methods work, a look at the
2868implementation can perhaps clarify matters. When an instance
2869attribute is referenced that isn't a data attribute, its class is
2870searched. If the name denotes a valid class attribute that is a
2871function object, a method object is created by packing (pointers to)
2872the instance object and the function object just found together in an
2873abstract object: this is the method object. When the method object is
2874called with an argument list, it is unpacked again, a new argument
2875list is constructed from the instance object and the original argument
2876list, and the function object is called with this new argument list.
2877
2878
2879\section{Random remarks}
Fred Drake6c2176e1998-02-26 21:47:54 +00002880\label{remarks}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002881
2882[These should perhaps be placed more carefully...]
2883
2884
2885Data attributes override method attributes with the same name; to
2886avoid accidental name conflicts, which may cause hard-to-find bugs in
2887large programs, it is wise to use some kind of convention that
2888minimizes the chance of conflicts, e.g., capitalize method names,
2889prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00002890an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002891
2892
2893Data attributes may be referenced by methods as well as by ordinary
2894users (``clients'') of an object. In other words, classes are not
2895usable to implement pure abstract data types. In fact, nothing in
2896Python makes it possible to enforce data hiding --- it is all based
2897upon convention. (On the other hand, the Python implementation,
Fred Drake3f205921998-01-13 18:56:38 +00002898written in \C{}, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002899access to an object if necessary; this can be used by extensions to
Fred Drake3f205921998-01-13 18:56:38 +00002900Python written in \C{}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002901
2902
2903Clients should use data attributes with care --- clients may mess up
2904invariants maintained by the methods by stamping on their data
2905attributes. Note that clients may add data attributes of their own to
2906an instance object without affecting the validity of the methods, as
2907long as name conflicts are avoided --- again, a naming convention can
2908save a lot of headaches here.
2909
2910
2911There is no shorthand for referencing data attributes (or other
2912methods!) from within methods. I find that this actually increases
2913the readability of methods: there is no chance of confusing local
2914variables and instance variables when glancing through a method.
2915
2916
2917Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00002918\code{self}. This is nothing more than a convention: the name
2919\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002920however, that by not following the convention your code may be less
2921readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00002922a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002923convention.)
2924
2925
2926Any function object that is a class attribute defines a method for
2927instances of that class. It is not necessary that the function
2928definition is textually enclosed in the class definition: assigning a
2929function object to a local variable in the class is also ok. For
2930example:
2931
2932\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002933# Function defined outside the class
2934def f1(self, x, y):
2935 return min(x, x+y)
2936
2937class C:
2938 f = f1
2939 def g(self):
2940 return 'hello world'
2941 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002942\end{verbatim}
2943
Fred Drake8842e861998-02-13 07:16:30 +00002944Now \code{f}, \code{g} and \code{h} are all attributes of class
2945\class{C} that refer to function objects, and consequently they are all
2946methods of instances of \class{C} --- \code{h} being exactly equivalent
2947to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002948the reader of a program.
2949
2950
2951Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00002952\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002953
2954\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002955class Bag:
2956 def empty(self):
2957 self.data = []
2958 def add(self, x):
2959 self.data.append(x)
2960 def addtwice(self, x):
2961 self.add(x)
2962 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002963\end{verbatim}
2964
2965
2966The instantiation operation (``calling'' a class object) creates an
2967empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00002968state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00002969\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002970
Guido van Rossum6938f061994-08-01 12:22:53 +00002971\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002972 def __init__(self):
2973 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00002974\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002975
Fred Drake8842e861998-02-13 07:16:30 +00002976When a class defines an \method{__init__()} method, class
2977instantiation automatically invokes \method{__init__()} for the
2978newly-created class instance. So in the \class{Bag} example, a new
2979and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002980
Guido van Rossum6938f061994-08-01 12:22:53 +00002981\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002982x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00002983\end{verbatim}
2984
Fred Drake8842e861998-02-13 07:16:30 +00002985Of course, the \method{__init__()} method may have arguments for
2986greater flexibility. In that case, arguments given to the class
2987instantiation operator are passed on to \method{__init__()}. For
2988example,
Guido van Rossum6938f061994-08-01 12:22:53 +00002989
Fred Drake8842e861998-02-13 07:16:30 +00002990\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00002991>>> class Complex:
2992... def __init__(self, realpart, imagpart):
2993... self.r = realpart
2994... self.i = imagpart
2995...
2996>>> x = Complex(3.0,-4.5)
2997>>> x.r, x.i
2998(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00002999\end{verbatim}
3000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003001Methods may reference global names in the same way as ordinary
3002functions. The global scope associated with a method is the module
3003containing the class definition. (The class itself is never used as a
3004global scope!) While one rarely encounters a good reason for using
3005global data in a method, there are many legitimate uses of the global
3006scope: for one thing, functions and modules imported into the global
3007scope can be used by methods, as well as functions and classes defined
3008in it. Usually, the class containing the method is itself defined in
3009this global scope, and in the next section we'll find some good
3010reasons why a method would want to reference its own class!
3011
3012
3013\section{Inheritance}
Fred Drake6c2176e1998-02-26 21:47:54 +00003014\label{inheritance}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003015
3016Of course, a language feature would not be worthy of the name ``class''
3017without supporting inheritance. The syntax for a derived class
3018definition looks as follows:
3019
3020\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003021class DerivedClassName(BaseClassName):
3022 <statement-1>
3023 .
3024 .
3025 .
3026 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003027\end{verbatim}
3028
Fred Drake8842e861998-02-13 07:16:30 +00003029The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003030the derived class definition. Instead of a base class name, an
3031expression is also allowed. This is useful when the base class is
3032defined in another module, e.g.,
3033
3034\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003035class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003036\end{verbatim}
3037
3038Execution of a derived class definition proceeds the same as for a
3039base class. When the class object is constructed, the base class is
3040remembered. This is used for resolving attribute references: if a
3041requested attribute is not found in the class, it is searched in the
3042base class. This rule is applied recursively if the base class itself
3043is derived from some other class.
3044
3045There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00003046\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003047references are resolved as follows: the corresponding class attribute
3048is searched, descending down the chain of base classes if necessary,
3049and the method reference is valid if this yields a function object.
3050
3051Derived classes may override methods of their base classes. Because
3052methods have no special privileges when calling other methods of the
3053same object, a method of a base class that calls another method
3054defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003055a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003056in Python are ``virtual functions''.)
3057
3058An overriding method in a derived class may in fact want to extend
3059rather than simply replace the base class method of the same name.
3060There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003061call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003062occasionally useful to clients as well. (Note that this only works if
3063the base class is defined or imported directly in the global scope.)
3064
3065
3066\subsection{Multiple inheritance}
Fred Drake6c2176e1998-02-26 21:47:54 +00003067\label{multiple}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003068
Guido van Rossum6938f061994-08-01 12:22:53 +00003069Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003070class definition with multiple base classes looks as follows:
3071
3072\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003073class DerivedClassName(Base1, Base2, Base3):
3074 <statement-1>
3075 .
3076 .
3077 .
3078 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003079\end{verbatim}
3080
3081The only rule necessary to explain the semantics is the resolution
3082rule used for class attribute references. This is depth-first,
3083left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003084\class{DerivedClassName}, it is searched in \class{Base1}, then
3085(recursively) in the base classes of \class{Base1}, and only if it is
3086not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003087
Fred Drake8842e861998-02-13 07:16:30 +00003088(To some people breadth first --- searching \class{Base2} and
3089\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003090natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003091attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003092one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003093a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003094rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003095\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003096
3097It is clear that indiscriminate use of multiple inheritance is a
3098maintenance nightmare, given the reliance in Python on conventions to
3099avoid accidental name conflicts. A well-known problem with multiple
3100inheritance is a class derived from two classes that happen to have a
3101common base class. While it is easy enough to figure out what happens
3102in this case (the instance will have a single copy of ``instance
3103variables'' or data attributes used by the common base class), it is
3104not clear that these semantics are in any way useful.
3105
3106
Guido van Rossum02455691997-07-17 16:21:52 +00003107\section{Private variables through name mangling}
Fred Drake6c2176e1998-02-26 21:47:54 +00003108\label{private}
Guido van Rossum02455691997-07-17 16:21:52 +00003109
3110There is now limited support for class-private
3111identifiers. Any identifier of the form \code{__spam} (at least two
3112leading underscores, at most one trailing underscore) is now textually
3113replaced with \code{_classname__spam}, where \code{classname} is the
3114current class name with leading underscore(s) stripped. This mangling
3115is done without regard of the syntactic position of the identifier, so
3116it can be used to define class-private instance and class variables,
3117methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003118private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003119may occur when the mangled name would be longer than 255 characters.
3120Outside classes, or when the class name consists of only underscores,
3121no mangling occurs.
3122
3123Name mangling is intended to give classes an easy way to define
3124``private'' instance variables and methods, without having to worry
3125about instance variables defined by derived classes, or mucking with
3126instance variables by code outside the class. Note that the mangling
3127rules are designed mostly to avoid accidents; it still is possible for
3128a determined soul to access or modify a variable that is considered
3129private. This can even be useful, e.g. for the debugger, and that's
3130one reason why this loophole is not closed. (Buglet: derivation of a
3131class with the same name as the base class makes use of private
3132variables of the base class possible.)
3133
3134Notice that code passed to \code{exec}, \code{eval()} or
3135\code{evalfile()} does not consider the classname of the invoking
3136class to be the current class; this is similar to the effect of the
3137\code{global} statement, the effect of which is likewise restricted to
3138code that is byte-compiled together. The same restriction applies to
3139\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3140when referencing \code{__dict__} directly.
3141
3142Here's an example of a class that implements its own
3143\code{__getattr__} and \code{__setattr__} methods and stores all
3144attributes in a private variable, in a way that works in Python 1.4 as
3145well as in previous versions:
3146
3147\begin{verbatim}
3148class VirtualAttributes:
3149 __vdict = None
3150 __vdict_name = locals().keys()[0]
3151
3152 def __init__(self):
3153 self.__dict__[self.__vdict_name] = {}
3154
3155 def __getattr__(self, name):
3156 return self.__vdict[name]
3157
3158 def __setattr__(self, name, value):
3159 self.__vdict[name] = value
3160\end{verbatim}
3161
Fred Drakeaf8a0151998-01-14 14:51:31 +00003162%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003163%potential problems, refrain from using identifiers starting with
3164%double underscore except for predefined uses like \code{__init__}. To
3165%use private names while maintaining future compatibility: refrain from
3166%using the same private name in classes related via subclassing; avoid
3167%explicit (manual) mangling/unmangling; and assume that at some point
3168%in the future, leading double underscore will revert to being just a
3169%naming convention. Discussion on extensive compile-time declarations
3170%are currently underway, and it is impossible to predict what solution
3171%will eventually be chosen for private names. Double leading
3172%underscore is still a candidate, of course --- just not the only one.
3173%It is placed in the distribution in the belief that it is useful, and
3174%so that widespread experience with its use can be gained. It will not
3175%be removed without providing a better solution and a migration path.
3176
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003177\section{Odds and ends}
Fred Drake6c2176e1998-02-26 21:47:54 +00003178\label{odds}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003179
3180Sometimes it is useful to have a data type similar to the Pascal
Fred Drake3f205921998-01-13 18:56:38 +00003181``record'' or \C{} ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003182items. An empty class definition will do nicely, e.g.:
3183
3184\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003185class Employee:
3186 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003187
Fred Drake8842e861998-02-13 07:16:30 +00003188john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003189
Fred Drake8842e861998-02-13 07:16:30 +00003190# Fill the fields of the record
3191john.name = 'John Doe'
3192john.dept = 'computer lab'
3193john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003194\end{verbatim}
3195
3196
3197A piece of Python code that expects a particular abstract data type
3198can often be passed a class that emulates the methods of that data
3199type instead. For instance, if you have a function that formats some
3200data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003201\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00003202buffer instead, and pass it as an argument.% (Unfortunately, this
3203%technique has its limitations: a class can't define operations that
3204%are accessed by special syntax such as sequence subscripting or
3205%arithmetic operators, and assigning such a ``pseudo-file'' to
3206%\code{sys.stdin} will not cause the interpreter to read further input
3207%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003208
3209
Fred Drake8842e861998-02-13 07:16:30 +00003210Instance method objects have attributes, too: \code{m.im_self} is the
3211object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003212function object corresponding to the method.
3213
Guido van Rossum02455691997-07-17 16:21:52 +00003214\subsection{Exceptions Can Be Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00003215\label{exceptionClasses}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003216
3217User-defined exceptions are no longer limited to being string objects
3218--- they can be identified by classes as well. Using this mechanism it
3219is possible to create extensible hierarchies of exceptions.
3220
3221There are two new valid (semantic) forms for the raise statement:
3222
3223\begin{verbatim}
3224raise Class, instance
3225
3226raise instance
3227\end{verbatim}
3228
Fred Drake8842e861998-02-13 07:16:30 +00003229In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003230or of a class derived from it. The second form is a shorthand for
3231
3232\begin{verbatim}
3233raise instance.__class__, instance
3234\end{verbatim}
3235
3236An except clause may list classes as well as string objects. A class
3237in an except clause is compatible with an exception if it is the same
3238class or a base class thereof (but not the other way around --- an
3239except clause listing a derived class is not compatible with a base
3240class). For example, the following code will print B, C, D in that
3241order:
3242
3243\begin{verbatim}
3244class B:
3245 pass
3246class C(B):
3247 pass
3248class D(C):
3249 pass
3250
3251for c in [B, C, D]:
3252 try:
3253 raise c()
3254 except D:
3255 print "D"
3256 except C:
3257 print "C"
3258 except B:
3259 print "B"
3260\end{verbatim}
3261
Fred Drake8842e861998-02-13 07:16:30 +00003262Note that if the except clauses were reversed (with \samp{except B}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003263first), it would have printed B, B, B --- the first matching except
3264clause is triggered.
3265
3266When an error message is printed for an unhandled exception which is a
3267class, the class name is printed, then a colon and a space, and
3268finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003269\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003270
3271In this release, the built-in exceptions are still strings.
3272
Guido van Rossum02455691997-07-17 16:21:52 +00003273\chapter{What Now?}
Fred Drake6c2176e1998-02-26 21:47:54 +00003274\label{whatNow}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003275
Guido van Rossum02455691997-07-17 16:21:52 +00003276Hopefully reading this tutorial has reinforced your interest in using
3277Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003278
Guido van Rossum02455691997-07-17 16:21:52 +00003279You should read, or at least page through, the Library Reference,
3280which gives complete (though terse) reference material about types,
3281functions, and modules that can save you a lot of time when writing
3282Python programs. The standard Python distribution includes a
Fred Drake3f205921998-01-13 18:56:38 +00003283\emph{lot} of code in both \C{} and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003284\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3285numbers, parse command-line options, write CGI programs, compress
3286data, and a lot more; skimming through the Library Reference will give
3287you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003288
Fred Drakeca6567f1998-01-22 20:44:18 +00003289The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003290code, documentation, and pointers to Python-related pages around the
Fred Drake391564f1998-04-01 23:11:56 +00003291Web. This web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00003292world, such as Europe, Japan, and Australia; a mirror may be faster
3293than the main site, depending on your geographical location. A more
Fred Drakeca6567f1998-01-22 20:44:18 +00003294informal site is \url{http://starship.skyport.net}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003295bunch of Python-related personal home pages; many people have
3296downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003297
Guido van Rossum02455691997-07-17 16:21:52 +00003298For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00003299newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
3300list at \email{python-list@cwi.nl}. The newsgroup and mailing list
3301are gatewayed, so messages posted to one will automatically be
3302forwarded to the other. There are around 35--45 postings a day,
3303% Postings figure based on average of last six months activity as
3304% reported by www.findmail.com; Oct. '97 - Mar. '98: 7480 msgs / 182
3305% days = 41.1 msgs / day.
3306asking (and answering) questions, suggesting new features, and
3307announcing new modules. Before posting, be sure to check the list of
3308Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003309\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3310\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003311answers many of the questions that come up again and again, and may
3312already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003313
Guido van Rossum02455691997-07-17 16:21:52 +00003314You can support the Python community by joining the Python Software
3315Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003316organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003317information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003318
Guido van Rossum194e57c1995-02-15 15:51:38 +00003319
Guido van Rossum02455691997-07-17 16:21:52 +00003320\chapter{Recent Additions as of Release 1.1}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003321
Fred Drake8842e861998-02-13 07:16:30 +00003322% XXX Should the stuff in this chapter be deleted, or can a home be
3323% found or it elsewhere in the Tutorial?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003324
Guido van Rossum02455691997-07-17 16:21:52 +00003325\section{Lambda Forms}
Fred Drake6c2176e1998-02-26 21:47:54 +00003326\label{lambda}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003327
Fred Drake8842e861998-02-13 07:16:30 +00003328% XXX Where to put this? Or just leave it out?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003329
Guido van Rossum02455691997-07-17 16:21:52 +00003330By popular demand, a few features commonly found in functional
3331programming languages and Lisp have been added to Python. With the
Fred Drake8842e861998-02-13 07:16:30 +00003332\keyword{lambda} keyword, small anonymous functions can be created.
Guido van Rossum02455691997-07-17 16:21:52 +00003333Here's a function that returns the sum of its two arguments:
Fred Drake8842e861998-02-13 07:16:30 +00003334\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
Guido van Rossum02455691997-07-17 16:21:52 +00003335objects are required. They are syntactically restricted to a single
3336expression. Semantically, they are just syntactic sugar for a normal
3337function definition. Like nested function definitions, lambda forms
3338cannot reference variables from the containing scope, but this can be
3339overcome through the judicious use of default argument values, e.g.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003340
Guido van Rossum02455691997-07-17 16:21:52 +00003341\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003342def make_incrementor(n):
3343 return lambda x, incr=n: x+incr
Guido van Rossum02455691997-07-17 16:21:52 +00003344\end{verbatim}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003345
3346\section{Documentation Strings}
Fred Drake6c2176e1998-02-26 21:47:54 +00003347\label{docstrings}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003348
Fred Drake8842e861998-02-13 07:16:30 +00003349% XXX Where to put this? Or just leave it out?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003350
3351There are emerging conventions about the content and formatting of
3352documentation strings.
3353
3354The first line should always be a short, concise summary of the
3355object's purpose. For brevity, it should not explicitly state the
3356object's name or type, since these are available by other means
3357(except if the name happens to be a verb describing a function's
3358operation). This line should begin with a capital letter and end with
3359a period.
3360
3361If there are more lines in the documentation string, the second line
3362should be blank, visually separating the summary from the rest of the
3363description. The following lines should be one of more of paragraphs
3364describing the objects calling conventions, its side effects, etc.
3365
3366Some people like to copy the Emacs convention of using UPPER CASE for
3367function parameters --- this often saves a few words or lines.
3368
3369The Python parser does not strip indentation from multi-line string
3370literals in Python, so tools that process documentation have to strip
3371indentation. This is done using the following convention. The first
Fred Drakeeee08cd1997-12-04 15:43:15 +00003372non-blank line \emph{after} the first line of the string determines the
Guido van Rossum194e57c1995-02-15 15:51:38 +00003373amount of indentation for the entire documentation string. (We can't
3374use the first line since it is generally adjacent to the string's
3375opening quotes so its indentation is not apparent in the string
3376literal.) Whitespace ``equivalent'' to this indentation is then
3377stripped from the start of all lines of the string. Lines that are
3378indented less should not occur, but if they occur all their leading
3379whitespace should be stripped. Equivalence of whitespace should be
3380tested after expansion of tabs (to 8 spaces, normally).
3381
Guido van Rossum194e57c1995-02-15 15:51:38 +00003382
Guido van Rossum02455691997-07-17 16:21:52 +00003383\appendix\chapter{Interactive Input Editing and History Substitution}
Fred Drake6c2176e1998-02-26 21:47:54 +00003384\label{interacting}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003385
Guido van Rossum02455691997-07-17 16:21:52 +00003386Some versions of the Python interpreter support editing of the current
3387input line and history substitution, similar to facilities found in
3388the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003389\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003390editing. This library has its own documentation which I won't
3391duplicate here; however, the basics are easily explained.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003392
Fred Drake8d486b11998-02-11 22:12:18 +00003393\section{Line Editing}
Fred Drake6c2176e1998-02-26 21:47:54 +00003394\label{lineEditing}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003395
Guido van Rossum02455691997-07-17 16:21:52 +00003396If supported, input line editing is active whenever the interpreter
3397prints a primary or secondary prompt. The current line can be edited
3398using the conventional Emacs control characters. The most important
3399of these are: C-A (Control-A) moves the cursor to the beginning of the
3400line, C-E to the end, C-B moves it one position to the left, C-F to
3401the right. Backspace erases the character to the left of the cursor,
3402C-D the character to its right. C-K kills (erases) the rest of the
3403line to the right of the cursor, C-Y yanks back the last killed
3404string. C-underscore undoes the last change you made; it can be
3405repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003406
Fred Drake8d486b11998-02-11 22:12:18 +00003407\section{History Substitution}
Fred Drake6c2176e1998-02-26 21:47:54 +00003408\label{history}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003409
Guido van Rossum02455691997-07-17 16:21:52 +00003410History substitution works as follows. All non-empty input lines
3411issued are saved in a history buffer, and when a new prompt is given
3412you are positioned on a new line at the bottom of this buffer. C-P
3413moves one line up (back) in the history buffer, C-N moves one down.
3414Any line in the history buffer can be edited; an asterisk appears in
3415front of the prompt to mark a line as modified. Pressing the Return
3416key passes the current line to the interpreter. C-R starts an
3417incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003418
Fred Drake8d486b11998-02-11 22:12:18 +00003419\section{Key Bindings}
Fred Drake6c2176e1998-02-26 21:47:54 +00003420\label{keyBindings}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003421
Guido van Rossum02455691997-07-17 16:21:52 +00003422The key bindings and some other parameters of the Readline library can
3423be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003424\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003425
Fred Drake8842e861998-02-13 07:16:30 +00003426\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003427key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003428\end{verbatim}
3429
Guido van Rossum02455691997-07-17 16:21:52 +00003430or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003431
Fred Drake8842e861998-02-13 07:16:30 +00003432\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003433"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003434\end{verbatim}
3435
Guido van Rossum02455691997-07-17 16:21:52 +00003436and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003437
Fred Drake8842e861998-02-13 07:16:30 +00003438\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003439set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003440\end{verbatim}
3441
Guido van Rossum02455691997-07-17 16:21:52 +00003442For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003443
Fred Drake8842e861998-02-13 07:16:30 +00003444\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003445# I prefer vi-style editing:
3446set editing-mode vi
3447# Edit using a single line:
3448set horizontal-scroll-mode On
3449# Rebind some keys:
3450Meta-h: backward-kill-word
3451"\C-u": universal-argument
3452"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003453\end{verbatim}
3454
Guido van Rossum02455691997-07-17 16:21:52 +00003455Note that the default binding for TAB in Python is to insert a TAB
3456instead of Readline's default filename completion function. If you
3457insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003458
Fred Drake8842e861998-02-13 07:16:30 +00003459\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003460TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003461\end{verbatim}
3462
Fred Drakeeee08cd1997-12-04 15:43:15 +00003463in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003464indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003465
Fred Drake8d486b11998-02-11 22:12:18 +00003466\section{Commentary}
Fred Drake6c2176e1998-02-26 21:47:54 +00003467\label{commentary}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003468
Guido van Rossum02455691997-07-17 16:21:52 +00003469This facility is an enormous step forward compared to previous
3470versions of the interpreter; however, some wishes are left: It would
3471be nice if the proper indentation were suggested on continuation lines
3472(the parser knows if an indent token is required next). The
3473completion mechanism might use the interpreter's symbol table. A
3474command to check (or even suggest) matching parentheses, quotes etc.
3475would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003476
Fred Drake8842e861998-02-13 07:16:30 +00003477% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003478
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003479\end{document}
Guido van Rossum02455691997-07-17 16:21:52 +00003480