blob: 121e4c189a803641896a34481e671cfb6a656071 [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
Fred Drake9f86b661998-07-28 21:55:19 +000017\ifhtml
18\chapter*{Front Matter\label{front}}
19\fi
20
Guido van Rossum16cd7f91994-10-06 10:29:26 +000021\input{copyright}
22
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023\begin{abstract}
24
25\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000026Python is an easy to learn, powerful programming language. It has
27efficient high-level data structures and a simple but effective
28approach to object-oriented programming. Python's elegant syntax and
29dynamic typing, together with its interpreted nature, make it an ideal
30language for scripting and rapid application development in many areas
31on most platforms.
32
33The Python interpreter and the extensive standard library are freely
34available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000035Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000036distributed. The same site also contains distributions of and
37pointers to many free third party Python modules, programs and tools,
38and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000039
Guido van Rossum4410c751991-06-04 20:22:18 +000040The Python interpreter is easily extended with new functions and data
Fred Drake3f205921998-01-13 18:56:38 +000041types implemented in \C{} or \Cpp{} (or other languages callable from \C{}).
Guido van Rossumdccc2981997-12-30 04:40:25 +000042Python is also suitable as an extension language for customizable
43applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000044
Guido van Rossum6fc178f1991-08-16 09:13:42 +000045This tutorial introduces the reader informally to the basic concepts
46and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000047Python interpreter handy for hands-on experience, but all examples are
48self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000049
Guido van Rossumdccc2981997-12-30 04:40:25 +000050For a description of standard objects and modules, see the
51\emph{Python Library Reference} document. The \emph{Python Reference
52Manual} gives a more formal definition of the language. To write
Fred Drake3f205921998-01-13 18:56:38 +000053extensions in \C{} or \Cpp{}, read the \emph{Extending and Embedding} and
54\emph{Python/\C{} API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000055Python in depth.
56
57This tutorial does not attempt to be comprehensive and cover every
58single feature, or even every commonly used feature. Instead, it
59introduces many of Python's most noteworthy features, and will give
60you a good idea of the language's flavor and style. After reading it,
61you will be able to read and write Python modules and programs, and
62you will be ready to learn more about the various Python library
63modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000064
65\end{abstract}
66
Fred Drake4d4f9e71998-01-13 22:25:02 +000067\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000068
Guido van Rossum5e0759d1992-08-07 16:06:24 +000069
Guido van Rossum6fc178f1991-08-16 09:13:42 +000070\chapter{Whetting Your Appetite}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000071
Fred Drake6c2176e1998-02-26 21:47:54 +000072\label{intro}
Guido van Rossum3a26dd81996-10-24 22:12:48 +000073
Guido van Rossum6fc178f1991-08-16 09:13:42 +000074If you ever wrote a large shell script, you probably know this
75feeling: you'd love to add yet another feature, but it's already so
76slow, and so big, and so complicated; or the feature involves a system
Fred Drake3f205921998-01-13 18:56:38 +000077call or other function that is only accessible from \C{} \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000078the problem at hand isn't serious enough to warrant rewriting the
Fred Drake3f205921998-01-13 18:56:38 +000079script in \C{}; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000080other data types (like sorted lists of file names) that are easy in
Fred Drake3f205921998-01-13 18:56:38 +000081the shell but lots of work to implement in \C{}, or perhaps you're not
82sufficiently familiar with \C{}.
Guido van Rossum02455691997-07-17 16:21:52 +000083
Fred Drake3f205921998-01-13 18:56:38 +000084Another situation: perhaps you have to work with several \C{} libraries,
85and the usual \C{} write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000086need to develop software more quickly. Possibly perhaps you've
87written a program that could use an extension language, and you don't
88want to design a language, write and debug an interpreter for it, then
89tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000090
Guido van Rossum6fc178f1991-08-16 09:13:42 +000091In such cases, Python may be just the language for you. Python is
92simple to use, but it is a real programming language, offering much
93more structure and support for large programs than the shell has. On
Fred Drake3f205921998-01-13 18:56:38 +000094the other hand, it also offers much more error checking than \C{}, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000095being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000096built in, such as flexible arrays and dictionaries that would cost you
Fred Drake3f205921998-01-13 18:56:38 +000097days to implement efficiently in \C{}. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000098types Python is applicable to a much larger problem domain than
99\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
100in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000101
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000102Python allows you to split up your program in modules that can be
103reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000104standard modules that you can use as the basis of your programs --- or
105as examples to start learning to program in Python. There are also
106built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000107sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000108
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000109Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000110during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000111necessary. The interpreter can be used interactively, which makes it
112easy to experiment with features of the language, to write throw-away
113programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000114It is also a handy desk calculator.
115
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000116Python allows writing very compact and readable programs. Programs
Fred Drake3f205921998-01-13 18:56:38 +0000117written in Python are typically much shorter than equivalent \C{}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000118programs, for several reasons:
119\begin{itemize}
120\item
121the high-level data types allow you to express complex operations in a
122single statement;
123\item
124statement grouping is done by indentation instead of begin/end
125brackets;
126\item
127no variable or argument declarations are necessary.
128\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000129
Fred Drake3f205921998-01-13 18:56:38 +0000130Python is \emph{extensible}: if you know how to program in \C{} it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000131to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000132perform critical operations at maximum speed, or to link Python
133programs to libraries that may only be available in binary form (such
134as a vendor-specific graphics library). Once you are really hooked,
Fred Drake3f205921998-01-13 18:56:38 +0000135you can link the Python interpreter into an application written in \C{}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000136and use it as an extension or command language for that application.
137
Guido van Rossum02455691997-07-17 16:21:52 +0000138By the way, the language is named after the BBC show ``Monty Python's
139Flying Circus'' and has nothing to do with nasty reptiles. Making
140references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000141it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000142
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000143\section{Where From Here}
Fred Drake6c2176e1998-02-26 21:47:54 +0000144\label{where}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000145
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000146Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000147in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000148using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000149
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000150In the next chapter, the mechanics of using the interpreter are
151explained. This is rather mundane information, but essential for
152trying out the examples shown later.
153
Guido van Rossum4410c751991-06-04 20:22:18 +0000154The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000155language and system though examples, beginning with simple
156expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000157and finally touching upon advanced concepts like exceptions
158and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000159
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000160\chapter{Using the Python Interpreter}
Fred Drake6c2176e1998-02-26 21:47:54 +0000161\label{using}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000162
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000163\section{Invoking the Interpreter}
Fred Drake6c2176e1998-02-26 21:47:54 +0000164\label{invoking}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000165
Fred Drakeeee08cd1997-12-04 15:43:15 +0000166The Python interpreter is usually installed as \file{/usr/local/bin/python}
167on those machines where it is available; putting \file{/usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000168your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000169typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000170
Fred Drake8842e861998-02-13 07:16:30 +0000171\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000172python
Fred Drake8842e861998-02-13 07:16:30 +0000173\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000174
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000175to the shell. Since the choice of the directory where the interpreter
176lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000177your local Python guru or system administrator. (E.g.,
178\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000179
Guido van Rossuma8a1b9b1998-06-22 14:28:39 +0000180Typing an EOF character (Control-D on \UNIX{}, Control-Z on DOS
Guido van Rossum02455691997-07-17 16:21:52 +0000181or Windows) at the primary prompt causes the interpreter to exit with
182a zero exit status. If that doesn't work, you can exit the
Fred Drake8842e861998-02-13 07:16:30 +0000183interpreter by typing the following commands: \samp{import sys;
Guido van Rossum02455691997-07-17 16:21:52 +0000184sys.exit()}.
185
186The interpreter's line-editing features usually aren't very
Fred Drake3f205921998-01-13 18:56:38 +0000187sophisticated. On \UNIX{}, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000188enabled support for the GNU readline library, which adds more
189elaborate interactive editing and history features. Perhaps the
190quickest check to see whether command line editing is supported is
191typing Control-P to the first Python prompt you get. If it beeps, you
192have command line editing; see Appendix A for an introduction to the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000193keys. If nothing appears to happen, or if \code{\^P} is echoed,
Guido van Rossum02455691997-07-17 16:21:52 +0000194command line editing isn't available; you'll only be able to use
195backspace to remove characters from the current line.
196
Fred Drake6dc2aae1996-12-13 21:56:03 +0000197The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000198with standard input connected to a tty device, it reads and executes
199commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000200a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000201that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000202
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000203A third way of starting the interpreter is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000204\samp{python -c command [arg] ...}, which
205executes the statement(s) in \code{command}, analogous to the shell's
206\code{-c} option. Since Python statements often contain spaces or other
207characters that are special to the shell, it is best to quote
208\code{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000209
Fred Drakeeee08cd1997-12-04 15:43:15 +0000210Note that there is a difference between \samp{python file} and
211\samp{python <file}. In the latter case, input requests from the
212program, such as calls to \code{input()} and \code{raw_input()}, are
213satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000214until the end by the parser before the program starts executing, the
215program will encounter EOF immediately. In the former case (which is
216usually what you want) they are satisfied from whatever file or device
217is connected to standard input of the Python interpreter.
218
Guido van Rossumb2c65561993-05-12 08:53:36 +0000219When a script file is used, it is sometimes useful to be able to run
220the script and enter interactive mode afterwards. This can be done by
Fred Drakeeee08cd1997-12-04 15:43:15 +0000221passing \code{-i} before the script. (This does not work if the script
Guido van Rossumb2c65561993-05-12 08:53:36 +0000222is read from standard input, for the same reason as explained in the
223previous paragraph.)
224
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000225\subsection{Argument Passing}
Fred Drake6c2176e1998-02-26 21:47:54 +0000226\label{argPassing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000227
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000228When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000229arguments thereafter are passed to the script in the variable
230\code{sys.argv}, which is a list of strings. Its length is at least
231one; when no script and no arguments are given, \code{sys.argv[0]} is
232an empty string. When the script name is given as \code{'-'} (meaning
233standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c
234command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options
235found after \code{-c command} are not consumed by the Python
236interpreter's option processing but left in \code{sys.argv} for the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000237command to handle.
238
239\subsection{Interactive Mode}
Fred Drake6c2176e1998-02-26 21:47:54 +0000240\label{interactive}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000241
Guido van Rossumdd010801991-06-07 14:31:11 +0000242When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000243\emph{interactive mode}. In this mode it prompts for the next command
244with the \emph{primary prompt}, usually three greater-than signs
Fred Drake8842e861998-02-13 07:16:30 +0000245(\samp{>>> }); for continuation lines it prompts with the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000246\emph{secondary prompt},
Fred Drake8842e861998-02-13 07:16:30 +0000247by default three dots (\samp{... }).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000248
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000249The interpreter prints a welcome message stating its version number
250and a copyright notice before printing the first prompt, e.g.:
251
Fred Drake8842e861998-02-13 07:16:30 +0000252\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000253python
Fred Drakeeee08cd1997-12-04 15:43:15 +0000254Python 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5
255Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000256>>>
Fred Drake8842e861998-02-13 07:16:30 +0000257\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000258
Fred Drakea594baf1998-04-03 05:16:31 +0000259\section{The Interpreter and Its Environment}
Fred Drake6c2176e1998-02-26 21:47:54 +0000260\label{interp}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000261
262\subsection{Error Handling}
Fred Drake6c2176e1998-02-26 21:47:54 +0000263\label{error}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000264
265When an error occurs, the interpreter prints an error
266message and a stack trace. In interactive mode, it then returns to
267the primary prompt; when input came from a file, it exits with a
268nonzero exit status after printing
Fred Drakeeee08cd1997-12-04 15:43:15 +0000269the stack trace. (Exceptions handled by an \code{except} clause in a
270\code{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000271unconditionally fatal and cause an exit with a nonzero exit; this
272applies to internal inconsistencies and some cases of running out of
273memory. All error messages are written to the standard error stream;
274normal output from the executed commands is written to standard
275output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000276
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000277Typing the interrupt character (usually Control-C or DEL) to the
278primary or secondary prompt cancels the input and returns to the
279primary prompt.%
280\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000281 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000282}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000283Typing an interrupt while a command is executing raises the
284\code{KeyboardInterrupt} exception, which may be handled by a
285\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000286
Fred Drakea594baf1998-04-03 05:16:31 +0000287\subsection{Executable Python Scripts}
Fred Drake6c2176e1998-02-26 21:47:54 +0000288\label{scripts}
Guido van Rossum4410c751991-06-04 20:22:18 +0000289
Fred Drake6dc2aae1996-12-13 21:56:03 +0000290On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000291executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000292
Fred Drake8842e861998-02-13 07:16:30 +0000293\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000294#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000295\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000296
Fred Drake391564f1998-04-01 23:11:56 +0000297(assuming that the interpreter is on the user's \envvar{PATH}) at the
298beginning of the script and giving the file an executable mode. The
299\samp{\#!} must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000300
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000301\subsection{The Interactive Startup File}
Fred Drake6c2176e1998-02-26 21:47:54 +0000302\label{startup}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000303
Fred Drake8842e861998-02-13 07:16:30 +0000304% XXX This should probably be dumped in an appendix, since most people
305% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000306
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000307When you use Python interactively, it is frequently handy to have some
308standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000309can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000310\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drakeeee08cd1997-12-04 15:43:15 +0000311commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000312shells.
313
314This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000315commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000316explicit source of commands (which otherwise behaves like an
317interactive session). It is executed in the same name space where
318interactive commands are executed, so that objects that it defines or
319imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000320You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000321this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000322
323If you want to read an additional start-up file from the current
Fred Drake72389881998-04-13 01:31:10 +0000324directory, you can program this in the global start-up file,
325e.g.\ \samp{execfile('.pythonrc')}\indexii{.pythonrc.py}{file}. If
326you want to use the startup file in a script, you must do this
327explicitly in the script:
Fred Drake8842e861998-02-13 07:16:30 +0000328
329\begin{verbatim}
330import os
Fred Drake72389881998-04-13 01:31:10 +0000331if os.path.isfile(os.environ['PYTHONSTARTUP']):
332 execfile(os.environ['PYTHONSTARTUP'])
Fred Drake8842e861998-02-13 07:16:30 +0000333\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000334
Fred Drake72389881998-04-13 01:31:10 +0000335
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000336\chapter{An Informal Introduction to Python}
Fred Drake6c2176e1998-02-26 21:47:54 +0000337\label{informal}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000338
339In the following examples, input and output are distinguished by the
Fred Drake8842e861998-02-13 07:16:30 +0000340presence or absence of prompts (\samp{>>> } and \samp{... }): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000341the example, you must type everything after the prompt, when the
342prompt appears; lines that do not begin with a prompt are output from
343the interpreter.%
Guido van Rossum02455691997-07-17 16:21:52 +0000344%\footnote{
345% I'd prefer to use different fonts to distinguish input
346% from output, but the amount of LaTeX hacking that would require
347% is currently beyond my ability.
348%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000349Note that a secondary prompt on a line by itself in an example means
350you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000351
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000352\section{Using Python as a Calculator}
Fred Drake6c2176e1998-02-26 21:47:54 +0000353\label{calculator}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000354
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000355Let's try some simple Python commands. Start the interpreter and wait
Fred Drake8842e861998-02-13 07:16:30 +0000356for the primary prompt, \samp{>>> }. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000357
358\subsection{Numbers}
Fred Drake6c2176e1998-02-26 21:47:54 +0000359\label{numbers}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000360
361The interpreter acts as a simple calculator: you can type an
362expression at it and it will write the value. Expression syntax is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000363straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/}
Fred Drake3f205921998-01-13 18:56:38 +0000364work just like in most other languages (e.g., Pascal or \C{}); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000365can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000366
Fred Drake8842e861998-02-13 07:16:30 +0000367\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000368>>> 2+2
3694
Guido van Rossum6938f061994-08-01 12:22:53 +0000370>>> # This is a comment
371... 2+2
3724
373>>> 2+2 # and a comment on the same line as code
3744
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000375>>> (50-5*6)/4
3765
Guido van Rossum6938f061994-08-01 12:22:53 +0000377>>> # Integer division returns the floor:
378... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003792
Guido van Rossum6938f061994-08-01 12:22:53 +0000380>>> 7/-3
381-3
Fred Drake8842e861998-02-13 07:16:30 +0000382\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000383
Fred Drake391564f1998-04-01 23:11:56 +0000384Like in \C{}, the equal sign (\character{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000385variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000386
Fred Drake8842e861998-02-13 07:16:30 +0000387\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000388>>> width = 20
389>>> height = 5*9
390>>> width * height
391900
Fred Drake8842e861998-02-13 07:16:30 +0000392\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000393%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000394A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000395
Fred Drake8842e861998-02-13 07:16:30 +0000396\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000397>>> x = y = z = 0 # Zero x, y and z
398>>> x
3990
400>>> y
4010
402>>> z
4030
Fred Drake8842e861998-02-13 07:16:30 +0000404\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000405%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000406There is full support for floating point; operators with mixed type
407operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000408
Fred Drake8842e861998-02-13 07:16:30 +0000409\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000410>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004113.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000412>>> 7.0 / 2
4133.5
Fred Drake8842e861998-02-13 07:16:30 +0000414\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000415%
416Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000417a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
418real component are written as \samp{(\var{real}+\var{imag}j)}, or can
419be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000420
Fred Drake8842e861998-02-13 07:16:30 +0000421\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000422>>> 1j * 1J
423(-1+0j)
424>>> 1j * complex(0,1)
425(-1+0j)
426>>> 3+1j*3
427(3+3j)
428>>> (3+1j)*3
429(9+3j)
430>>> (1+2j)/(1+1j)
431(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000432\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000433%
434Complex numbers are always represented as two floating point numbers,
435the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000436number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000437
Fred Drake8842e861998-02-13 07:16:30 +0000438\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000439>>> a=1.5+0.5j
440>>> a.real
4411.5
442>>> a.imag
4430.5
Fred Drake8842e861998-02-13 07:16:30 +0000444\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000445%
446The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000447(\function{float()}, \function{int()} and \function{long()}) don't
448work for complex numbers --- there is no one correct way to convert a
449complex number to a real number. Use \code{abs(\var{z})} to get its
450magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000451
Fred Drake8842e861998-02-13 07:16:30 +0000452\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000453>>> a=1.5+0.5j
454>>> float(a)
455Traceback (innermost last):
456 File "<stdin>", line 1, in ?
457TypeError: can't convert complex to float; use e.g. abs(z)
458>>> a.real
4591.5
460>>> abs(a)
4611.58113883008
Fred Drake8842e861998-02-13 07:16:30 +0000462\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000463%
464In interactive mode, the last printed expression is assigned to the
465variable \code{_}. This means that when you are using Python as a
466desk calculator, it is somewhat easier to continue calculations, for
467example:
468
469\begin{verbatim}
470>>> tax = 17.5 / 100
471>>> price = 3.50
472>>> price * tax
4730.6125
474>>> price + _
4754.1125
476>>> round(_, 2)
4774.11
478\end{verbatim}
479
480This variable should be treated as read-only by the user. Don't
481explicitly assign a value to it --- you would create an independent
482local variable with the same name masking the built-in variable with
483its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000484
485\subsection{Strings}
Fred Drake6c2176e1998-02-26 21:47:54 +0000486\label{strings}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000487
Guido van Rossum02455691997-07-17 16:21:52 +0000488Besides numbers, Python can also manipulate strings, which can be
489expressed in several ways. They can be enclosed in single quotes or
490double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000491
Fred Drake8842e861998-02-13 07:16:30 +0000492\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000493>>> 'spam eggs'
494'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000495>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000496"doesn't"
497>>> "doesn't"
498"doesn't"
499>>> '"Yes," he said.'
500'"Yes," he said.'
501>>> "\"Yes,\" he said."
502'"Yes," he said.'
503>>> '"Isn\'t," she said.'
504'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000505\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000506
Fred Drake8842e861998-02-13 07:16:30 +0000507String literals can span multiple lines in several ways. Newlines can
508be escaped with backslashes, e.g.:
Guido van Rossum02455691997-07-17 16:21:52 +0000509
510\begin{verbatim}
511hello = "This is a rather long string containing\n\
512several lines of text just as you would do in C.\n\
513 Note that whitespace at the beginning of the line is\
514 significant.\n"
515print hello
516\end{verbatim}
517
518which would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000519
Guido van Rossum02455691997-07-17 16:21:52 +0000520\begin{verbatim}
521This is a rather long string containing
522several lines of text just as you would do in C.
523 Note that whitespace at the beginning of the line is significant.
524\end{verbatim}
525
526Or, strings can be surrounded in a pair of matching triple-quotes:
527\code{"""} or \code {'''}. End of lines do not need to be escaped
528when using triple-quotes, but they will be included in the string.
529
530\begin{verbatim}
531print """
532Usage: thingy [OPTIONS]
533 -h Display this usage message
534 -H hostname Hostname to connect to
535"""
536\end{verbatim}
537
538produces the following output:
539
Fred Drake8842e861998-02-13 07:16:30 +0000540\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000541Usage: thingy [OPTIONS]
542 -h Display this usage message
543 -H hostname Hostname to connect to
Fred Drake8842e861998-02-13 07:16:30 +0000544\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000545
Guido van Rossum02455691997-07-17 16:21:52 +0000546The interpreter prints the result of string operations in the same way
547as they are typed for input: inside quotes, and with quotes and other
548funny characters escaped by backslashes, to show the precise
549value. The string is enclosed in double quotes if the string contains
550a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000551quotes. (The \keyword{print} statement, described later, can be used
552to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000553
Fred Drakeeee08cd1997-12-04 15:43:15 +0000554Strings can be concatenated (glued together) with the \code{+}
555operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000556
Fred Drake8842e861998-02-13 07:16:30 +0000557\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000558>>> word = 'Help' + 'A'
559>>> word
560'HelpA'
561>>> '<' + word*5 + '>'
562'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000563\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000564
Guido van Rossum02455691997-07-17 16:21:52 +0000565Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000566the first line above could also have been written \samp{word = 'Help'
Guido van Rossum02455691997-07-17 16:21:52 +0000567'A'}; this only works with two literals, not with arbitrary string expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000568
Fred Drake3f205921998-01-13 18:56:38 +0000569Strings can be subscripted (indexed); like in \C{}, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000570of a string has subscript (index) 0. There is no separate character
571type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000572substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000573separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000574
Fred Drake8842e861998-02-13 07:16:30 +0000575\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000576>>> word[4]
577'A'
578>>> word[0:2]
579'He'
580>>> word[2:4]
581'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000582\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000583
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000584Slice indices have useful defaults; an omitted first index defaults to
585zero, an omitted second index defaults to the size of the string being
586sliced.
587
Fred Drake8842e861998-02-13 07:16:30 +0000588\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000589>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000590'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000591>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000592'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000593\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000594
Fred Drakeeee08cd1997-12-04 15:43:15 +0000595Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
596equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000597
Fred Drake8842e861998-02-13 07:16:30 +0000598\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000599>>> word[:2] + word[2:]
600'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000601>>> word[:3] + word[3:]
602'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000603\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000604
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000605Degenerate slice indices are handled gracefully: an index that is too
606large is replaced by the string size, an upper bound smaller than the
607lower bound returns an empty string.
608
Fred Drake8842e861998-02-13 07:16:30 +0000609\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000610>>> word[1:100]
611'elpA'
612>>> word[10:]
613''
614>>> word[2:1]
615''
Fred Drake8842e861998-02-13 07:16:30 +0000616\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000617
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000618Indices may be negative numbers, to start counting from the right.
619For example:
620
Fred Drake8842e861998-02-13 07:16:30 +0000621\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000622>>> word[-1] # The last character
623'A'
624>>> word[-2] # The last-but-one character
625'p'
626>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000627'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000628>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000629'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000630\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000631
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000632But note that -0 is really the same as 0, so it does not count from
633the right!
634
Fred Drake8842e861998-02-13 07:16:30 +0000635\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000636>>> word[-0] # (since -0 equals 0)
637'H'
Fred Drake8842e861998-02-13 07:16:30 +0000638\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000639
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000640Out-of-range negative slice indices are truncated, but don't try this
641for single-element (non-slice) indices:
642
Fred Drake8842e861998-02-13 07:16:30 +0000643\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000644>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000645'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000646>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000647Traceback (innermost last):
648 File "<stdin>", line 1
649IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000650\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000651
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000652The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000653pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000654character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000655string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000656
Fred Drake8842e861998-02-13 07:16:30 +0000657\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000658 +---+---+---+---+---+
659 | H | e | l | p | A |
660 +---+---+---+---+---+
661 0 1 2 3 4 5
662-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000663\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000664
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000665The first row of numbers gives the position of the indices 0...5 in
666the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000667The slice from \var{i} to \var{j} consists of all characters between
668the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000669
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000670For nonnegative indices, the length of a slice is the difference of
671the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000672\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000673
Fred Drake8842e861998-02-13 07:16:30 +0000674The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000675
Fred Drake8842e861998-02-13 07:16:30 +0000676\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000677>>> s = 'supercalifragilisticexpialidocious'
678>>> len(s)
67934
Fred Drake8842e861998-02-13 07:16:30 +0000680\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000681
682\subsection{Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +0000683\label{lists}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000684
Fred Drakeeee08cd1997-12-04 15:43:15 +0000685Python knows a number of \emph{compound} data types, used to group
686together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000687can be written as a list of comma-separated values (items) between
688square brackets. List items need not all have the same type.
689
Fred Drake8842e861998-02-13 07:16:30 +0000690\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000691>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000692>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000693['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000694\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000695
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000696Like string indices, list indices start at 0, and lists can be sliced,
697concatenated and so on:
698
Fred Drake8842e861998-02-13 07:16:30 +0000699\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000700>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000701'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000702>>> a[3]
7031234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000704>>> a[-2]
705100
706>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000707['eggs', 100]
708>>> a[:2] + ['bacon', 2*2]
709['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000710>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000711['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000712\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000713
Fred Drakeeee08cd1997-12-04 15:43:15 +0000714Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000715individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000716
Fred Drake8842e861998-02-13 07:16:30 +0000717\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000718>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000719['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000720>>> a[2] = a[2] + 23
721>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000722['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000723\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000724
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000725Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000726of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000727
Fred Drake8842e861998-02-13 07:16:30 +0000728\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000729>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000730... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000731>>> a
732[1, 12, 123, 1234]
733>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000734... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000735>>> a
736[123, 1234]
737>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000738... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000739>>> a
740[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000741>>> a[:0] = a # Insert (a copy of) itself at the beginning
742>>> a
743[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000744\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000745
Fred Drake8842e861998-02-13 07:16:30 +0000746The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000747
Fred Drake8842e861998-02-13 07:16:30 +0000748\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000749>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007508
Fred Drake8842e861998-02-13 07:16:30 +0000751\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000752
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000753It is possible to nest lists (create lists containing other lists),
754for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000755
Fred Drake8842e861998-02-13 07:16:30 +0000756\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000757>>> q = [2, 3]
758>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000759>>> len(p)
7603
761>>> p[1]
762[2, 3]
763>>> p[1][0]
7642
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000765>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000766>>> p
767[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000768>>> q
769[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000770\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000771
Fred Drakeeee08cd1997-12-04 15:43:15 +0000772Note that in the last example, \code{p[1]} and \code{q} really refer to
773the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000774
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000775\section{First Steps Towards Programming}
Fred Drake6c2176e1998-02-26 21:47:54 +0000776\label{firstSteps}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000777
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000778Of course, we can use Python for more complicated tasks than adding
779two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000780subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000781
Fred Drake8842e861998-02-13 07:16:30 +0000782\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000783>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000784... # the sum of two elements defines the next
785... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000786>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000787... print b
788... a, b = b, a+b
789...
7901
7911
7922
7933
7945
7958
Fred Drake8842e861998-02-13 07:16:30 +0000796\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000797
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000798This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000799
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000800\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000801
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000802\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000803The first line contains a \emph{multiple assignment}: the variables
804\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000805last line this is used again, demonstrating that the expressions on
806the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000807assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000808
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000809\item
Fred Drake8842e861998-02-13 07:16:30 +0000810The \keyword{while} loop executes as long as the condition (here:
811\code{b < 10}) remains true. In Python, like in \C{}, any non-zero
812integer value is true; zero is false. The condition may also be a
813string or list value, in fact any sequence; anything with a non-zero
814length is true, empty sequences are false. The test used in the
815example is a simple comparison. The standard comparison operators are
816written the same as in \C{}: \code{<}, \code{>}, \code{==}, \code{<=},
817\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000818
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000819\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000820The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000821way of grouping statements. Python does not (yet!) provide an
822intelligent input line editing facility, so you have to type a tab or
823space(s) for each indented line. In practice you will prepare more
824complicated input for Python with a text editor; most text editors have
825an auto-indent facility. When a compound statement is entered
826interactively, it must be followed by a blank line to indicate
827completion (since the parser cannot guess when you have typed the last
828line).
829
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000830\item
Fred Drake8842e861998-02-13 07:16:30 +0000831The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000832given. It differs from just writing the expression you want to write
833(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000834multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000835and a space is inserted between items, so you can format things nicely,
836like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000837
Fred Drake8842e861998-02-13 07:16:30 +0000838\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000839>>> i = 256*256
840>>> print 'The value of i is', i
841The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000842\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000843
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000844A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000845
Fred Drake8842e861998-02-13 07:16:30 +0000846\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000847>>> a, b = 0, 1
848>>> while b < 1000:
849... print b,
850... a, b = b, a+b
851...
8521 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000853\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000854
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000855Note that the interpreter inserts a newline before it prints the next
856prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000857
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000858\end{itemize}
859
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000860
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000861\chapter{More Control Flow Tools}
Fred Drake6c2176e1998-02-26 21:47:54 +0000862\label{moreControl}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000863
Fred Drake8842e861998-02-13 07:16:30 +0000864Besides the \keyword{while} statement just introduced, Python knows
865the usual control flow statements known from other languages, with
866some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000867
Fred Drake391564f1998-04-01 23:11:56 +0000868\section{\keyword{if} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +0000869\label{if}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000870
Fred Drake8842e861998-02-13 07:16:30 +0000871Perhaps the most well-known statement type is the \keyword{if}
872statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000873
Fred Drake8842e861998-02-13 07:16:30 +0000874\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000875>>> if x < 0:
876... x = 0
877... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000878... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000879... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000880... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000881... print 'Single'
882... else:
883... print 'More'
884...
Fred Drake8842e861998-02-13 07:16:30 +0000885\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000886
Fred Drake8842e861998-02-13 07:16:30 +0000887There can be zero or more \keyword{elif} parts, and the \keyword{else}
888part is optional. The keyword `\keyword{elif}' is short for `else
889if', and is useful to avoid excessive indentation. An
890\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif}
891\ldots\ sequence is a substitute for the \emph{switch} or
892% ^^^^
893% Weird spacings happen here if the wrapping of the source text
894% gets changed in the wrong way.
895\emph{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000896
Fred Drake391564f1998-04-01 23:11:56 +0000897\section{\keyword{for} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +0000898\label{for}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000899
Fred Drake8842e861998-02-13 07:16:30 +0000900The \keyword{for} statement in Python differs a bit from what you may be
Fred Drake3f205921998-01-13 18:56:38 +0000901used to in \C{} or Pascal. Rather than always iterating over an
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000902arithmetic progression of numbers (like in Pascal), or leaving the user
Fred Drake3f205921998-01-13 18:56:38 +0000903completely free in the iteration test and step (as \C{}), Python's
Fred Drake8842e861998-02-13 07:16:30 +0000904\keyword{for} statement iterates over the items of any sequence (e.g., a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000905list or a string), in the order that they appear in the sequence. For
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000906example (no pun intended):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000907
Fred Drake8842e861998-02-13 07:16:30 +0000908\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000909>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000910... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000911>>> for x in a:
912... print x, len(x)
913...
914cat 3
915window 6
916defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000917\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000918
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000919It is not safe to modify the sequence being iterated over in the loop
920(this can only happen for mutable sequence types, i.e., lists). If
921you need to modify the list you are iterating over, e.g., duplicate
922selected items, you must iterate over a copy. The slice notation
923makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000924
Fred Drake8842e861998-02-13 07:16:30 +0000925\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000926>>> for x in a[:]: # make a slice copy of the entire list
927... if len(x) > 6: a.insert(0, x)
928...
929>>> a
930['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000931\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000932
Fred Drakee7957181998-04-04 07:17:47 +0000933\section{The \function{range()} Function}
Fred Drake6c2176e1998-02-26 21:47:54 +0000934\label{range}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000935
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000936If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000937function \function{range()} comes in handy. It generates lists
938containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000939
Fred Drake8842e861998-02-13 07:16:30 +0000940\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000941>>> range(10)
942[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000943\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000944
Fred Drake8842e861998-02-13 07:16:30 +0000945The given end point is never part of the generated list;
946\code{range(10)} generates a list of 10 values, exactly the legal
947indices for items of a sequence of length 10. It is possible to let
948the range start at another number, or to specify a different increment
949(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000950
Fred Drake8842e861998-02-13 07:16:30 +0000951\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000952>>> range(5, 10)
953[5, 6, 7, 8, 9]
954>>> range(0, 10, 3)
955[0, 3, 6, 9]
956>>> range(-10, -100, -30)
957[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000958\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000959
Fred Drake8842e861998-02-13 07:16:30 +0000960To iterate over the indices of a sequence, combine \function{range()}
961and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000962
Fred Drake8842e861998-02-13 07:16:30 +0000963\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000964>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000965>>> for i in range(len(a)):
966... print i, a[i]
967...
9680 Mary
9691 had
9702 a
9713 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009724 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000973\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000974
Fred Drake391564f1998-04-01 23:11:56 +0000975\section{\keyword{break} and \keyword{continue} Statements, and
976 \keyword{else} Clauses on Loops}
Fred Drake6c2176e1998-02-26 21:47:54 +0000977\label{break}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000978
Fred Drake8842e861998-02-13 07:16:30 +0000979The \keyword{break} statement, like in \C{}, breaks out of the smallest
980enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000981
Fred Drake8842e861998-02-13 07:16:30 +0000982The \keyword{continue} statement, also borrowed from \C{}, continues
983with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000984
Fred Drake8842e861998-02-13 07:16:30 +0000985Loop statements may have an \code{else} clause; it is executed when
986the loop terminates through exhaustion of the list (with
987\keyword{for}) or when the condition becomes false (with
988\keyword{while}), but not when the loop is terminated by a
989\keyword{break} statement. This is exemplified by the following loop,
990which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000991
Fred Drake8842e861998-02-13 07:16:30 +0000992\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000993>>> for n in range(2, 10):
994... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000995... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000996... print n, 'equals', x, '*', n/x
997... break
998... else:
999... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001000...
Guido van Rossum2292b8e1991-01-23 16:31:24 +000010012 is a prime number
10023 is a prime number
10034 equals 2 * 2
10045 is a prime number
10056 equals 2 * 3
10067 is a prime number
10078 equals 2 * 4
10089 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +00001009\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001010
Fred Drake391564f1998-04-01 23:11:56 +00001011\section{\keyword{pass} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +00001012\label{pass}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001013
Fred Drake8842e861998-02-13 07:16:30 +00001014The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001015It can be used when a statement is required syntactically but the
1016program requires no action.
1017For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001018
Fred Drake8842e861998-02-13 07:16:30 +00001019\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001020>>> while 1:
1021... pass # Busy-wait for keyboard interrupt
1022...
Fred Drake8842e861998-02-13 07:16:30 +00001023\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001024
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001025\section{Defining Functions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001026\label{functions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001027
1028We can create a function that writes the Fibonacci series to an
1029arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001030
Fred Drake8842e861998-02-13 07:16:30 +00001031\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001032>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001033... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001034... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001035... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001036... print b,
1037... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001038...
1039>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001040... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010411 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001042\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001043
Fred Drake8842e861998-02-13 07:16:30 +00001044The keyword \keyword{def} introduces a function \emph{definition}. It
1045must be followed by the function name and the parenthesized list of
1046formal parameters. The statements that form the body of the function
1047start at the next line, indented by a tab stop. The first statement
1048of the function body can optionally be a string literal; this string
1049literal is the function's documentation string, or \dfn{docstring}.
1050There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001051documentation, or to let the user interactively browse through code;
1052it's good practice to include docstrings in code that you write, so
1053try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001054
Fred Drakeeee08cd1997-12-04 15:43:15 +00001055The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001056for the local variables of the function. More precisely, all variable
1057assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001058whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001059in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001060Thus, global variables cannot be directly assigned a value within a
1061function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001062they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001063
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001064The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001065the local symbol table of the called function when it is called; thus,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001066arguments are passed using \emph{call by value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001067\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001068 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001069 description, since if a mutable object is passed, the caller
1070 will see any changes the callee makes to it (e.g., items
1071 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001072}
1073When a function calls another function, a new local symbol table is
1074created for that call.
1075
Fred Drake8842e861998-02-13 07:16:30 +00001076A function definition introduces the function name in the current
1077symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001078has a type that is recognized by the interpreter as a user-defined
1079function. This value can be assigned to another name which can then
1080also be used as a function. This serves as a general renaming
1081mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001082
Fred Drake8842e861998-02-13 07:16:30 +00001083\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001084>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001085<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001086>>> f = fib
1087>>> f(100)
10881 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001089\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001090
Fred Drakeeee08cd1997-12-04 15:43:15 +00001091You might object that \code{fib} is not a function but a procedure. In
Fred Drake3f205921998-01-13 18:56:38 +00001092Python, like in \C{}, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001093value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001094albeit a rather boring one. This value is called \code{None} (it's a
1095built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001096the interpreter if it would be the only value written. You can see it
1097if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001098
Fred Drake8842e861998-02-13 07:16:30 +00001099\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001100>>> print fib(0)
1101None
Fred Drake8842e861998-02-13 07:16:30 +00001102\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001103
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001104It is simple to write a function that returns a list of the numbers of
1105the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001106
Fred Drake8842e861998-02-13 07:16:30 +00001107\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001108>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001109... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001110... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001111... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001112... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001113... result.append(b) # see below
1114... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001115... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001116...
1117>>> f100 = fib2(100) # call it
1118>>> f100 # write the result
1119[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001120\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001121%
Guido van Rossum4410c751991-06-04 20:22:18 +00001122This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001123
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001124\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001125
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001126\item
Fred Drake8842e861998-02-13 07:16:30 +00001127The \keyword{return} statement returns with a value from a function.
1128\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001129the middle of a procedure (falling off the end also returns from a
1130procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001131
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001132\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001133The statement \code{result.append(b)} calls a \emph{method} of the list
1134object \code{result}. A method is a function that `belongs' to an
1135object and is named \code{obj.methodname}, where \code{obj} is some
1136object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001137of a method that is defined by the object's type. Different types
1138define different methods. Methods of different types may have the
1139same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001140own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001141in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001142The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001143list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001144example it is equivalent to \samp{result = result + [b]}, but more
1145efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001146
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001147\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001148
Guido van Rossum02455691997-07-17 16:21:52 +00001149\section{More on Defining Functions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001150\label{defining}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001151
Guido van Rossum02455691997-07-17 16:21:52 +00001152It is also possible to define functions with a variable number of
1153arguments. There are three forms, which can be combined.
1154
1155\subsection{Default Argument Values}
Fred Drake6c2176e1998-02-26 21:47:54 +00001156\label{defaultArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001157
1158The most useful form is to specify a default value for one or more
1159arguments. This creates a function that can be called with fewer
1160arguments than it is defined, e.g.
1161
1162\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001163def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1164 while 1:
1165 ok = raw_input(prompt)
1166 if ok in ('y', 'ye', 'yes'): return 1
1167 if ok in ('n', 'no', 'nop', 'nope'): return 0
1168 retries = retries - 1
1169 if retries < 0: raise IOError, 'refusenik user'
1170 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001171\end{verbatim}
1172
1173This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001174\code{ask_ok('Do you really want to quit?')} or like this:
1175\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001176
1177The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001178in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001179
1180\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001181i = 5
1182def f(arg = i): print arg
1183i = 6
1184f()
Guido van Rossum02455691997-07-17 16:21:52 +00001185\end{verbatim}
1186
Fred Drakeeee08cd1997-12-04 15:43:15 +00001187will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001188
Guido van Rossumaee5e261998-08-07 17:45:09 +00001189\strong{Important warning:} The default value is evaluated only once.
1190This makes a difference when the default is a mutable object such as a
1191list or dictionary. For example, the following function accumulates
1192the arguments passed to it on subsequent calls:
1193
1194\begin{verbatim}
1195def f(a, l = []):
1196 l.append(a)
1197 return a
1198print f(1)
1199print f(2)
1200print f(3)
1201\end{verbatim}
1202
1203This will print
1204
1205\begin{verbatim}
1206[1]
1207[1, 2]
1208[1, 2, 3]
1209\end{verbatim}
1210
1211If you don't want the default to be shared between subsequent calls,
1212you can write the function like this instead:
1213
1214\begin{verbatim}
1215def f(a, l = None):
1216 if l is None:
1217 l = []
1218 l.append(a)
1219 return a
1220\end{verbatim}
1221
Guido van Rossum02455691997-07-17 16:21:52 +00001222\subsection{Keyword Arguments}
Fred Drake6c2176e1998-02-26 21:47:54 +00001223\label{keywordArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001224
1225Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001226keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001227instance, the following function:
1228
1229\begin{verbatim}
1230def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1231 print "-- This parrot wouldn't", action,
1232 print "if you put", voltage, "Volts through it."
1233 print "-- Lovely plumage, the", type
1234 print "-- It's", state, "!"
1235\end{verbatim}
1236
1237could be called in any of the following ways:
1238
1239\begin{verbatim}
1240parrot(1000)
1241parrot(action = 'VOOOOOM', voltage = 1000000)
1242parrot('a thousand', state = 'pushing up the daisies')
1243parrot('a million', 'bereft of life', 'jump')
1244\end{verbatim}
1245
1246but the following calls would all be invalid:
1247
1248\begin{verbatim}
1249parrot() # required argument missing
1250parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1251parrot(110, voltage=220) # duplicate value for argument
1252parrot(actor='John Cleese') # unknown keyword
1253\end{verbatim}
1254
1255In general, an argument list must have any positional arguments
1256followed by any keyword arguments, where the keywords must be chosen
1257from the formal parameter names. It's not important whether a formal
1258parameter has a default value or not. No argument must receive a
1259value more than once --- formal parameter names corresponding to
1260positional arguments cannot be used as keywords in the same calls.
1261
1262When a final formal parameter of the form \code{**\var{name}} is
1263present, it receives a dictionary containing all keyword arguments
1264whose keyword doesn't correspond to a formal parameter. This may be
1265combined with a formal parameter of the form \code{*\var{name}}
1266(described in the next subsection) which receives a tuple containing
1267the positional arguments beyond the formal parameter list.
1268(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1269example, if we define a function like this:
1270
1271\begin{verbatim}
1272def cheeseshop(kind, *arguments, **keywords):
1273 print "-- Do you have any", kind, '?'
1274 print "-- I'm sorry, we're all out of", kind
1275 for arg in arguments: print arg
1276 print '-'*40
1277 for kw in keywords.keys(): print kw, ':', keywords[kw]
1278\end{verbatim}
1279
1280It could be called like this:
1281
1282\begin{verbatim}
1283cheeseshop('Limburger', "It's very runny, sir.",
1284 "It's really very, VERY runny, sir.",
1285 client='John Cleese',
1286 shopkeeper='Michael Palin',
1287 sketch='Cheese Shop Sketch')
1288\end{verbatim}
1289
1290and of course it would print:
1291
1292\begin{verbatim}
1293-- Do you have any Limburger ?
1294-- I'm sorry, we're all out of Limburger
1295It's very runny, sir.
1296It's really very, VERY runny, sir.
1297----------------------------------------
1298client : John Cleese
1299shopkeeper : Michael Palin
1300sketch : Cheese Shop Sketch
1301\end{verbatim}
1302
1303\subsection{Arbitrary Argument Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +00001304\label{arbitraryArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001305
1306Finally, the least frequently used option is to specify that a
1307function can be called with an arbitrary number of arguments. These
1308arguments will be wrapped up in a tuple. Before the variable number
1309of arguments, zero or more normal arguments may occur.
1310
1311\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001312def fprintf(file, format, *args):
1313 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001314\end{verbatim}
1315
Fred Drakea594baf1998-04-03 05:16:31 +00001316
1317\subsection{Lambda Forms}
1318\label{lambda}
1319
1320By popular demand, a few features commonly found in functional
1321programming languages and Lisp have been added to Python. With the
1322\keyword{lambda} keyword, small anonymous functions can be created.
1323Here's a function that returns the sum of its two arguments:
1324\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1325objects are required. They are syntactically restricted to a single
1326expression. Semantically, they are just syntactic sugar for a normal
1327function definition. Like nested function definitions, lambda forms
1328cannot reference variables from the containing scope, but this can be
1329overcome through the judicious use of default argument values, e.g.
1330
1331\begin{verbatim}
1332def make_incrementor(n):
1333 return lambda x, incr=n: x+incr
1334\end{verbatim}
1335
1336\subsection{Documentation Strings}
1337\label{docstrings}
1338
1339There are emerging conventions about the content and formatting of
1340documentation strings.
1341
1342The first line should always be a short, concise summary of the
1343object's purpose. For brevity, it should not explicitly state the
1344object's name or type, since these are available by other means
1345(except if the name happens to be a verb describing a function's
1346operation). This line should begin with a capital letter and end with
1347a period.
1348
1349If there are more lines in the documentation string, the second line
1350should be blank, visually separating the summary from the rest of the
1351description. The following lines should be one of more of paragraphs
1352describing the objects calling conventions, its side effects, etc.
1353
1354The Python parser does not strip indentation from multi-line string
1355literals in Python, so tools that process documentation have to strip
1356indentation. This is done using the following convention. The first
1357non-blank line \emph{after} the first line of the string determines the
1358amount of indentation for the entire documentation string. (We can't
1359use the first line since it is generally adjacent to the string's
1360opening quotes so its indentation is not apparent in the string
1361literal.) Whitespace ``equivalent'' to this indentation is then
1362stripped from the start of all lines of the string. Lines that are
1363indented less should not occur, but if they occur all their leading
1364whitespace should be stripped. Equivalence of whitespace should be
1365tested after expansion of tabs (to 8 spaces, normally).
1366
1367
1368
Guido van Rossum02455691997-07-17 16:21:52 +00001369\chapter{Data Structures}
Fred Drake6c2176e1998-02-26 21:47:54 +00001370\label{structures}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001371
1372This chapter describes some things you've learned about already in
1373more detail, and adds some new things as well.
1374
1375\section{More on Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +00001376\label{moreLists}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001377
1378The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001379of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001380
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001381\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001382
Fred Drakeeee08cd1997-12-04 15:43:15 +00001383\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001384Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001385the element before which to insert, so \code{a.insert(0, x)} inserts at
1386the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1387\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001388
Fred Drakeeee08cd1997-12-04 15:43:15 +00001389\item[\code{append(x)}]
1390Equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001391
Fred Drakeeee08cd1997-12-04 15:43:15 +00001392\item[\code{index(x)}]
1393Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001394It is an error if there is no such item.
1395
Fred Drakeeee08cd1997-12-04 15:43:15 +00001396\item[\code{remove(x)}]
1397Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001398It is an error if there is no such item.
1399
Fred Drakeeee08cd1997-12-04 15:43:15 +00001400\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001401Sort the items of the list, in place.
1402
Fred Drakeeee08cd1997-12-04 15:43:15 +00001403\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001404Reverse the elements of the list, in place.
1405
Fred Drakeeee08cd1997-12-04 15:43:15 +00001406\item[\code{count(x)}]
1407Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001408
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001409\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001410
1411An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001412
Fred Drake8842e861998-02-13 07:16:30 +00001413\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001414>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001415>>> print a.count(333), a.count(66.6), a.count('x')
14162 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001417>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001418>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001419>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001420[66.6, 333, -1, 333, 1, 1234.5, 333]
1421>>> a.index(333)
14221
1423>>> a.remove(333)
1424>>> a
1425[66.6, -1, 333, 1, 1234.5, 333]
1426>>> a.reverse()
1427>>> a
1428[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001429>>> a.sort()
1430>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001431[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001432\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001433
Guido van Rossum02455691997-07-17 16:21:52 +00001434\subsection{Functional Programming Tools}
Fred Drake6c2176e1998-02-26 21:47:54 +00001435\label{functional}
Guido van Rossum02455691997-07-17 16:21:52 +00001436
1437There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001438lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001439
Fred Drake8842e861998-02-13 07:16:30 +00001440\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1441the same type, if possible) consisting of those items from the
1442sequence for which \code{\var{function}(\var{item})} is true. For
1443example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001444
1445\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001446>>> def f(x): return x%2 != 0 and x%3 != 0
1447...
1448>>> filter(f, range(2, 25))
1449[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001450\end{verbatim}
1451
Fred Drake8842e861998-02-13 07:16:30 +00001452\samp{map(\var{function}, \var{sequence})} calls
1453\code{\var{function}(\var{item})} for each of the sequence's items and
1454returns a list of the return values. For example, to compute some
1455cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001456
1457\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001458>>> def cube(x): return x*x*x
1459...
1460>>> map(cube, range(1, 11))
1461[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001462\end{verbatim}
1463
1464More than one sequence may be passed; the function must then have as
1465many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001466corresponding item from each sequence (or \code{None} if some sequence
1467is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001468a function returning its argument(s) is substituted.
1469
1470Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001471\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1472turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001473
1474\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001475>>> seq = range(8)
1476>>> def square(x): return x*x
1477...
1478>>> map(None, seq, map(square, seq))
1479[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001480\end{verbatim}
1481
Fred Drake8842e861998-02-13 07:16:30 +00001482\samp{reduce(\var{func}, \var{sequence})} returns a single value
1483constructed by calling the binary function \var{func} on the first two
1484items of the sequence, then on the result and the next item, and so
1485on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001486
1487\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001488>>> def add(x,y): return x+y
1489...
1490>>> reduce(add, range(1, 11))
149155
Guido van Rossum02455691997-07-17 16:21:52 +00001492\end{verbatim}
1493
1494If there's only one item in the sequence, its value is returned; if
1495the sequence is empty, an exception is raised.
1496
1497A third argument can be passed to indicate the starting value. In this
1498case the starting value is returned for an empty sequence, and the
1499function is first applied to the starting value and the first sequence
1500item, then to the result and the next item, and so on. For example,
1501
1502\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001503>>> def sum(seq):
1504... def add(x,y): return x+y
1505... return reduce(add, seq, 0)
1506...
1507>>> sum(range(1, 11))
150855
1509>>> sum([])
15100
Guido van Rossum02455691997-07-17 16:21:52 +00001511\end{verbatim}
1512
Fred Drakee7957181998-04-04 07:17:47 +00001513\section{The \keyword{del} statement}
Fred Drake6c2176e1998-02-26 21:47:54 +00001514\label{del}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001515
1516There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001517of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001518remove slices from a list (which we did earlier by assignment of an
1519empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001520
Fred Drake8842e861998-02-13 07:16:30 +00001521\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001522>>> a
1523[-1, 1, 66.6, 333, 333, 1234.5]
1524>>> del a[0]
1525>>> a
1526[1, 66.6, 333, 333, 1234.5]
1527>>> del a[2:4]
1528>>> a
1529[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001530\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001531
1532\keyword{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001533
Fred Drake8842e861998-02-13 07:16:30 +00001534\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001535>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001536\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001537
Fred Drakeeee08cd1997-12-04 15:43:15 +00001538Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001539another value is assigned to it). We'll find other uses for
1540\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001541
1542\section{Tuples and Sequences}
Fred Drake6c2176e1998-02-26 21:47:54 +00001543\label{tuples}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001544
1545We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001546indexing and slicing operations. They are two examples of
1547\emph{sequence} data types. Since Python is an evolving language,
1548other sequence data types may be added. There is also another
1549standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001550
1551A tuple consists of a number of values separated by commas, for
1552instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001553
Fred Drake8842e861998-02-13 07:16:30 +00001554\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001555>>> t = 12345, 54321, 'hello!'
1556>>> t[0]
155712345
1558>>> t
1559(12345, 54321, 'hello!')
1560>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001561... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001562>>> u
1563((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001564\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001565
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001566As you see, on output tuples are alway enclosed in parentheses, so
1567that nested tuples are interpreted correctly; they may be input with
1568or without surrounding parentheses, although often parentheses are
1569necessary anyway (if the tuple is part of a larger expression).
1570
1571Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1572from a database, etc. Tuples, like strings, are immutable: it is not
1573possible to assign to the individual items of a tuple (you can
1574simulate much of the same effect with slicing and concatenation,
1575though).
1576
1577A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001578items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001579tuples are constructed by an empty pair of parentheses; a tuple with
1580one item is constructed by following a value with a comma
1581(it is not sufficient to enclose a single value in parentheses).
1582Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001583
Fred Drake8842e861998-02-13 07:16:30 +00001584\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001585>>> empty = ()
1586>>> singleton = 'hello', # <-- note trailing comma
1587>>> len(empty)
15880
1589>>> len(singleton)
15901
1591>>> singleton
1592('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001593\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001594
Fred Drakeeee08cd1997-12-04 15:43:15 +00001595The statement \code{t = 12345, 54321, 'hello!'} is an example of
1596\emph{tuple packing}: the values \code{12345}, \code{54321} and
1597\code{'hello!'} are packed together in a tuple. The reverse operation
1598is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001599
Fred Drake8842e861998-02-13 07:16:30 +00001600\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001601>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001602\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001603
Fred Drakeeee08cd1997-12-04 15:43:15 +00001604This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001605unpacking requires that the list of variables on the left has the same
1606number of elements as the length of the tuple. Note that multiple
1607assignment is really just a combination of tuple packing and tuple
1608unpacking!
1609
Guido van Rossumaee5e261998-08-07 17:45:09 +00001610% XXX This is no longer necessary!
Fred Drakeeee08cd1997-12-04 15:43:15 +00001611Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001612unpacking}. This is supported by enclosing the list of variables in
1613square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001614
Fred Drake8842e861998-02-13 07:16:30 +00001615\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001616>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001617>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001618\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001619
Guido van Rossumaee5e261998-08-07 17:45:09 +00001620% XXX Add a bit on the difference between tuples and lists.
1621% XXX Also explain that a tuple can *contain* a mutable object!
1622
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001623\section{Dictionaries}
Fred Drake6c2176e1998-02-26 21:47:54 +00001624\label{dictionaries}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001625
Fred Drakeeee08cd1997-12-04 15:43:15 +00001626Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001627Dictionaries are sometimes found in other languages as ``associative
1628memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001629indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001630which can be any non-mutable type; strings and numbers can always be
1631keys. Tuples can be used as keys if they contain only strings,
1632numbers, or tuples. You can't use lists as keys, since lists can be
1633modified in place using their \code{append()} method.
1634
Guido van Rossum6938f061994-08-01 12:22:53 +00001635It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001636\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001637(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001638A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001639Placing a comma-separated list of key:value pairs within the
1640braces adds initial key:value pairs to the dictionary; this is also the
1641way dictionaries are written on output.
1642
1643The main operations on a dictionary are storing a value with some key
1644and extracting the value given the key. It is also possible to delete
1645a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001646with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001647If you store using a key that is already in use, the old value
1648associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001649value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001650
Fred Drakeeee08cd1997-12-04 15:43:15 +00001651The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001652keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001653just apply the \code{sort()} method to the list of keys). To check
1654whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001655method of the dictionary.
1656
1657Here is a small example using a dictionary:
1658
Fred Drake8842e861998-02-13 07:16:30 +00001659\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001660>>> tel = {'jack': 4098, 'sape': 4139}
1661>>> tel['guido'] = 4127
1662>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001663{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001664>>> tel['jack']
16654098
1666>>> del tel['sape']
1667>>> tel['irv'] = 4127
1668>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001669{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001670>>> tel.keys()
1671['guido', 'irv', 'jack']
1672>>> tel.has_key('guido')
16731
Fred Drake8842e861998-02-13 07:16:30 +00001674\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001675
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001676\section{More on Conditions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001677\label{conditions}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001678
Fred Drakeeee08cd1997-12-04 15:43:15 +00001679The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001680contain other operators besides comparisons.
1681
Fred Drakeeee08cd1997-12-04 15:43:15 +00001682The comparison operators \code{in} and \code{not in} check whether a value
1683occurs (does not occur) in a sequence. The operators \code{is} and
1684\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001685only matters for mutable objects like lists. All comparison operators
1686have the same priority, which is lower than that of all numerical
1687operators.
1688
Fred Drakeeee08cd1997-12-04 15:43:15 +00001689Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a}
1690is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001691
Fred Drakeeee08cd1997-12-04 15:43:15 +00001692Comparisons may be combined by the Boolean operators \code{and} and
1693\code{or}, and the outcome of a comparison (or of any other Boolean
1694expression) may be negated with \code{not}. These all have lower
1695priorities than comparison operators again; between them, \code{not} has
1696the highest priority, and \code{or} the lowest, so that
1697\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 +00001698course, parentheses can be used to express the desired composition.
1699
Fred Drakeeee08cd1997-12-04 15:43:15 +00001700The Boolean operators \code{and} and \code{or} are so-called
1701\emph{shortcut} operators: their arguments are evaluated from left to
1702right, and evaluation stops as soon as the outcome is determined.
1703E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1704and B and C} does not evaluate the expression C. In general, the
1705return value of a shortcut operator, when used as a general value and
1706not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001707
1708It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001709expression to a variable. For example,
1710
Fred Drake8842e861998-02-13 07:16:30 +00001711\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001712>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1713>>> non_null = string1 or string2 or string3
1714>>> non_null
1715'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001716\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001717
Fred Drake3f205921998-01-13 18:56:38 +00001718Note that in Python, unlike \C{}, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001719
1720\section{Comparing Sequences and Other Types}
Fred Drake6c2176e1998-02-26 21:47:54 +00001721\label{comparing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001722
1723Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001724sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001725first the first two items are compared, and if they differ this
1726determines the outcome of the comparison; if they are equal, the next
1727two items are compared, and so on, until either sequence is exhausted.
1728If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001729the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001730items of two sequences compare equal, the sequences are considered
1731equal. If one sequence is an initial subsequence of the other, the
1732shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001733strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001734examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001735
Fred Drake8842e861998-02-13 07:16:30 +00001736\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001737(1, 2, 3) < (1, 2, 4)
1738[1, 2, 3] < [1, 2, 4]
1739'ABC' < 'C' < 'Pascal' < 'Python'
1740(1, 2, 3, 4) < (1, 2, 4)
1741(1, 2) < (1, 2, -1)
1742(1, 2, 3) = (1.0, 2.0, 3.0)
1743(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001744\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001745
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001746Note that comparing objects of different types is legal. The outcome
1747is deterministic but arbitrary: the types are ordered by their name.
1748Thus, a list is always smaller than a string, a string is always
1749smaller than a tuple, etc. Mixed numeric types are compared according
1750to their numeric value, so 0 equals 0.0, etc.%
1751\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001752 The rules for comparing objects of different types should
1753 not be relied upon; they may change in a future version of
1754 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001755}
1756
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001757
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001758\chapter{Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001759\label{modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001760
Guido van Rossum4410c751991-06-04 20:22:18 +00001761If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001762definitions you have made (functions and variables) are lost.
1763Therefore, if you want to write a somewhat longer program, you are
1764better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001765and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001766\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001767into several files for easier maintenance. You may also want to use a
1768handy function that you've written in several programs without copying
1769its definition into each program.
1770
Guido van Rossum4410c751991-06-04 20:22:18 +00001771To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001772them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001773Such a file is called a \emph{module}; definitions from a module can be
1774\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001775collection of variables that you have access to in a script
1776executed at the top level
1777and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001778
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001779A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001780file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001781a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001782the global variable \code{__name__}. For instance, use your favorite text
1783editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001784with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001785
Fred Drake8842e861998-02-13 07:16:30 +00001786\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001787# Fibonacci numbers module
1788
1789def fib(n): # write Fibonacci series up to n
1790 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001791 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001792 print b,
1793 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001794
1795def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001796 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001797 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001798 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001799 result.append(b)
1800 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001801 return result
Fred Drake8842e861998-02-13 07:16:30 +00001802\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001803
Guido van Rossum4410c751991-06-04 20:22:18 +00001804Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001805following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001806
Fred Drake8842e861998-02-13 07:16:30 +00001807\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001808>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001809\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001810
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001811This does not enter the names of the functions defined in
Fred Drakeeee08cd1997-12-04 15:43:15 +00001812\code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001813directly in the current symbol table; it only enters the module name
Fred Drakeeee08cd1997-12-04 15:43:15 +00001814\code{fibo}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001815there.
1816Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001817
Fred Drake8842e861998-02-13 07:16:30 +00001818\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001819>>> fibo.fib(1000)
18201 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1821>>> fibo.fib2(100)
1822[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001823>>> fibo.__name__
1824'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001825\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001826%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001827If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001828
Fred Drake8842e861998-02-13 07:16:30 +00001829\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001830>>> fib = fibo.fib
1831>>> fib(500)
18321 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001833\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001834
Guido van Rossum02455691997-07-17 16:21:52 +00001835
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001836\section{More on Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001837\label{moreModules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001838
1839A module can contain executable statements as well as function
1840definitions.
1841These statements are intended to initialize the module.
1842They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001843\emph{first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001844time the module is imported somewhere.%
1845\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001846 In fact function definitions are also `statements' that are
1847 `executed'; the execution enters the function name in the
1848 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001849}
1850
1851Each module has its own private symbol table, which is used as the
1852global symbol table by all functions defined in the module.
1853Thus, the author of a module can use global variables in the module
1854without worrying about accidental clashes with a user's global
1855variables.
1856On the other hand, if you know what you are doing you can touch a
1857module's global variables with the same notation used to refer to its
1858functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001859\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001860
1861Modules can import other modules.
1862It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001863\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001864statements at the beginning of a module (or script, for that matter).
1865The imported module names are placed in the importing module's global
1866symbol table.
1867
1868There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001869\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001870statement that imports names from a module directly into the importing
1871module's symbol table.
1872For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001873
Fred Drake8842e861998-02-13 07:16:30 +00001874\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001875>>> from fibo import fib, fib2
1876>>> fib(500)
18771 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001878\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001879
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001880This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001881in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001882defined).
1883
1884There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001885
Fred Drake8842e861998-02-13 07:16:30 +00001886\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001887>>> from fibo import *
1888>>> fib(500)
18891 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001890\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001891
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001892This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001893(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001894
Guido van Rossum02455691997-07-17 16:21:52 +00001895\subsection{The Module Search Path}
Fred Drake6c2176e1998-02-26 21:47:54 +00001896\label{searchPath}
Guido van Rossum02455691997-07-17 16:21:52 +00001897
Guido van Rossumaee5e261998-08-07 17:45:09 +00001898% XXX Need to document that a lone .pyc/.pyo is acceptable too!
1899
Fred Drake391564f1998-04-01 23:11:56 +00001900\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00001901When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001902for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001903and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00001904the environment variable \envvar{PYTHONPATH}. This has the same syntax as
1905the shell variable \envvar{PATH}, i.e., a list of
1906directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001907is not found there, the search continues in an installation-dependent
Fred Drake391564f1998-04-01 23:11:56 +00001908default path; on \UNIX{}, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001909
1910Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001911variable \code{sys.path} which is initialized from the directory
1912containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00001913\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001914Python programs that know what they're doing to modify or replace the
1915module search path. See the section on Standard Modules later.
1916
1917\subsection{``Compiled'' Python files}
1918
1919As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001920use a lot of standard modules, if a file called \file{spam.pyc} exists
1921in the directory where \file{spam.py} is found, this is assumed to
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001922contain an already-``byte-compiled'' version of the module \module{spam}.
Fred Drake8842e861998-02-13 07:16:30 +00001923The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001924\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1925ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001926
Fred Drakeeee08cd1997-12-04 15:43:15 +00001927Normally, you don't need to do anything to create the \file{spam.pyc} file.
1928Whenever \file{spam.py} is successfully compiled, an attempt is made to
1929write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001930this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001931completely, the resulting \file{spam.pyc} file will be recognized as
1932invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001933file is platform independent, so a Python module directory can be
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001934shared by machines of different architectures.
Guido van Rossum02455691997-07-17 16:21:52 +00001935
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001936Some tips for experts:
1937
1938\begin{itemize}
1939
1940\item
1941When the Python interpreter is invoked with the \code{-O} flag,
1942optimized code is generated and stored in \file{.pyo} files.
1943The optimizer currently doesn't help much; it only removes
1944\keyword{assert} statements and \code{SET_LINENO} instructions.
1945When \code{-O} is used, \emph{all} bytecode is optimized; \code{.pyc}
1946files are ignored and \code{.py} files are compiled to optimized
1947bytecode.
1948
1949\item
1950A program doesn't run any faster when it is read from a
1951\file{.pyc} or \file{.pyo} file than when it is read from a \file{.py}
1952file; the only thing that's faster about \file{.pyc} or \file{.pyo}
1953files is the speed with which they are loaded.
1954
1955\item
Guido van Rossum002f7aa1998-06-28 19:16:38 +00001956When a script is run by giving its name on the command line, the
1957bytecode for the script is never written to a \file{.pyc} or
1958\file{.pyo} file. Thus, the startup time of a script may be reduced
1959by moving most of its code to a module and having a small bootstrap
1960script that imports that module.
1961
1962\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001963It is possible to have a file called \file{spam.pyc} (or
1964\file{spam.pyo} when \code{-O} is used) without a module
1965\file{spam.py} in the same module. This can be used to distribute
1966a library of Python code in a form that is moderately hard to reverse
1967engineer.
1968
1969\item
1970The module \module{compileall}\refstmodindex{compileall} can create
1971\file{.pyc} files (or \file{.pyo} files when \code{-O} is used) for
1972all modules in a directory.
1973
1974\end{itemize}
1975
Guido van Rossum02455691997-07-17 16:21:52 +00001976
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001977\section{Standard Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001978\label{standardModules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001979
Guido van Rossum4410c751991-06-04 20:22:18 +00001980Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001981document, the \emph{Python Library Reference} (``Library Reference''
1982hereafter). Some modules are built into the interpreter; these
1983provide access to operations that are not part of the core of the
1984language but are nevertheless built in, either for efficiency or to
1985provide access to operating system primitives such as system calls.
1986The set of such modules is a configuration option; e.g., the
1987\module{amoeba} module is only provided on systems that somehow
1988support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00001989attention: \module{sys}\refstmodindex{sys}, which is built into every
1990Python interpreter. The variables \code{sys.ps1} and \code{sys.ps2}
1991define the strings used as primary and secondary prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001992
Fred Drake8842e861998-02-13 07:16:30 +00001993\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001994>>> import sys
1995>>> sys.ps1
1996'>>> '
1997>>> sys.ps2
1998'... '
1999>>> sys.ps1 = 'C> '
2000C> print 'Yuck!'
2001Yuck!
2002C>
Fred Drake8842e861998-02-13 07:16:30 +00002003\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002004
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002005These two variables are only defined if the interpreter is in
2006interactive mode.
2007
2008The variable
Fred Drakeeee08cd1997-12-04 15:43:15 +00002009\code{sys.path}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002010is a list of strings that determine the interpreter's search path for
2011modules.
2012It is initialized to a default path taken from the environment variable
Fred Drake391564f1998-04-01 23:11:56 +00002013\envvar{PYTHONPATH}, or from a built-in default if \envvar{PYTHONPATH}
2014is not set. You can modify it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002015
Fred Drake8842e861998-02-13 07:16:30 +00002016\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002017>>> import sys
2018>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00002019\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002020
Fred Drakee7957181998-04-04 07:17:47 +00002021\section{The \function{dir()} Function}
Fred Drake6c2176e1998-02-26 21:47:54 +00002022\label{dir}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002023
Fred Drake8842e861998-02-13 07:16:30 +00002024The built-in function \function{dir()} is used to find out which names
2025a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002026
Fred Drake8842e861998-02-13 07:16:30 +00002027\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002028>>> import fibo, sys
2029>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00002030['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002031>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00002032['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
2033'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
2034'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00002035\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002036
Fred Drake8842e861998-02-13 07:16:30 +00002037Without arguments, \function{dir()} lists the names you have defined
2038currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002039
Fred Drake8842e861998-02-13 07:16:30 +00002040\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002041>>> a = [1, 2, 3, 4, 5]
2042>>> import fibo, sys
2043>>> fib = fibo.fib
2044>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00002045['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00002046\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002047
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002048Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002049
Fred Drake8842e861998-02-13 07:16:30 +00002050\function{dir()} does not list the names of built-in functions and
2051variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00002052standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002053
Fred Drake8842e861998-02-13 07:16:30 +00002054\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00002055>>> import __builtin__
2056>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00002057['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
2058'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2059'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
2060'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
2061'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
2062'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
2063'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
2064'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
2065'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00002066\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002067
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002068\section{Packages}
2069
2070Packages are a way of structuring Python's module namespace
2071by using ``dotted module names''. For example, the module name \module{A.B}
2072designates a submodule named \samp{B} in a package named \samp{A}. Just like the
2073use of modules saves the authors of different modules from having to
2074worry about each other's global variable names, the use of dotted
2075module names saves the authors of multi-module packages like NumPy or
2076PIL from having to worry about each other's module names.
2077
2078Suppose you want to design a collection of modules (a ``package'') for
2079the uniform handling of sound files and sound data. There are many
2080different sound file formats (usually recognized by their extension,
2081e.g. \file{.wav}, \file{.aiff}, \file{.au}), so you may need to create
2082and maintain a growing collection of modules for the conversion
2083between the various file formats. There are also many different
2084operations you might want to perform on sound data (e.g. mixing,
2085adding echo, applying an equalizer function, creating an artificial
2086stereo effect), so in addition you will be writing a never-ending
2087stream of modules to perform these operations. Here's a possible
2088structure for your package (expressed in terms of a hierarchical
2089filesystem):
2090
2091\begin{verbatim}
2092Sound/ Top-level package
2093 __init__.py Initialize the sound package
2094 Formats/ Subpackage for file format conversions
2095 __init__.py
2096 wavread.py
2097 wavwrite.py
2098 aiffread.py
2099 aiffwrite.py
2100 auread.py
2101 auwrite.py
2102 ...
2103 Effects/ Subpackage for sound effects
2104 __init__.py
2105 echo.py
2106 surround.py
2107 reverse.py
2108 ...
2109 Filters/ Subpackage for filters
2110 __init__.py
2111 equalizer.py
2112 vocoder.py
2113 karaoke.py
2114 ...
2115\end{verbatim}
2116The \file{__init__.py} files are required to make Python treat the
2117directories as containing packages; this is done to prevent
2118directories with a common name, such as \samp{string}, from
2119unintentionally hiding valid modules that occur later on the module
2120search path. In the simplest case, \file{__init__.py} can just be an
2121empty file, but it can also execute initialization code for the
2122package or set the \code{__all__} variable, described later.
2123
2124Users of the package can import individual modules from the
2125package, for example:
2126
2127\begin{verbatim}
2128import Sound.Effects.echo
2129\end{verbatim}
2130This loads the submodule \module{Sound.Effects.echo}. It must be referenced
2131with its full name, e.g.
2132
2133\begin{verbatim}
2134Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
2135\end{verbatim}
2136An alternative way of importing the submodule is:
2137
2138\begin{verbatim}
2139from Sound.Effects import echo
2140\end{verbatim}
2141This also loads the submodule \module{echo}, and makes it available without
2142its package prefix, so it can be used as follows:
2143
2144\begin{verbatim}
2145echo.echofilter(input, output, delay=0.7, atten=4)
2146\end{verbatim}
2147
2148Yet another variation is to import the desired function or variable directly:
2149
2150\begin{verbatim}
2151from Sound.Effects.echo import echofilter
2152\end{verbatim}
2153
2154Again, this loads the submodule \module{echo}, but this makes its function
2155echofilter directly available:
2156
2157\begin{verbatim}
2158echofilter(input, output, delay=0.7, atten=4)
2159\end{verbatim}
2160
2161Note that when using \code{from \var{package} import \var{item}}, the
2162item can be either a submodule (or subpackage) of the package, or some
2163other name defined in the package, like a function, class or
2164variable. The \code{import} statement first tests whether the item is
2165defined in the package; if not, it assumes it is a module and attempts
2166to load it. If it fails to find it, \exception{ImportError} is raised.
2167
2168Contrarily, when using syntax like \code{import
2169\var{item.subitem.subsubitem}}, each item except for the last must be
2170a package; the last item can be a module or a package but can't be a
2171class or function or variable defined in the previous item.
2172
2173\subsection{Importing * From a Package}
2174%The \code{__all__} Attribute
2175
2176Now what happens when the user writes \code{from Sound.Effects import
2177*}? Ideally, one would hope that this somehow goes out to the
2178filesystem, finds which submodules are present in the package, and
2179imports them all. Unfortunately, this operation does not work very
2180well on Mac and Windows platforms, where the filesystem does not
2181always have accurate information about the case of a filename! On
2182these platforms, there is no guaranteed way to know whether a file
2183\file{ECHO.PY} should be imported as a module \module{echo},
2184\module{Echo} or \module{ECHO}. (For example, Windows 95 has the
2185annoying practice of showing all file names with a capitalized first
2186letter.) The DOS 8+3 filename restriction adds another interesting
2187problem for long module names.
2188
2189The only solution is for the package author to provide an explicit
2190index of the package. The import statement uses the following
2191convention: if a package's \file{__init__.py} code defines a list named
2192\code{__all__}, it is taken to be the list of module names that should be imported
2193when \code{from \var{package} import *} is
2194encountered. It is up to the package author to keep this list
2195up-to-date when a new version of the package is released. Package
2196authors may also decide not to support it, if they don't see a use for
2197importing * from their package. For example, the file
2198\code{Sounds/Effects/__init__.py} could contain the following code:
2199
2200\begin{verbatim}
2201__all__ = ["echo", "surround", "reverse"]
2202\end{verbatim}
2203
2204This would mean that \code{from Sound.Effects import *} would
2205import the three named submodules of the \module{Sound} package.
2206
2207If \code{__all__} is not defined, the statement \code{from Sound.Effects
2208import *} does \emph{not} import all submodules from the package
2209\module{Sound.Effects} into the current namespace; it only ensures that the
2210package \module{Sound.Effects} has been imported (possibly running its
2211initialization code, \file{__init__.py}) and then imports whatever names are
2212defined in the package. This includes any names defined (and
2213submodules explicitly loaded) by \file{__init__.py}. It also includes any
2214submodules of the package that were explicitly loaded by previous
2215import statements, e.g.
2216
2217\begin{verbatim}
2218import Sound.Effects.echo
2219import Sound.Effects.surround
2220from Sound.Effects import *
2221\end{verbatim}
2222
2223
2224In this example, the echo and surround modules are imported in the
2225current namespace because they are defined in the \module{Sound.Effects}
2226package when the \code{from...import} statement is executed. (This also
2227works when \code{__all__} is defined.)
2228
2229Note that in general the practicing of importing * from a module or
2230package is frowned upon, since it often causes poorly readable code.
2231However, it is okay to use it to save typing in interactive sessions,
2232and certain modules are designed to export only names that follow
2233certain patterns.
2234
2235Remember, there is nothing wrong with using \code{from Package
2236import specific_submodule}! In fact, this is the
2237recommended notation unless the importing module needs to use
2238submodules with the same name from different packages.
2239
2240
2241\subsection{Intra-package References}
2242
2243The submodules often need to refer to each other. For example, the
2244\module{surround} module might use the \module{echo} module. In fact, such references
2245are so common that the \code{import} statement first looks in the
2246containing package before looking in the standard module search path.
2247Thus, the surround module can simply use \code{import echo} or
2248\code{from echo import echofilter}. If the imported module is not
2249found in the current package (the package of which the current module
2250is a submodule), the \code{import} statement looks for a top-level module
2251with the given name.
2252
2253When packages are structured into subpackages (as with the \module{Sound}
2254package in the example), there's no shortcut to refer to submodules of
2255sibling packages - the full name of the subpackage must be used. For
2256example, if the module \module{Sound.Filters.vocoder} needs to use the \module{echo}
2257module in the \module{Sound.Effects} package, it can use \code{from
2258Sound.Effects import echo}.
2259
2260%(One could design a notation to refer to parent packages, similar to
2261%the use of ".." to refer to the parent directory in Unix and Windows
2262%filesystems. In fact, the \module{ni} module, which was the
2263%ancestor of this package system, supported this using \code{__} for
2264%the package containing the current module,
2265%\code{__.__} for the parent package, and so on. This feature was dropped
2266%because of its awkwardness; since most packages will have a relative
2267%shallow substructure, this is no big loss.)
2268
2269
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002270
Guido van Rossum02455691997-07-17 16:21:52 +00002271\chapter{Input and Output}
Fred Drake6c2176e1998-02-26 21:47:54 +00002272\label{io}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002273
Guido van Rossum02455691997-07-17 16:21:52 +00002274There are several ways to present the output of a program; data can be
2275printed in a human-readable form, or written to a file for future use.
2276This chapter will discuss some of the possibilities.
2277
2278\section{Fancier Output Formatting}
Fred Drakeeee08cd1997-12-04 15:43:15 +00002279So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00002280statements} and the \keyword{print} statement. (A third way is using
2281the \method{write()} method of file objects; the standard output file
2282can be referenced as \code{sys.stdout}. See the Library Reference for
2283more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002284
2285Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00002286simply printing space-separated values. There are two ways to format
2287your output; the first way is to do all the string handling yourself;
2288using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00002289lay-out you can imagine. The standard module
2290\module{string}\refstmodindex{string} contains some useful operations
2291for padding strings to a given column width;
Guido van Rossum02455691997-07-17 16:21:52 +00002292these will be discussed shortly. The second way is to use the
2293\code{\%} operator with a string as the left argument. \code{\%}
Fred Drake8842e861998-02-13 07:16:30 +00002294interprets the left argument as a \C{} \cfunction{sprintf()}-style
2295format string to be applied to the right argument, and returns the
2296string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002297
2298One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00002299Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00002300the \function{repr()} function, or just write the value between
2301reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002302
Fred Drake8842e861998-02-13 07:16:30 +00002303\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002304>>> x = 10 * 3.14
2305>>> y = 200*200
2306>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2307>>> print s
2308The value of x is 31.4, and y is 40000...
2309>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00002310... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00002311>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002312>>> ps
2313'[31.4, 40000]'
2314>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00002315... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002316>>> hellos = `hello`
2317>>> print hellos
2318'hello, world\012'
2319>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002320... `x, y, ('spam', 'eggs')`
2321"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00002322\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002323
Guido van Rossum6938f061994-08-01 12:22:53 +00002324Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002325
Fred Drake8842e861998-02-13 07:16:30 +00002326\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002327>>> import string
2328>>> for x in range(1, 11):
2329... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
2330... # Note trailing comma on previous line
2331... print string.rjust(`x*x*x`, 4)
2332...
2333 1 1 1
2334 2 4 8
2335 3 9 27
2336 4 16 64
2337 5 25 125
2338 6 36 216
2339 7 49 343
2340 8 64 512
2341 9 81 729
234210 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002343>>> for x in range(1,11):
2344... print '%2d %3d %4d' % (x, x*x, x*x*x)
2345...
2346 1 1 1
2347 2 4 8
2348 3 9 27
2349 4 16 64
2350 5 25 125
2351 6 36 216
2352 7 49 343
2353 8 64 512
2354 9 81 729
235510 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002356\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002357
Fred Drake8842e861998-02-13 07:16:30 +00002358(Note that one space between each column was added by the way
2359\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002360
Fred Drake8842e861998-02-13 07:16:30 +00002361This example demonstrates the function \function{string.rjust()},
2362which right-justifies a string in a field of a given width by padding
2363it with spaces on the left. There are similar functions
2364\function{string.ljust()} and \function{string.center()}. These
2365functions do not write anything, they just return a new string. If
2366the input string is too long, they don't truncate it, but return it
2367unchanged; this will mess up your column lay-out but that's usually
2368better than the alternative, which would be lying about a value. (If
2369you really want truncation you can always add a slice operation, as in
2370\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002371
Fred Drake8842e861998-02-13 07:16:30 +00002372There is another function, \function{string.zfill()}, which pads a
2373numeric string on the left with zeros. It understands about plus and
2374minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002375
Fred Drake8842e861998-02-13 07:16:30 +00002376\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002377>>> string.zfill('12', 5)
2378'00012'
2379>>> string.zfill('-3.14', 7)
2380'-003.14'
2381>>> string.zfill('3.14159265359', 5)
2382'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002383\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002384%
2385Using the \code{\%} operator looks like this:
2386
2387\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002388>>> import math
2389>>> print 'The value of PI is approximately %5.3f.' % math.pi
2390The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002391\end{verbatim}
2392
2393If there is more than one format in the string you pass a tuple as
2394right operand, e.g.
2395
2396\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002397>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2398>>> for name, phone in table.items():
2399... print '%-10s ==> %10d' % (name, phone)
2400...
2401Jack ==> 4098
2402Dcab ==> 8637678
2403Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002404\end{verbatim}
2405
Fred Drake3f205921998-01-13 18:56:38 +00002406Most formats work exactly as in \C{} and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002407type; however, if you don't you get an exception, not a core dump.
2408The \verb\%s\ format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002409not a string object, it is converted to string using the
2410\function{str()} built-in function. Using \code{*} to pass the width
2411or precision in as a separate (integer) argument is supported. The
2412\C{} formats \verb\%n\ and \verb\%p\ are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002413
2414If you have a really long format string that you don't want to split
2415up, it would be nice if you could reference the variables to be
2416formatted by name instead of by position. This can be done by using
Fred Drake3f205921998-01-13 18:56:38 +00002417an extension of \C{} formats using the form \verb\%(name)format\, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002418
2419\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002420>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2421>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2422Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002423\end{verbatim}
2424
2425This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002426\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002427local variables.
2428
2429\section{Reading and Writing Files}
Fred Drake6c2176e1998-02-26 21:47:54 +00002430\label{files}
2431
Guido van Rossum02455691997-07-17 16:21:52 +00002432% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002433\function{open()}\bifuncindex{open} returns a file
2434object\obindex{file}, and is most commonly used with two arguments:
2435\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002436
Fred Drake8842e861998-02-13 07:16:30 +00002437\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002438>>> f=open('/tmp/workfile', 'w')
2439>>> print f
2440<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002441\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002442
Guido van Rossum02455691997-07-17 16:21:52 +00002443The first argument is a string containing the filename. The second
2444argument is another string containing a few characters describing the
2445way in which the file will be used. \var{mode} can be \code{'r'} when
2446the file will only be read, \code{'w'} for only writing (an existing
2447file with the same name will be erased), and \code{'a'} opens the file
2448for appending; any data written to the file is automatically added to
2449the end. \code{'r+'} opens the file for both reading and writing.
2450The \var{mode} argument is optional; \code{'r'} will be assumed if
2451it's omitted.
2452
Fred Drake391564f1998-04-01 23:11:56 +00002453On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00002454mode opens the file in binary mode, so there are also modes like
2455\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2456distinction between text and binary files; the end-of-line characters
2457in text files are automatically altered slightly when data is read or
2458written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002459\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2460\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00002461writing such files. (Note that the precise semantics of text mode on
2462the Macintosh depends on the underlying \C{} library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00002463
Fred Drakea594baf1998-04-03 05:16:31 +00002464\subsection{Methods of File Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002465\label{fileMethods}
Guido van Rossum02455691997-07-17 16:21:52 +00002466
2467The rest of the examples in this section will assume that a file
2468object called \code{f} has already been created.
2469
2470To read a file's contents, call \code{f.read(\var{size})}, which reads
2471some quantity of data and returns it as a string. \var{size} is an
2472optional numeric argument. When \var{size} is omitted or negative,
2473the entire contents of the file will be read and returned; it's your
2474problem if the file is twice as large as your machine's memory.
2475Otherwise, at most \var{size} bytes are read and returned. If the end
2476of the file has been reached, \code{f.read()} will return an empty
2477string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002478\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002479>>> f.read()
2480'This is the entire file.\012'
2481>>> f.read()
2482''
Fred Drake8842e861998-02-13 07:16:30 +00002483\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002484
Guido van Rossum02455691997-07-17 16:21:52 +00002485\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002486character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002487omitted on the last line of the file if the file doesn't end in a
2488newline. This makes the return value unambiguous; if
2489\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002490been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002491string containing only a single newline.
2492
Fred Drake8842e861998-02-13 07:16:30 +00002493\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002494>>> f.readline()
2495'This is the first line of the file.\012'
2496>>> f.readline()
2497'Second line of the file\012'
2498>>> f.readline()
2499''
Fred Drake8842e861998-02-13 07:16:30 +00002500\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002501
Fred Drakeeee08cd1997-12-04 15:43:15 +00002502\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002503a list containing all the lines of data in the file.
2504
Fred Drake8842e861998-02-13 07:16:30 +00002505\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002506>>> f.readlines()
2507['This is the first line of the file.\012', 'Second line of the file\012']
Fred Drake8842e861998-02-13 07:16:30 +00002508\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002509
Guido van Rossum02455691997-07-17 16:21:52 +00002510\code{f.write(\var{string})} writes the contents of \var{string} to
2511the file, returning \code{None}.
2512
Fred Drake8842e861998-02-13 07:16:30 +00002513\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002514>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002515\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002516
Guido van Rossum02455691997-07-17 16:21:52 +00002517\code{f.tell()} returns an integer giving the file object's current
2518position in the file, measured in bytes from the beginning of the
2519file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002520\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002521computed from adding \var{offset} to a reference point; the reference
2522point is selected by the \var{from_what} argument. A \var{from_what}
2523value of 0 measures from the beginning of the file, 1 uses the current
2524file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002525\var{from_what} can be omitted and defaults to 0, using the beginning
2526of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002527
Fred Drake8842e861998-02-13 07:16:30 +00002528\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002529>>> f=open('/tmp/workfile', 'r+')
2530>>> f.write('0123456789abcdef')
2531>>> f.seek(5) # Go to the 5th byte in the file
2532>>> f.read(1)
2533'5'
2534>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2535>>> f.read(1)
2536'd'
Fred Drake8842e861998-02-13 07:16:30 +00002537\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002538
Guido van Rossum02455691997-07-17 16:21:52 +00002539When you're done with a file, call \code{f.close()} to close it and
2540free up any system resources taken up by the open file. After calling
2541\code{f.close()}, attempts to use the file object will automatically fail.
2542
Fred Drake8842e861998-02-13 07:16:30 +00002543\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002544>>> f.close()
2545>>> f.read()
2546Traceback (innermost last):
2547 File "<stdin>", line 1, in ?
2548ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002549\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002550
Fred Drake8842e861998-02-13 07:16:30 +00002551File objects have some additional methods, such as \method{isatty()}
2552and \method{truncate()} which are less frequently used; consult the
2553Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002554
Fred Drakea594baf1998-04-03 05:16:31 +00002555\subsection{The \module{pickle} Module}
Fred Drake6c2176e1998-02-26 21:47:54 +00002556\label{pickle}
Fred Drake391564f1998-04-01 23:11:56 +00002557\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00002558
2559Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002560bit more effort, since the \method{read()} method only returns
2561strings, which will have to be passed to a function like
2562\function{string.atoi()}, which takes a string like \code{'123'} and
2563returns its numeric value 123. However, when you want to save more
2564complex data types like lists, dictionaries, or class instances,
2565things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002566
2567Rather than have users be constantly writing and debugging code to
2568save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002569\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002570any Python object (even some forms of Python code!), and convert it to
2571a string representation; this process is called \dfn{pickling}.
2572Reconstructing the object from the string representation is called
2573\dfn{unpickling}. Between pickling and unpickling, the string
2574representing the object may have been stored in a file or data, or
2575sent over a network connection to some distant machine.
2576
2577If you have an object \code{x}, and a file object \code{f} that's been
2578opened for writing, the simplest way to pickle the object takes only
2579one line of code:
2580
Fred Drake8842e861998-02-13 07:16:30 +00002581\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002582pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002583\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002584
Fred Drake8842e861998-02-13 07:16:30 +00002585To unpickle the object again, if \code{f} is a file object which has
2586been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002587
Fred Drake8842e861998-02-13 07:16:30 +00002588\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002589x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002590\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002591
Guido van Rossum02455691997-07-17 16:21:52 +00002592(There are other variants of this, used when pickling many objects or
2593when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002594complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002595
Fred Drake8842e861998-02-13 07:16:30 +00002596\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002597stored and reused by other programs or by a future invocation of the
2598same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002599object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002600write Python extensions take care to ensure that new data types such
Fred Drake72389881998-04-13 01:31:10 +00002601as matrices can be properly pickled and unpickled.
Guido van Rossum02455691997-07-17 16:21:52 +00002602
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002603
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002604
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002605\chapter{Errors and Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002606\label{errors}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002607
2608Until now error messages haven't been more than mentioned, but if you
2609have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002610(at least) two distinguishable kinds of errors: \emph{syntax errors}
2611and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002612
2613\section{Syntax Errors}
Fred Drake6c2176e1998-02-26 21:47:54 +00002614\label{syntaxErrors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002615
2616Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002617kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002618
Fred Drake8842e861998-02-13 07:16:30 +00002619\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002620>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002621 File "<stdin>", line 1
2622 while 1 print 'Hello world'
2623 ^
2624SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002625\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002626
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002627The parser repeats the offending line and displays a little `arrow'
2628pointing at the earliest point in the line where the error was detected.
2629The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002630\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002631the arrow: in the example, the error is detected at the keyword
Fred Drake391564f1998-04-01 23:11:56 +00002632\keyword{print}, since a colon (\character{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002633File name and line number are printed so you know where to look in case
2634the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002635
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002636\section{Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002637\label{exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002638
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002639Even if a statement or expression is syntactically correct, it may
2640cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002641Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002642not unconditionally fatal: you will soon learn how to handle them in
2643Python programs. Most exceptions are not handled by programs,
2644however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002645
Fred Drake8842e861998-02-13 07:16:30 +00002646\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002647>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002648Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002649 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002650ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002651>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002652Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002653 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002654NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002655>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002656Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002657 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002658TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002659\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002660
Guido van Rossumb2c65561993-05-12 08:53:36 +00002661The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002662Exceptions come in different types, and the type is printed as part of
2663the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002664\exception{ZeroDivisionError},
2665\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002666and
Fred Drake8842e861998-02-13 07:16:30 +00002667\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002668The string printed as the exception type is the name of the built-in
2669name for the exception that occurred. This is true for all built-in
2670exceptions, but need not be true for user-defined exceptions (although
2671it is a useful convention).
2672Standard exception names are built-in identifiers (not reserved
2673keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002674
Guido van Rossumb2c65561993-05-12 08:53:36 +00002675The rest of the line is a detail whose interpretation depends on the
2676exception type; its meaning is dependent on the exception type.
2677
2678The preceding part of the error message shows the context where the
2679exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002680In general it contains a stack backtrace listing source lines; however,
2681it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002682
Fred Drake8842e861998-02-13 07:16:30 +00002683The Library Reference lists the built-in exceptions and their
2684meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002685
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002686\section{Handling Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002687\label{handling}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002688
2689It is possible to write programs that handle selected exceptions.
2690Look at the following example, which prints a table of inverses of
2691some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002692
Fred Drake8842e861998-02-13 07:16:30 +00002693\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002694>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002695>>> for x in numbers:
2696... print x,
2697... try:
2698... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002699... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002700... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002701...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000027020.3333 3.00030003
27032.5 0.4
27040 *** has no inverse ***
270510 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002706\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002707
Fred Drake8842e861998-02-13 07:16:30 +00002708The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002709\begin{itemize}
2710\item
Fred Drake8842e861998-02-13 07:16:30 +00002711First, the \emph{try clause}
2712(the statement(s) between the \keyword{try} and \keyword{except}
2713keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002714\item
2715If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002716\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002717is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002718\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002719If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002720the rest of the clause is skipped. Then if its type matches the
2721exception named after the \keyword{except} keyword, the rest of the
2722try clause is skipped, the except clause is executed, and then
2723execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002724\item
2725If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002726except clause, it is passed on to outer \keyword{try} statements; if
2727no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002728and execution stops with a message as shown above.
2729\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002730A \keyword{try} statement may have more than one except clause, to
2731specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002732At most one handler will be executed.
2733Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002734clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002735An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002736e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002737
Fred Drake8842e861998-02-13 07:16:30 +00002738\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002739... except (RuntimeError, TypeError, NameError):
2740... pass
Fred Drake8842e861998-02-13 07:16:30 +00002741\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002742
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002743The last except clause may omit the exception name(s), to serve as a
2744wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002745Use this with extreme caution, since it is easy to mask a real
2746programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002747
Fred Drake8842e861998-02-13 07:16:30 +00002748The \keyword{try} \ldots\ \keyword{except} statement has an optional
2749\emph{else clause}, which must follow all except clauses. It is
2750useful to place code that must be executed if the try clause does not
2751raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002752
2753\begin{verbatim}
Guido van Rossuma4289a71998-07-07 20:18:06 +00002754for arg in sys.argv[1:]:
Fred Drake8842e861998-02-13 07:16:30 +00002755 try:
2756 f = open(arg, 'r')
2757 except IOError:
2758 print 'cannot open', arg
2759 else:
2760 print arg, 'has', len(f.readlines()), 'lines'
2761 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002762\end{verbatim}
2763
2764
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002765When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002766the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002767The presence and type of the argument depend on the exception type.
2768For exception types which have an argument, the except clause may
2769specify a variable after the exception name (or list) to receive the
2770argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002771
Fred Drake8842e861998-02-13 07:16:30 +00002772\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002773>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002774... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002775... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002776... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002777...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002778name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002779\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002780
Guido van Rossumb2c65561993-05-12 08:53:36 +00002781If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002782(`detail') of the message for unhandled exceptions.
2783
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002784Exception handlers don't just handle exceptions if they occur
2785immediately in the try clause, but also if they occur inside functions
2786that are called (even indirectly) in the try clause.
2787For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002788
Fred Drake8842e861998-02-13 07:16:30 +00002789\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002790>>> def this_fails():
2791... x = 1/0
2792...
2793>>> try:
2794... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002795... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002796... print 'Handling run-time error:', detail
2797...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002798Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002799\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002800
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002801
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002802\section{Raising Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002803\label{raising}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002804
Fred Drake8842e861998-02-13 07:16:30 +00002805The \keyword{raise} statement allows the programmer to force a
2806specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002807For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002808
Fred Drake8842e861998-02-13 07:16:30 +00002809\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002810>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002811Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002812 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002813NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002814\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002815
Fred Drake8842e861998-02-13 07:16:30 +00002816The first argument to \keyword{raise} names the exception to be
2817raised. The optional second argument specifies the exception's
2818argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002819
Guido van Rossum02455691997-07-17 16:21:52 +00002820
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002821\section{User-defined Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002822\label{userExceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002823
2824Programs may name their own exceptions by assigning a string to a
2825variable.
2826For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002827
Fred Drake8842e861998-02-13 07:16:30 +00002828\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002829>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002830>>> try:
2831... raise my_exc, 2*2
2832... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002833... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002834...
Guido van Rossum6938f061994-08-01 12:22:53 +00002835My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002836>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002837Traceback (innermost last):
2838 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002839my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002840\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002841
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002842Many standard modules use this to report errors that may occur in
2843functions they define.
2844
Guido van Rossum02455691997-07-17 16:21:52 +00002845
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002846\section{Defining Clean-up Actions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002847\label{cleanup}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002848
Fred Drake8842e861998-02-13 07:16:30 +00002849The \keyword{try} statement has another optional clause which is
2850intended to define clean-up actions that must be executed under all
2851circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002852
Fred Drake8842e861998-02-13 07:16:30 +00002853\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002854>>> try:
2855... raise KeyboardInterrupt
2856... finally:
2857... print 'Goodbye, world!'
2858...
2859Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002860Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002861 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002862KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002863\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002864
Fred Drake8842e861998-02-13 07:16:30 +00002865A \emph{finally clause} is executed whether or not an exception has
2866occurred in the try clause. When an exception has occurred, it is
2867re-raised after the finally clause is executed. The finally clause is
2868also executed ``on the way out'' when the \keyword{try} statement is
2869left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002870
Fred Drake8842e861998-02-13 07:16:30 +00002871A \keyword{try} statement must either have one or more except clauses
2872or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002873
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002874\chapter{Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00002875\label{classes}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002876
2877Python's class mechanism adds classes to the language with a minimum
2878of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002879found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002880do not put an absolute barrier between definition and user, but rather
2881rely on the politeness of the user not to ``break into the
2882definition.'' The most important features of classes are retained
2883with full power, however: the class inheritance mechanism allows
2884multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00002885base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002886same name. Objects can contain an arbitrary amount of private data.
2887
Guido van Rossum16d6e711994-08-08 12:30:22 +00002888In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002889\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002890no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002891shorthands for referencing the object's members from its methods: the
2892method function is declared with an explicit first argument
2893representing the object, which is provided implicitly by the call. As
2894in Smalltalk, classes themselves are objects, albeit in the wider
2895sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002896provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002897or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002898extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002899built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00002900subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002901
Fred Drakea594baf1998-04-03 05:16:31 +00002902\section{A Word About Terminology}
Fred Drake6c2176e1998-02-26 21:47:54 +00002903\label{terminology}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002904
Fred Drake391564f1998-04-01 23:11:56 +00002905Lacking universally accepted terminology to talk about classes, I will
2906make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002907terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002908Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002909
2910I also have to warn you that there's a terminological pitfall for
2911object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002912necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2913unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00002914built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00002915exotic types like files aren't. However, \emph{all} Python types
2916share a little bit of common semantics that is best described by using
2917the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002918
2919Objects have individuality, and multiple names (in multiple scopes)
2920can be bound to the same object. This is known as aliasing in other
2921languages. This is usually not appreciated on a first glance at
2922Python, and can be safely ignored when dealing with immutable basic
2923types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002924(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002925objects such as lists, dictionaries, and most types representing
2926entities outside the program (files, windows, etc.). This is usually
2927used to the benefit of the program, since aliases behave like pointers
2928in some respects. For example, passing an object is cheap since only
2929a pointer is passed by the implementation; and if a function modifies
2930an object passed as an argument, the caller will see the change --- this
2931obviates the need for two different argument passing mechanisms as in
2932Pascal.
2933
2934
Fred Drakea594baf1998-04-03 05:16:31 +00002935\section{Python Scopes and Name Spaces}
Fred Drake6c2176e1998-02-26 21:47:54 +00002936\label{scopes}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002937
2938Before introducing classes, I first have to tell you something about
2939Python's scope rules. Class definitions play some neat tricks with
2940name spaces, and you need to know how scopes and name spaces work to
2941fully understand what's going on. Incidentally, knowledge about this
2942subject is useful for any advanced Python programmer.
2943
2944Let's begin with some definitions.
2945
Fred Drakeeee08cd1997-12-04 15:43:15 +00002946A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002947spaces are currently implemented as Python dictionaries, but that's
2948normally not noticeable in any way (except for performance), and it
2949may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002950built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002951names); the global names in a module; and the local names in a
2952function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002953also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002954spaces is that there is absolutely no relation between names in
2955different name spaces; for instance, two different modules may both
2956define a function ``maximize'' without confusion --- users of the
2957modules must prefix it with the module name.
2958
Fred Drakeeee08cd1997-12-04 15:43:15 +00002959By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002960dot --- for example, in the expression \code{z.real}, \code{real} is
2961an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002962names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002963\code{modname.funcname}, \code{modname} is a module object and
2964\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002965be a straightforward mapping between the module's attributes and the
2966global names defined in the module: they share the same name space!%
2967\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002968 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002969 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002970 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002971 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002972 Obviously, using this violates the abstraction of name space
2973 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002974 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002975}
2976
2977Attributes may be read-only or writable. In the latter case,
2978assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002979you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drake391564f1998-04-01 23:11:56 +00002980also be deleted with the \keyword{del} statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002981\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002982
2983Name spaces are created at different moments and have different
2984lifetimes. The name space containing the built-in names is created
2985when the Python interpreter starts up, and is never deleted. The
2986global name space for a module is created when the module definition
2987is read in; normally, module name spaces also last until the
2988interpreter quits. The statements executed by the top-level
2989invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002990interactively, are considered part of a module called
2991\module{__main__}, so they have their own global name space. (The
2992built-in names actually also live in a module; this is called
2993\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002994
2995The local name space for a function is created when the function is
2996called, and deleted when the function returns or raises an exception
2997that is not handled within the function. (Actually, forgetting would
2998be a better way to describe what actually happens.) Of course,
2999recursive invocations each have their own local name space.
3000
Fred Drakeeee08cd1997-12-04 15:43:15 +00003001A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003002is directly accessible. ``Directly accessible'' here means that an
3003unqualified reference to a name attempts to find the name in the name
3004space.
3005
3006Although scopes are determined statically, they are used dynamically.
3007At any time during execution, exactly three nested scopes are in use
3008(i.e., exactly three name spaces are directly accessible): the
3009innermost scope, which is searched first, contains the local names,
3010the middle scope, searched next, contains the current module's global
3011names, and the outermost scope (searched last) is the name space
3012containing built-in names.
3013
3014Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00003015current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003016the same name space as the global scope: the module's name space.
3017Class definitions place yet another name space in the local scope.
3018
3019It is important to realize that scopes are determined textually: the
3020global scope of a function defined in a module is that module's name
3021space, no matter from where or by what alias the function is called.
3022On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00003023run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003024static name resolution, at ``compile'' time, so don't rely on dynamic
3025name resolution! (In fact, local variables are already determined
3026statically.)
3027
3028A special quirk of Python is that assignments always go into the
3029innermost scope. Assignments do not copy data --- they just
3030bind names to objects. The same is true for deletions: the statement
Fred Drake391564f1998-04-01 23:11:56 +00003031\samp{del x} removes the binding of \code{x} from the name space
3032referenced by the local scope. In fact, all operations that introduce
3033new names use the local scope: in particular, import statements and
3034function definitions bind the module or function name in the local
3035scope. (The \keyword{global} statement can be used to indicate that
3036particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003037
3038
Fred Drakea594baf1998-04-03 05:16:31 +00003039\section{A First Look at Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00003040\label{firstClasses}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003041
3042Classes introduce a little bit of new syntax, three new object types,
3043and some new semantics.
3044
3045
Fred Drakea594baf1998-04-03 05:16:31 +00003046\subsection{Class Definition Syntax}
Fred Drake6c2176e1998-02-26 21:47:54 +00003047\label{classDefinition}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003048
3049The simplest form of class definition looks like this:
3050
3051\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003052class ClassName:
3053 <statement-1>
3054 .
3055 .
3056 .
3057 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003058\end{verbatim}
3059
Fred Drake8842e861998-02-13 07:16:30 +00003060Class definitions, like function definitions (\keyword{def}
3061statements) must be executed before they have any effect. (You could
3062conceivably place a class definition in a branch of an \keyword{if}
3063statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003064
3065In practice, the statements inside a class definition will usually be
3066function definitions, but other statements are allowed, and sometimes
3067useful --- we'll come back to this later. The function definitions
3068inside a class normally have a peculiar form of argument list,
3069dictated by the calling conventions for methods --- again, this is
3070explained later.
3071
3072When a class definition is entered, a new name space is created, and
3073used as the local scope --- thus, all assignments to local variables
3074go into this new name space. In particular, function definitions bind
3075the name of the new function here.
3076
Fred Drakeeee08cd1997-12-04 15:43:15 +00003077When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003078object} is created. This is basically a wrapper around the contents
3079of the name space created by the class definition; we'll learn more
3080about class objects in the next section. The original local scope
3081(the one in effect just before the class definitions was entered) is
Fred Drakea594baf1998-04-03 05:16:31 +00003082reinstated, and the class object is bound here to the class name given
3083in the class definition header (\class{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003084
3085
Fred Drakea594baf1998-04-03 05:16:31 +00003086\subsection{Class Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00003087\label{classObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003088
3089Class objects support two kinds of operations: attribute references
3090and instantiation.
3091
Fred Drakeeee08cd1997-12-04 15:43:15 +00003092\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00003093attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003094names are all the names that were in the class's name space when the
3095class object was created. So, if the class definition looked like
3096this:
3097
3098\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003099class MyClass:
3100 "A simple example class"
3101 i = 12345
3102 def f(x):
3103 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003104\end{verbatim}
3105
Fred Drake8842e861998-02-13 07:16:30 +00003106then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003107references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00003108Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00003109of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00003110attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00003111the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003112
Fred Drakeeee08cd1997-12-04 15:43:15 +00003113Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003114the class object is a parameterless function that returns a new
3115instance of the class. For example, (assuming the above class):
3116
3117\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003118x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003119\end{verbatim}
3120
Fred Drakeeee08cd1997-12-04 15:43:15 +00003121creates a new \emph{instance} of the class and assigns this object to
3122the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003123
3124
Fred Drakea594baf1998-04-03 05:16:31 +00003125\subsection{Instance Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00003126\label{instanceObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003127
3128Now what can we do with instance objects? The only operations
3129understood by instance objects are attribute references. There are
3130two kinds of valid attribute names.
3131
Fred Drakeeee08cd1997-12-04 15:43:15 +00003132The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00003133``instance variables'' in Smalltalk, and to ``data members'' in
3134\Cpp{}. Data attributes need not be declared; like local variables,
3135they spring into existence when they are first assigned to. For
3136example, if \code{x} is the instance of \class{MyClass} created above,
3137the following piece of code will print the value \code{16}, without
3138leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003139
3140\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003141x.counter = 1
3142while x.counter < 10:
3143 x.counter = x.counter * 2
3144print x.counter
3145del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003146\end{verbatim}
3147
3148The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00003149are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003150object. (In Python, the term method is not unique to class instances:
3151other object types can have methods as well, e.g., list objects have
3152methods called append, insert, remove, sort, and so on. However,
3153below, we'll use the term method exclusively to mean methods of class
3154instance objects, unless explicitly stated otherwise.)
3155
3156Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00003157definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003158objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00003159example, \code{x.f} is a valid method reference, since
3160\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00003161\code{MyClass.i} is not. But \code{x.f} is not the same thing as
3162\code{MyClass.f} --- it is a \emph{method object}, not a function
Fred Drakea594baf1998-04-03 05:16:31 +00003163object.%
3164\obindex{method}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003165
3166
Fred Drakea594baf1998-04-03 05:16:31 +00003167\subsection{Method Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00003168\label{methodObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003169
3170Usually, a method is called immediately, e.g.:
3171
3172\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003173x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003174\end{verbatim}
3175
Fred Drake8842e861998-02-13 07:16:30 +00003176In our example, this will return the string \code{'hello world'}.
3177However, it is not necessary to call a method right away: \code{x.f}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003178is a method object, and can be stored away and called at a later
3179moment, for example:
3180
3181\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003182xf = x.f
3183while 1:
3184 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003185\end{verbatim}
3186
Fred Drake8842e861998-02-13 07:16:30 +00003187will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003188
3189What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00003190that \code{x.f()} was called without an argument above, even though
3191the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003192happened to the argument? Surely Python raises an exception when a
3193function that requires an argument is called without any --- even if
3194the argument isn't actually used...
3195
3196Actually, you may have guessed the answer: the special thing about
3197methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00003198function. In our example, the call \code{x.f()} is exactly equivalent
3199to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00003200\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003201with an argument list that is created by inserting the method's object
3202before the first argument.
3203
3204If you still don't understand how methods work, a look at the
3205implementation can perhaps clarify matters. When an instance
3206attribute is referenced that isn't a data attribute, its class is
3207searched. If the name denotes a valid class attribute that is a
3208function object, a method object is created by packing (pointers to)
3209the instance object and the function object just found together in an
3210abstract object: this is the method object. When the method object is
3211called with an argument list, it is unpacked again, a new argument
3212list is constructed from the instance object and the original argument
3213list, and the function object is called with this new argument list.
3214
3215
Fred Drakea594baf1998-04-03 05:16:31 +00003216\section{Random Remarks}
Fred Drake6c2176e1998-02-26 21:47:54 +00003217\label{remarks}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003218
3219[These should perhaps be placed more carefully...]
3220
3221
3222Data attributes override method attributes with the same name; to
3223avoid accidental name conflicts, which may cause hard-to-find bugs in
3224large programs, it is wise to use some kind of convention that
3225minimizes the chance of conflicts, e.g., capitalize method names,
3226prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00003227an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003228
3229
3230Data attributes may be referenced by methods as well as by ordinary
3231users (``clients'') of an object. In other words, classes are not
3232usable to implement pure abstract data types. In fact, nothing in
3233Python makes it possible to enforce data hiding --- it is all based
3234upon convention. (On the other hand, the Python implementation,
Fred Drake3f205921998-01-13 18:56:38 +00003235written in \C{}, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003236access to an object if necessary; this can be used by extensions to
Fred Drake3f205921998-01-13 18:56:38 +00003237Python written in \C{}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003238
3239
3240Clients should use data attributes with care --- clients may mess up
3241invariants maintained by the methods by stamping on their data
3242attributes. Note that clients may add data attributes of their own to
3243an instance object without affecting the validity of the methods, as
3244long as name conflicts are avoided --- again, a naming convention can
3245save a lot of headaches here.
3246
3247
3248There is no shorthand for referencing data attributes (or other
3249methods!) from within methods. I find that this actually increases
3250the readability of methods: there is no chance of confusing local
3251variables and instance variables when glancing through a method.
3252
3253
3254Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00003255\code{self}. This is nothing more than a convention: the name
3256\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003257however, that by not following the convention your code may be less
3258readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00003259a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003260convention.)
3261
3262
3263Any function object that is a class attribute defines a method for
3264instances of that class. It is not necessary that the function
3265definition is textually enclosed in the class definition: assigning a
3266function object to a local variable in the class is also ok. For
3267example:
3268
3269\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003270# Function defined outside the class
3271def f1(self, x, y):
3272 return min(x, x+y)
3273
3274class C:
3275 f = f1
3276 def g(self):
3277 return 'hello world'
3278 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003279\end{verbatim}
3280
Fred Drake8842e861998-02-13 07:16:30 +00003281Now \code{f}, \code{g} and \code{h} are all attributes of class
3282\class{C} that refer to function objects, and consequently they are all
3283methods of instances of \class{C} --- \code{h} being exactly equivalent
3284to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003285the reader of a program.
3286
3287
3288Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00003289\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003290
3291\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003292class Bag:
3293 def empty(self):
3294 self.data = []
3295 def add(self, x):
3296 self.data.append(x)
3297 def addtwice(self, x):
3298 self.add(x)
3299 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003300\end{verbatim}
3301
3302
3303The instantiation operation (``calling'' a class object) creates an
3304empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00003305state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00003306\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003307
Guido van Rossum6938f061994-08-01 12:22:53 +00003308\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003309 def __init__(self):
3310 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00003311\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003312
Fred Drake8842e861998-02-13 07:16:30 +00003313When a class defines an \method{__init__()} method, class
3314instantiation automatically invokes \method{__init__()} for the
3315newly-created class instance. So in the \class{Bag} example, a new
3316and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003317
Guido van Rossum6938f061994-08-01 12:22:53 +00003318\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003319x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00003320\end{verbatim}
3321
Fred Drake8842e861998-02-13 07:16:30 +00003322Of course, the \method{__init__()} method may have arguments for
3323greater flexibility. In that case, arguments given to the class
3324instantiation operator are passed on to \method{__init__()}. For
3325example,
Guido van Rossum6938f061994-08-01 12:22:53 +00003326
Fred Drake8842e861998-02-13 07:16:30 +00003327\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00003328>>> class Complex:
3329... def __init__(self, realpart, imagpart):
3330... self.r = realpart
3331... self.i = imagpart
3332...
3333>>> x = Complex(3.0,-4.5)
3334>>> x.r, x.i
3335(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00003336\end{verbatim}
3337
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003338Methods may reference global names in the same way as ordinary
3339functions. The global scope associated with a method is the module
3340containing the class definition. (The class itself is never used as a
3341global scope!) While one rarely encounters a good reason for using
3342global data in a method, there are many legitimate uses of the global
3343scope: for one thing, functions and modules imported into the global
3344scope can be used by methods, as well as functions and classes defined
3345in it. Usually, the class containing the method is itself defined in
3346this global scope, and in the next section we'll find some good
3347reasons why a method would want to reference its own class!
3348
3349
3350\section{Inheritance}
Fred Drake6c2176e1998-02-26 21:47:54 +00003351\label{inheritance}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003352
3353Of course, a language feature would not be worthy of the name ``class''
3354without supporting inheritance. The syntax for a derived class
3355definition looks as follows:
3356
3357\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003358class DerivedClassName(BaseClassName):
3359 <statement-1>
3360 .
3361 .
3362 .
3363 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003364\end{verbatim}
3365
Fred Drake8842e861998-02-13 07:16:30 +00003366The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003367the derived class definition. Instead of a base class name, an
3368expression is also allowed. This is useful when the base class is
3369defined in another module, e.g.,
3370
3371\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003372class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003373\end{verbatim}
3374
3375Execution of a derived class definition proceeds the same as for a
3376base class. When the class object is constructed, the base class is
3377remembered. This is used for resolving attribute references: if a
3378requested attribute is not found in the class, it is searched in the
3379base class. This rule is applied recursively if the base class itself
3380is derived from some other class.
3381
3382There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00003383\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003384references are resolved as follows: the corresponding class attribute
3385is searched, descending down the chain of base classes if necessary,
3386and the method reference is valid if this yields a function object.
3387
3388Derived classes may override methods of their base classes. Because
3389methods have no special privileges when calling other methods of the
3390same object, a method of a base class that calls another method
3391defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003392a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003393in Python are ``virtual functions''.)
3394
3395An overriding method in a derived class may in fact want to extend
3396rather than simply replace the base class method of the same name.
3397There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003398call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003399occasionally useful to clients as well. (Note that this only works if
3400the base class is defined or imported directly in the global scope.)
3401
3402
Fred Drakea594baf1998-04-03 05:16:31 +00003403\subsection{Multiple Inheritance}
Fred Drake6c2176e1998-02-26 21:47:54 +00003404\label{multiple}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003405
Guido van Rossum6938f061994-08-01 12:22:53 +00003406Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003407class definition with multiple base classes looks as follows:
3408
3409\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003410class DerivedClassName(Base1, Base2, Base3):
3411 <statement-1>
3412 .
3413 .
3414 .
3415 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003416\end{verbatim}
3417
3418The only rule necessary to explain the semantics is the resolution
3419rule used for class attribute references. This is depth-first,
3420left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003421\class{DerivedClassName}, it is searched in \class{Base1}, then
3422(recursively) in the base classes of \class{Base1}, and only if it is
3423not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003424
Fred Drake8842e861998-02-13 07:16:30 +00003425(To some people breadth first --- searching \class{Base2} and
3426\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003427natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003428attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003429one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003430a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003431rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003432\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003433
3434It is clear that indiscriminate use of multiple inheritance is a
3435maintenance nightmare, given the reliance in Python on conventions to
3436avoid accidental name conflicts. A well-known problem with multiple
3437inheritance is a class derived from two classes that happen to have a
3438common base class. While it is easy enough to figure out what happens
3439in this case (the instance will have a single copy of ``instance
3440variables'' or data attributes used by the common base class), it is
3441not clear that these semantics are in any way useful.
3442
3443
Fred Drakea594baf1998-04-03 05:16:31 +00003444\section{Private Variables}
Fred Drake6c2176e1998-02-26 21:47:54 +00003445\label{private}
Guido van Rossum02455691997-07-17 16:21:52 +00003446
Fred Drakea594baf1998-04-03 05:16:31 +00003447There is limited support for class-private
Guido van Rossum02455691997-07-17 16:21:52 +00003448identifiers. Any identifier of the form \code{__spam} (at least two
3449leading underscores, at most one trailing underscore) is now textually
3450replaced with \code{_classname__spam}, where \code{classname} is the
3451current class name with leading underscore(s) stripped. This mangling
3452is done without regard of the syntactic position of the identifier, so
3453it can be used to define class-private instance and class variables,
3454methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003455private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003456may occur when the mangled name would be longer than 255 characters.
3457Outside classes, or when the class name consists of only underscores,
3458no mangling occurs.
3459
3460Name mangling is intended to give classes an easy way to define
3461``private'' instance variables and methods, without having to worry
3462about instance variables defined by derived classes, or mucking with
3463instance variables by code outside the class. Note that the mangling
3464rules are designed mostly to avoid accidents; it still is possible for
3465a determined soul to access or modify a variable that is considered
3466private. This can even be useful, e.g. for the debugger, and that's
3467one reason why this loophole is not closed. (Buglet: derivation of a
3468class with the same name as the base class makes use of private
3469variables of the base class possible.)
3470
3471Notice that code passed to \code{exec}, \code{eval()} or
3472\code{evalfile()} does not consider the classname of the invoking
3473class to be the current class; this is similar to the effect of the
3474\code{global} statement, the effect of which is likewise restricted to
3475code that is byte-compiled together. The same restriction applies to
3476\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3477when referencing \code{__dict__} directly.
3478
3479Here's an example of a class that implements its own
3480\code{__getattr__} and \code{__setattr__} methods and stores all
3481attributes in a private variable, in a way that works in Python 1.4 as
3482well as in previous versions:
3483
3484\begin{verbatim}
3485class VirtualAttributes:
3486 __vdict = None
3487 __vdict_name = locals().keys()[0]
3488
3489 def __init__(self):
3490 self.__dict__[self.__vdict_name] = {}
3491
3492 def __getattr__(self, name):
3493 return self.__vdict[name]
3494
3495 def __setattr__(self, name, value):
3496 self.__vdict[name] = value
3497\end{verbatim}
3498
Fred Drakeaf8a0151998-01-14 14:51:31 +00003499%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003500%potential problems, refrain from using identifiers starting with
3501%double underscore except for predefined uses like \code{__init__}. To
3502%use private names while maintaining future compatibility: refrain from
3503%using the same private name in classes related via subclassing; avoid
3504%explicit (manual) mangling/unmangling; and assume that at some point
3505%in the future, leading double underscore will revert to being just a
3506%naming convention. Discussion on extensive compile-time declarations
3507%are currently underway, and it is impossible to predict what solution
3508%will eventually be chosen for private names. Double leading
3509%underscore is still a candidate, of course --- just not the only one.
3510%It is placed in the distribution in the belief that it is useful, and
3511%so that widespread experience with its use can be gained. It will not
3512%be removed without providing a better solution and a migration path.
3513
Fred Drakea594baf1998-04-03 05:16:31 +00003514\section{Odds and Ends}
Fred Drake6c2176e1998-02-26 21:47:54 +00003515\label{odds}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003516
3517Sometimes it is useful to have a data type similar to the Pascal
Fred Drake3f205921998-01-13 18:56:38 +00003518``record'' or \C{} ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003519items. An empty class definition will do nicely, e.g.:
3520
3521\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003522class Employee:
3523 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003524
Fred Drake8842e861998-02-13 07:16:30 +00003525john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003526
Fred Drake8842e861998-02-13 07:16:30 +00003527# Fill the fields of the record
3528john.name = 'John Doe'
3529john.dept = 'computer lab'
3530john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003531\end{verbatim}
3532
3533
3534A piece of Python code that expects a particular abstract data type
3535can often be passed a class that emulates the methods of that data
3536type instead. For instance, if you have a function that formats some
3537data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003538\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00003539buffer instead, and pass it as an argument.% (Unfortunately, this
3540%technique has its limitations: a class can't define operations that
3541%are accessed by special syntax such as sequence subscripting or
3542%arithmetic operators, and assigning such a ``pseudo-file'' to
3543%\code{sys.stdin} will not cause the interpreter to read further input
3544%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003545
3546
Fred Drake8842e861998-02-13 07:16:30 +00003547Instance method objects have attributes, too: \code{m.im_self} is the
3548object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003549function object corresponding to the method.
3550
Guido van Rossum02455691997-07-17 16:21:52 +00003551\subsection{Exceptions Can Be Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00003552\label{exceptionClasses}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003553
3554User-defined exceptions are no longer limited to being string objects
3555--- they can be identified by classes as well. Using this mechanism it
3556is possible to create extensible hierarchies of exceptions.
3557
3558There are two new valid (semantic) forms for the raise statement:
3559
3560\begin{verbatim}
3561raise Class, instance
3562
3563raise instance
3564\end{verbatim}
3565
Fred Drake8842e861998-02-13 07:16:30 +00003566In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003567or of a class derived from it. The second form is a shorthand for
3568
3569\begin{verbatim}
3570raise instance.__class__, instance
3571\end{verbatim}
3572
3573An except clause may list classes as well as string objects. A class
3574in an except clause is compatible with an exception if it is the same
3575class or a base class thereof (but not the other way around --- an
3576except clause listing a derived class is not compatible with a base
3577class). For example, the following code will print B, C, D in that
3578order:
3579
3580\begin{verbatim}
3581class B:
3582 pass
3583class C(B):
3584 pass
3585class D(C):
3586 pass
3587
3588for c in [B, C, D]:
3589 try:
3590 raise c()
3591 except D:
3592 print "D"
3593 except C:
3594 print "C"
3595 except B:
3596 print "B"
3597\end{verbatim}
3598
Fred Drake8842e861998-02-13 07:16:30 +00003599Note that if the except clauses were reversed (with \samp{except B}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003600first), it would have printed B, B, B --- the first matching except
3601clause is triggered.
3602
3603When an error message is printed for an unhandled exception which is a
3604class, the class name is printed, then a colon and a space, and
3605finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003606\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003607
Guido van Rossum194e57c1995-02-15 15:51:38 +00003608
Guido van Rossum02455691997-07-17 16:21:52 +00003609\chapter{What Now?}
Fred Drake6c2176e1998-02-26 21:47:54 +00003610\label{whatNow}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003611
Guido van Rossum02455691997-07-17 16:21:52 +00003612Hopefully reading this tutorial has reinforced your interest in using
3613Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003614
Guido van Rossum02455691997-07-17 16:21:52 +00003615You should read, or at least page through, the Library Reference,
3616which gives complete (though terse) reference material about types,
3617functions, and modules that can save you a lot of time when writing
3618Python programs. The standard Python distribution includes a
Fred Drake3f205921998-01-13 18:56:38 +00003619\emph{lot} of code in both \C{} and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003620\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3621numbers, parse command-line options, write CGI programs, compress
3622data, and a lot more; skimming through the Library Reference will give
3623you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003624
Fred Drakeca6567f1998-01-22 20:44:18 +00003625The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003626code, documentation, and pointers to Python-related pages around the
Fred Drake391564f1998-04-01 23:11:56 +00003627Web. This web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00003628world, such as Europe, Japan, and Australia; a mirror may be faster
3629than the main site, depending on your geographical location. A more
Fred Drakeca6567f1998-01-22 20:44:18 +00003630informal site is \url{http://starship.skyport.net}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003631bunch of Python-related personal home pages; many people have
3632downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003633
Guido van Rossum02455691997-07-17 16:21:52 +00003634For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00003635newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
3636list at \email{python-list@cwi.nl}. The newsgroup and mailing list
3637are gatewayed, so messages posted to one will automatically be
3638forwarded to the other. There are around 35--45 postings a day,
3639% Postings figure based on average of last six months activity as
3640% reported by www.findmail.com; Oct. '97 - Mar. '98: 7480 msgs / 182
3641% days = 41.1 msgs / day.
3642asking (and answering) questions, suggesting new features, and
3643announcing new modules. Before posting, be sure to check the list of
3644Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003645\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3646\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003647answers many of the questions that come up again and again, and may
3648already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003649
Guido van Rossum02455691997-07-17 16:21:52 +00003650You can support the Python community by joining the Python Software
3651Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003652organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003653information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003654
Guido van Rossum194e57c1995-02-15 15:51:38 +00003655
Fred Drakea594baf1998-04-03 05:16:31 +00003656\appendix
Guido van Rossum194e57c1995-02-15 15:51:38 +00003657
Fred Drakea594baf1998-04-03 05:16:31 +00003658\chapter{Interactive Input Editing and History Substitution}
Fred Drake6c2176e1998-02-26 21:47:54 +00003659\label{interacting}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003660
Guido van Rossum02455691997-07-17 16:21:52 +00003661Some versions of the Python interpreter support editing of the current
3662input line and history substitution, similar to facilities found in
3663the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003664\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003665editing. This library has its own documentation which I won't
3666duplicate here; however, the basics are easily explained.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003667
Fred Drake8d486b11998-02-11 22:12:18 +00003668\section{Line Editing}
Fred Drake6c2176e1998-02-26 21:47:54 +00003669\label{lineEditing}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003670
Guido van Rossum02455691997-07-17 16:21:52 +00003671If supported, input line editing is active whenever the interpreter
3672prints a primary or secondary prompt. The current line can be edited
3673using the conventional Emacs control characters. The most important
3674of these are: C-A (Control-A) moves the cursor to the beginning of the
3675line, C-E to the end, C-B moves it one position to the left, C-F to
3676the right. Backspace erases the character to the left of the cursor,
3677C-D the character to its right. C-K kills (erases) the rest of the
3678line to the right of the cursor, C-Y yanks back the last killed
3679string. C-underscore undoes the last change you made; it can be
3680repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003681
Fred Drake8d486b11998-02-11 22:12:18 +00003682\section{History Substitution}
Fred Drake6c2176e1998-02-26 21:47:54 +00003683\label{history}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003684
Guido van Rossum02455691997-07-17 16:21:52 +00003685History substitution works as follows. All non-empty input lines
3686issued are saved in a history buffer, and when a new prompt is given
3687you are positioned on a new line at the bottom of this buffer. C-P
3688moves one line up (back) in the history buffer, C-N moves one down.
3689Any line in the history buffer can be edited; an asterisk appears in
3690front of the prompt to mark a line as modified. Pressing the Return
3691key passes the current line to the interpreter. C-R starts an
3692incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003693
Fred Drake8d486b11998-02-11 22:12:18 +00003694\section{Key Bindings}
Fred Drake6c2176e1998-02-26 21:47:54 +00003695\label{keyBindings}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003696
Guido van Rossum02455691997-07-17 16:21:52 +00003697The key bindings and some other parameters of the Readline library can
3698be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003699\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003700
Fred Drake8842e861998-02-13 07:16:30 +00003701\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003702key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003703\end{verbatim}
3704
Guido van Rossum02455691997-07-17 16:21:52 +00003705or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003706
Fred Drake8842e861998-02-13 07:16:30 +00003707\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003708"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003709\end{verbatim}
3710
Guido van Rossum02455691997-07-17 16:21:52 +00003711and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003712
Fred Drake8842e861998-02-13 07:16:30 +00003713\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003714set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003715\end{verbatim}
3716
Guido van Rossum02455691997-07-17 16:21:52 +00003717For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003718
Fred Drake8842e861998-02-13 07:16:30 +00003719\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003720# I prefer vi-style editing:
3721set editing-mode vi
3722# Edit using a single line:
3723set horizontal-scroll-mode On
3724# Rebind some keys:
3725Meta-h: backward-kill-word
3726"\C-u": universal-argument
3727"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003728\end{verbatim}
3729
Guido van Rossum02455691997-07-17 16:21:52 +00003730Note that the default binding for TAB in Python is to insert a TAB
3731instead of Readline's default filename completion function. If you
3732insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003733
Fred Drake8842e861998-02-13 07:16:30 +00003734\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003735TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003736\end{verbatim}
3737
Fred Drakeeee08cd1997-12-04 15:43:15 +00003738in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003739indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003740
Fred Drake72389881998-04-13 01:31:10 +00003741Automatic completion of variable and module names is optionally
3742available. To enable it in the interpreter's interactive mode, add
3743the following to your \file{\$HOME/.pythonrc} file:% $ <- bow to font-lock
3744\indexii{.pythonrc.py}{file}%
3745\refstmodindex{rlcompleter}%
3746\refbimodindex{readline}
3747
3748\begin{verbatim}
3749import rlcompleter, readline
3750readline.parse_and_bind('tab: complete')
3751\end{verbatim}
3752
3753This binds the TAB key to the completion function, so hitting the TAB
3754key twice suggests completions; it looks at Python statement names,
3755the current local variables, and the available module names. For
3756dotted expressions such as \code{string.a}, it will evaluate the the
3757expression up to the final \character{.} and then suggest completions
3758from the attributes of the resulting object. Note that this may
3759execute application-defined code if an object with a
3760\method{__getattr__()} method is part of the expression.
3761
3762
Fred Drake8d486b11998-02-11 22:12:18 +00003763\section{Commentary}
Fred Drake6c2176e1998-02-26 21:47:54 +00003764\label{commentary}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003765
Guido van Rossum02455691997-07-17 16:21:52 +00003766This facility is an enormous step forward compared to previous
3767versions of the interpreter; however, some wishes are left: It would
3768be nice if the proper indentation were suggested on continuation lines
3769(the parser knows if an indent token is required next). The
3770completion mechanism might use the interpreter's symbol table. A
3771command to check (or even suggest) matching parentheses, quotes etc.
3772would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003773
Fred Drake8842e861998-02-13 07:16:30 +00003774% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003775
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003776\end{document}
Guido van Rossum02455691997-07-17 16:21:52 +00003777