blob: 9b8d0bac34fac2a5b0e9d94dcd3a0776a5883947 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Fred Drake1b0b2a42001-03-13 17:56:08 +00002\usepackage[T1]{fontenc}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003
Guido van Rossum02455691997-07-17 16:21:52 +00004% Things to do:
5% Add a section on file I/O
6% Write a chapter entitled ``Some Useful Modules''
Fred Drake20082d92000-04-03 04:26:58 +00007% --re, math+cmath
Guido van Rossum02455691997-07-17 16:21:52 +00008% Should really move the Python startup file info to an appendix
Guido van Rossum02455691997-07-17 16:21:52 +00009
Guido van Rossumdccc2981997-12-30 04:40:25 +000010\title{Python Tutorial}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000011
Guido van Rossum16cd7f91994-10-06 10:29:26 +000012\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +000013
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000014\begin{document}
15
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000016\maketitle
17
Fred Drake9f86b661998-07-28 21:55:19 +000018\ifhtml
19\chapter*{Front Matter\label{front}}
20\fi
21
Guido van Rossum16cd7f91994-10-06 10:29:26 +000022\input{copyright}
23
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000024\begin{abstract}
25
26\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000027Python is an easy to learn, powerful programming language. It has
28efficient high-level data structures and a simple but effective
29approach to object-oriented programming. Python's elegant syntax and
30dynamic typing, together with its interpreted nature, make it an ideal
31language for scripting and rapid application development in many areas
32on most platforms.
33
34The Python interpreter and the extensive standard library are freely
35available in source or binary form for all major platforms from the
Fred Drake17f690f2001-07-14 02:14:42 +000036Python Web site, \url{http://www.python.org/}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000037distributed. The same site also contains distributions of and
38pointers to many free third party Python modules, programs and tools,
39and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000040
Guido van Rossum4410c751991-06-04 20:22:18 +000041The Python interpreter is easily extended with new functions and data
Fred Drakeee84d591999-03-10 17:25:30 +000042types implemented in C or \Cpp{} (or other languages callable from C).
Guido van Rossumdccc2981997-12-30 04:40:25 +000043Python is also suitable as an extension language for customizable
44applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000045
Guido van Rossum6fc178f1991-08-16 09:13:42 +000046This tutorial introduces the reader informally to the basic concepts
47and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000048Python interpreter handy for hands-on experience, but all examples are
49self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000050
Guido van Rossumdccc2981997-12-30 04:40:25 +000051For a description of standard objects and modules, see the
Fred Drake37f15741999-11-10 16:21:37 +000052\citetitle[../lib/lib.html]{Python Library Reference} document. The
53\citetitle[../ref/ref.html]{Python Reference Manual} gives a more
54formal definition of the language. To write extensions in C or
Fred Drakec37b65e2001-11-28 07:26:15 +000055\Cpp, read \citetitle[../ext/ext.html]{Extending and Embedding the
Fred Drake37f15741999-11-10 16:21:37 +000056Python Interpreter} and \citetitle[../api/api.html]{Python/C API
57Reference}. There are also several books covering Python in depth.
Guido van Rossumdccc2981997-12-30 04:40:25 +000058
59This tutorial does not attempt to be comprehensive and cover every
60single feature, or even every commonly used feature. Instead, it
61introduces many of Python's most noteworthy features, and will give
62you a good idea of the language's flavor and style. After reading it,
63you will be able to read and write Python modules and programs, and
64you will be ready to learn more about the various Python library
Fred Drake37f15741999-11-10 16:21:37 +000065modules described in the \citetitle[../lib/lib.html]{Python Library
66Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000067
68\end{abstract}
69
Fred Drake4d4f9e71998-01-13 22:25:02 +000070\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000071
Guido van Rossum5e0759d1992-08-07 16:06:24 +000072
Fred Drakeb7833d31998-09-11 16:21:55 +000073\chapter{Whetting Your Appetite \label{intro}}
Guido van Rossum3a26dd81996-10-24 22:12:48 +000074
Guido van Rossum6fc178f1991-08-16 09:13:42 +000075If you ever wrote a large shell script, you probably know this
76feeling: you'd love to add yet another feature, but it's already so
77slow, and so big, and so complicated; or the feature involves a system
Fred Drakeee84d591999-03-10 17:25:30 +000078call or other function that is only accessible from C \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000079the problem at hand isn't serious enough to warrant rewriting the
Fred Drakeee84d591999-03-10 17:25:30 +000080script in C; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000081other data types (like sorted lists of file names) that are easy in
Fred Drakeee84d591999-03-10 17:25:30 +000082the shell but lots of work to implement in C, or perhaps you're not
83sufficiently familiar with C.
Guido van Rossum02455691997-07-17 16:21:52 +000084
Fred Drakeee84d591999-03-10 17:25:30 +000085Another situation: perhaps you have to work with several C libraries,
86and the usual C write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000087need to develop software more quickly. Possibly perhaps you've
88written a program that could use an extension language, and you don't
89want to design a language, write and debug an interpreter for it, then
90tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000091
Guido van Rossum6fc178f1991-08-16 09:13:42 +000092In such cases, Python may be just the language for you. Python is
93simple to use, but it is a real programming language, offering much
94more structure and support for large programs than the shell has. On
Fred Drakeee84d591999-03-10 17:25:30 +000095the other hand, it also offers much more error checking than C, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000096being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000097built in, such as flexible arrays and dictionaries that would cost you
Fred Drakeee84d591999-03-10 17:25:30 +000098days to implement efficiently in C. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000099types Python is applicable to a much larger problem domain than
100\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
101in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000102
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000103Python allows you to split up your program in modules that can be
104reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000105standard modules that you can use as the basis of your programs --- or
106as examples to start learning to program in Python. There are also
107built-in modules that provide things like file I/O, system calls,
Fred Drake17f690f2001-07-14 02:14:42 +0000108sockets, and even interfaces to graphical user interface toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000109
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000110Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000111during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000112necessary. The interpreter can be used interactively, which makes it
113easy to experiment with features of the language, to write throw-away
114programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000115It is also a handy desk calculator.
116
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000117Python allows writing very compact and readable programs. Programs
Fred Drake20082d92000-04-03 04:26:58 +0000118written in Python are typically much shorter than equivalent C or
119\Cpp{} programs, for several reasons:
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000120\begin{itemize}
121\item
122the high-level data types allow you to express complex operations in a
123single statement;
124\item
125statement grouping is done by indentation instead of begin/end
126brackets;
127\item
128no variable or argument declarations are necessary.
129\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000130
Fred Drakeee84d591999-03-10 17:25:30 +0000131Python is \emph{extensible}: if you know how to program in C it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000132to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000133perform critical operations at maximum speed, or to link Python
134programs to libraries that may only be available in binary form (such
135as a vendor-specific graphics library). Once you are really hooked,
Fred Drakeee84d591999-03-10 17:25:30 +0000136you can link the Python interpreter into an application written in C
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000137and use it as an extension or command language for that application.
138
Guido van Rossum02455691997-07-17 16:21:52 +0000139By the way, the language is named after the BBC show ``Monty Python's
140Flying Circus'' and has nothing to do with nasty reptiles. Making
141references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000142it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000143
Fred Drake2664cbb2003-06-20 14:27:27 +0000144%\section{Where From Here \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
Fred Drakef64f8a01999-06-10 15:30:21 +0000155language and system through examples, beginning with simple
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000156expressions, 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
Fred Drakeb7833d31998-09-11 16:21:55 +0000160\chapter{Using the Python Interpreter \label{using}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000161
Fred Drakeb7833d31998-09-11 16:21:55 +0000162\section{Invoking the Interpreter \label{invoking}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000163
Fred Drake20082d92000-04-03 04:26:58 +0000164The Python interpreter is usually installed as
165\file{/usr/local/bin/python} on those machines where it is available;
166putting \file{/usr/local/bin} in your \UNIX{} shell's search path
167makes it possible to start it by typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000168
Fred Drake8842e861998-02-13 07:16:30 +0000169\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000170python
Fred Drake8842e861998-02-13 07:16:30 +0000171\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000172
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000173to the shell. Since the choice of the directory where the interpreter
174lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000175your local Python guru or system administrator. (E.g.,
176\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000177
Fred Drake5d6e4022001-04-11 04:38:34 +0000178Typing an end-of-file character (\kbd{Control-D} on \UNIX,
Martin v. Löwis36a4d8c2002-10-10 18:24:54 +0000179\kbd{Control-Z} on Windows) at the primary prompt causes the
Fred Drake5443c492000-07-08 05:18:54 +0000180interpreter to exit with a zero exit status. If that doesn't work,
181you can exit the interpreter by typing the following commands:
182\samp{import sys; sys.exit()}.
Guido van Rossum02455691997-07-17 16:21:52 +0000183
184The interpreter's line-editing features usually aren't very
Fred Drakec37b65e2001-11-28 07:26:15 +0000185sophisticated. On \UNIX, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000186enabled support for the GNU readline library, which adds more
187elaborate interactive editing and history features. Perhaps the
188quickest check to see whether command line editing is supported is
189typing Control-P to the first Python prompt you get. If it beeps, you
Fred Drake5443c492000-07-08 05:18:54 +0000190have command line editing; see Appendix \ref{interacting} for an
191introduction to the keys. If nothing appears to happen, or if
192\code{\^P} is echoed, command line editing isn't available; you'll
193only be able to use backspace to remove characters from the current
194line.
Guido van Rossum02455691997-07-17 16:21:52 +0000195
Fred Drake6dc2aae1996-12-13 21:56:03 +0000196The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000197with standard input connected to a tty device, it reads and executes
198commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000199a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000200that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000201
Raymond Hettingerc2a5cb22003-08-23 03:49:08 +0000202A second way of starting the interpreter is
Fred Drake37f15741999-11-10 16:21:37 +0000203\samp{\program{python} \programopt{-c} \var{command} [arg] ...}, which
204executes the statement(s) in \var{command}, analogous to the shell's
205\programopt{-c} option. Since Python statements often contain spaces
206or other characters that are special to the shell, it is best to quote
207\var{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000208
Fred Drakeeee08cd1997-12-04 15:43:15 +0000209Note that there is a difference between \samp{python file} and
210\samp{python <file}. In the latter case, input requests from the
Fred Drake6bab1832003-05-20 15:28:58 +0000211program, such as calls to \function{input()} and \function{raw_input()}, are
Fred Drakeeee08cd1997-12-04 15:43:15 +0000212satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000213until the end by the parser before the program starts executing, the
Fred Drake5d6e4022001-04-11 04:38:34 +0000214program will encounter end-of-file immediately. In the former case
215(which is usually what you want) they are satisfied from whatever file
216or device is connected to standard input of the Python interpreter.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000217
Guido van Rossumb2c65561993-05-12 08:53:36 +0000218When a script file is used, it is sometimes useful to be able to run
219the script and enter interactive mode afterwards. This can be done by
Fred Drake37f15741999-11-10 16:21:37 +0000220passing \programopt{-i} before the script. (This does not work if the
221script is read from standard input, for the same reason as explained
222in the previous paragraph.)
Guido van Rossumb2c65561993-05-12 08:53:36 +0000223
Fred Drakeb7833d31998-09-11 16:21:55 +0000224\subsection{Argument Passing \label{argPassing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000225
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000226When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000227arguments thereafter are passed to the script in the variable
228\code{sys.argv}, which is a list of strings. Its length is at least
229one; when no script and no arguments are given, \code{sys.argv[0]} is
230an empty string. When the script name is given as \code{'-'} (meaning
Fred Drake37f15741999-11-10 16:21:37 +0000231standard input), \code{sys.argv[0]} is set to \code{'-'}. When
232\programopt{-c} \var{command} is used, \code{sys.argv[0]} is set to
233\code{'-c'}. Options found after \programopt{-c} \var{command} are
234not consumed by the Python interpreter's option processing but left in
235\code{sys.argv} for the command to handle.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000236
Fred Drakeb7833d31998-09-11 16:21:55 +0000237\subsection{Interactive Mode \label{interactive}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000238
Guido van Rossumdd010801991-06-07 14:31:11 +0000239When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000240\emph{interactive mode}. In this mode it prompts for the next command
241with the \emph{primary prompt}, usually three greater-than signs
Fred Drake31b761e2000-09-29 15:17:36 +0000242(\samp{>\code{>}>~}); for continuation lines it prompts with the
Fred Drake20082d92000-04-03 04:26:58 +0000243\emph{secondary prompt}, by default three dots (\samp{...~}).
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000244The interpreter prints a welcome message stating its version number
Fred Drakeed514942001-07-06 17:28:39 +0000245and a copyright notice before printing the first prompt:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000246
Fred Drake8842e861998-02-13 07:16:30 +0000247\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000248python
Fred Drakeee84d591999-03-10 17:25:30 +0000249Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Fred Drakeeee08cd1997-12-04 15:43:15 +0000250Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000251>>>
Fred Drake8842e861998-02-13 07:16:30 +0000252\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000253
Fred Drake20082d92000-04-03 04:26:58 +0000254Continuation lines are needed when entering a multi-line construct.
255As an example, take a look at this \keyword{if} statement:
256
257\begin{verbatim}
258>>> the_world_is_flat = 1
259>>> if the_world_is_flat:
260... print "Be careful not to fall off!"
261...
262Be careful not to fall off!
263\end{verbatim}
264
265
Fred Drakeb7833d31998-09-11 16:21:55 +0000266\section{The Interpreter and Its Environment \label{interp}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000267
Fred Drakeb7833d31998-09-11 16:21:55 +0000268\subsection{Error Handling \label{error}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000269
270When an error occurs, the interpreter prints an error
271message and a stack trace. In interactive mode, it then returns to
272the primary prompt; when input came from a file, it exits with a
273nonzero exit status after printing
Fred Drake6bab1832003-05-20 15:28:58 +0000274the stack trace. (Exceptions handled by an \keyword{except} clause in a
275\keyword{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000276unconditionally fatal and cause an exit with a nonzero exit; this
277applies to internal inconsistencies and some cases of running out of
278memory. All error messages are written to the standard error stream;
279normal output from the executed commands is written to standard
280output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000281
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000282Typing the interrupt character (usually Control-C or DEL) to the
283primary or secondary prompt cancels the input and returns to the
Fred Drake93aa0f21999-04-05 21:39:17 +0000284primary prompt.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000285 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000286}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000287Typing an interrupt while a command is executing raises the
Fred Drake6bab1832003-05-20 15:28:58 +0000288\exception{KeyboardInterrupt} exception, which may be handled by a
289\keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000290
Fred Drakeb7833d31998-09-11 16:21:55 +0000291\subsection{Executable Python Scripts \label{scripts}}
Guido van Rossum4410c751991-06-04 20:22:18 +0000292
Fred Drake6dc2aae1996-12-13 21:56:03 +0000293On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000294executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000295
Fred Drake8842e861998-02-13 07:16:30 +0000296\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000297#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000298\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000299
Fred Drake391564f1998-04-01 23:11:56 +0000300(assuming that the interpreter is on the user's \envvar{PATH}) at the
301beginning of the script and giving the file an executable mode. The
Fred Drakedfda8d72003-07-07 21:00:29 +0000302\samp{\#!} must be the first two characters of the file. On some
303platforms, this first line must end with a \UNIX-style line ending
304(\character{\e n}), not a Mac OS (\character{\e r}) or Windows
305(\character{\e r\e n}) line ending. Note that
Fred Drakebdadf0f1999-04-29 13:20:25 +0000306the hash, or pound, character, \character{\#}, is used to start a
307comment in Python.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000308
Fred Drakedfda8d72003-07-07 21:00:29 +0000309The script can be given a executable mode, or permission, using the
310\program{chmod} command:
311
312\begin{verbatim}
313$ chmod +x myscript.py
314\end{verbatim} % $ <-- bow to font-lock
315
316
Martin v. Löwis7928f382003-06-28 08:11:55 +0000317\subsection{Source Code Encoding}
318
Fred Drakedfda8d72003-07-07 21:00:29 +0000319It is possible to use encodings different than \ASCII{} in Python source
Martin v. Löwis7928f382003-06-28 08:11:55 +0000320files. The best way to do it is to put one more special comment line
Skip Montanaro32a5e872003-06-29 16:01:51 +0000321right after the \code{\#!} line to define the source file encoding:
Martin v. Löwis7928f382003-06-28 08:11:55 +0000322
323\begin{verbatim}
324# -*- coding: iso-8859-1 -*-
325\end{verbatim}
326
Skip Montanaro32a5e872003-06-29 16:01:51 +0000327With that declaration, all characters in the source file will be treated as
328{}\code{iso-8859-1}, and it will be
Martin v. Löwis7928f382003-06-28 08:11:55 +0000329possible to directly write Unicode string literals in the selected
Skip Montanaro32a5e872003-06-29 16:01:51 +0000330encoding. The list of possible encodings can be found in the
Martin v. Löwis7928f382003-06-28 08:11:55 +0000331\citetitle[../lib/lib.html]{Python Library Reference}, in the section
332on \module{codecs}.
333
334If your editor supports saving files as \code{UTF-8} with an UTF-8
335signature (aka BOM -- Byte Order Mark), you can use that instead of an
Skip Montanaro32a5e872003-06-29 16:01:51 +0000336encoding declaration. IDLE supports this capability if
Martin v. Löwis7928f382003-06-28 08:11:55 +0000337\code{Options/General/Default Source Encoding/UTF-8} is set. Notice
338that this signature is not understood in older Python releases (2.2
339and earlier), and also not understood by the operating system for
Fred Drakeded8e742003-06-28 11:50:34 +0000340\code{\#!} files.
Martin v. Löwis7928f382003-06-28 08:11:55 +0000341
Skip Montanaro32a5e872003-06-29 16:01:51 +0000342By using UTF-8 (either through the signature or an encoding
Martin v. Löwis7928f382003-06-28 08:11:55 +0000343declaration), characters of most languages in the world can be used
344simultaneously in string literals and comments. Using non-ASCII
345characters in identifiers is not supported. To display all these
346characters properly, your editor must recognize that the file is
347UTF-8, and it must use a font that supports all the characters in the
348file.
349
Fred Drakeb7833d31998-09-11 16:21:55 +0000350\subsection{The Interactive Startup File \label{startup}}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000351
Fred Drake8842e861998-02-13 07:16:30 +0000352% XXX This should probably be dumped in an appendix, since most people
353% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000354
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000355When you use Python interactively, it is frequently handy to have some
356standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000357can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000358\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drake20082d92000-04-03 04:26:58 +0000359commands. This is similar to the \file{.profile} feature of the
360\UNIX{} shells.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000361
362This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000363commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000364explicit source of commands (which otherwise behaves like an
Fred Drake13494372000-09-12 16:23:48 +0000365interactive session). It is executed in the same namespace where
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000366interactive commands are executed, so that objects that it defines or
367imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000368You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000369this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000370
371If you want to read an additional start-up file from the current
Fred Drakeed514942001-07-06 17:28:39 +0000372directory, you can program this in the global start-up file using code
373like \samp{if os.path.isfile('.pythonrc.py'):
Fred Drake5443c492000-07-08 05:18:54 +0000374execfile('.pythonrc.py')}. If you want to use the startup file in a
375script, you must do this explicitly in the script:
Fred Drake8842e861998-02-13 07:16:30 +0000376
377\begin{verbatim}
378import os
Fred Drake5443c492000-07-08 05:18:54 +0000379filename = os.environ.get('PYTHONSTARTUP')
380if filename and os.path.isfile(filename):
381 execfile(filename)
Fred Drake8842e861998-02-13 07:16:30 +0000382\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000383
Fred Drake72389881998-04-13 01:31:10 +0000384
Fred Drakeb7833d31998-09-11 16:21:55 +0000385\chapter{An Informal Introduction to Python \label{informal}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000386
387In the following examples, input and output are distinguished by the
Fred Drake31b761e2000-09-29 15:17:36 +0000388presence or absence of prompts (\samp{>\code{>}>~} and \samp{...~}): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000389the example, you must type everything after the prompt, when the
390prompt appears; lines that do not begin with a prompt are output from
Fred Drakebdadf0f1999-04-29 13:20:25 +0000391the interpreter. %
Guido van Rossum02455691997-07-17 16:21:52 +0000392%\footnote{
393% I'd prefer to use different fonts to distinguish input
394% from output, but the amount of LaTeX hacking that would require
395% is currently beyond my ability.
396%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000397Note that a secondary prompt on a line by itself in an example means
398you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000399
Fred Drakebdadf0f1999-04-29 13:20:25 +0000400Many of the examples in this manual, even those entered at the
401interactive prompt, include comments. Comments in Python start with
402the hash character, \character{\#}, and extend to the end of the
403physical line. A comment may appear at the start of a line or
404following whitespace or code, but not within a string literal. A hash
405character within a string literal is just a hash character.
406
407Some examples:
408
409\begin{verbatim}
410# this is the first comment
411SPAM = 1 # and this is the second comment
412 # ... and now a third!
413STRING = "# This is not a comment."
414\end{verbatim}
415
416
Fred Drakeb7833d31998-09-11 16:21:55 +0000417\section{Using Python as a Calculator \label{calculator}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000418
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000419Let's try some simple Python commands. Start the interpreter and wait
Fred Drake31b761e2000-09-29 15:17:36 +0000420for the primary prompt, \samp{>\code{>}>~}. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000421
Fred Drakeb7833d31998-09-11 16:21:55 +0000422\subsection{Numbers \label{numbers}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000423
424The interpreter acts as a simple calculator: you can type an
425expression at it and it will write the value. Expression syntax is
Fred Drake20082d92000-04-03 04:26:58 +0000426straightforward: the operators \code{+}, \code{-}, \code{*} and
427\code{/} work just like in most other languages (for example, Pascal
428or C); parentheses can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000429
Fred Drake8842e861998-02-13 07:16:30 +0000430\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000431>>> 2+2
4324
Guido van Rossum6938f061994-08-01 12:22:53 +0000433>>> # This is a comment
434... 2+2
4354
436>>> 2+2 # and a comment on the same line as code
4374
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000438>>> (50-5*6)/4
4395
Guido van Rossum6938f061994-08-01 12:22:53 +0000440>>> # Integer division returns the floor:
441... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004422
Guido van Rossum6938f061994-08-01 12:22:53 +0000443>>> 7/-3
444-3
Fred Drake8842e861998-02-13 07:16:30 +0000445\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000446
Fred Drakeee84d591999-03-10 17:25:30 +0000447Like in C, the equal sign (\character{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000448variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000449
Fred Drake8842e861998-02-13 07:16:30 +0000450\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000451>>> width = 20
452>>> height = 5*9
453>>> width * height
454900
Fred Drake8842e861998-02-13 07:16:30 +0000455\end{verbatim}
Fred Drake20082d92000-04-03 04:26:58 +0000456
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000457A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000458
Fred Drake8842e861998-02-13 07:16:30 +0000459\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000460>>> x = y = z = 0 # Zero x, y and z
461>>> x
4620
463>>> y
4640
465>>> z
4660
Fred Drake8842e861998-02-13 07:16:30 +0000467\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +0000468
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000469There is full support for floating point; operators with mixed type
470operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000471
Fred Drake8842e861998-02-13 07:16:30 +0000472\begin{verbatim}
Tim Petersbd695a72001-05-22 06:54:14 +0000473>>> 3 * 3.75 / 1.5
4747.5
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000475>>> 7.0 / 2
4763.5
Fred Drake8842e861998-02-13 07:16:30 +0000477\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +0000478
Guido van Rossum02455691997-07-17 16:21:52 +0000479Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000480a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
481real component are written as \samp{(\var{real}+\var{imag}j)}, or can
482be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000483
Fred Drake8842e861998-02-13 07:16:30 +0000484\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000485>>> 1j * 1J
486(-1+0j)
487>>> 1j * complex(0,1)
488(-1+0j)
489>>> 3+1j*3
490(3+3j)
491>>> (3+1j)*3
492(9+3j)
493>>> (1+2j)/(1+1j)
494(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000495\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +0000496
Guido van Rossum02455691997-07-17 16:21:52 +0000497Complex numbers are always represented as two floating point numbers,
498the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000499number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000500
Fred Drake8842e861998-02-13 07:16:30 +0000501\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000502>>> a=1.5+0.5j
503>>> a.real
5041.5
505>>> a.imag
5060.5
Fred Drake8842e861998-02-13 07:16:30 +0000507\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +0000508
Guido van Rossum02455691997-07-17 16:21:52 +0000509The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000510(\function{float()}, \function{int()} and \function{long()}) don't
511work for complex numbers --- there is no one correct way to convert a
512complex number to a real number. Use \code{abs(\var{z})} to get its
513magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000514
Fred Drake8842e861998-02-13 07:16:30 +0000515\begin{verbatim}
Tim Petersbd695a72001-05-22 06:54:14 +0000516>>> a=3.0+4.0j
Guido van Rossum02455691997-07-17 16:21:52 +0000517>>> float(a)
Fred Drake162c6a62001-02-14 03:20:18 +0000518Traceback (most recent call last):
Guido van Rossum02455691997-07-17 16:21:52 +0000519 File "<stdin>", line 1, in ?
520TypeError: can't convert complex to float; use e.g. abs(z)
521>>> a.real
Tim Petersbd695a72001-05-22 06:54:14 +00005223.0
523>>> a.imag
5244.0
525>>> abs(a) # sqrt(a.real**2 + a.imag**2)
5265.0
527>>>
Fred Drake8842e861998-02-13 07:16:30 +0000528\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +0000529
Guido van Rossum02455691997-07-17 16:21:52 +0000530In interactive mode, the last printed expression is assigned to the
531variable \code{_}. This means that when you are using Python as a
532desk calculator, it is somewhat easier to continue calculations, for
533example:
534
535\begin{verbatim}
Tim Petersbd695a72001-05-22 06:54:14 +0000536>>> tax = 12.5 / 100
537>>> price = 100.50
Guido van Rossum02455691997-07-17 16:21:52 +0000538>>> price * tax
Tim Petersbd695a72001-05-22 06:54:14 +000053912.5625
Guido van Rossum02455691997-07-17 16:21:52 +0000540>>> price + _
Tim Petersbd695a72001-05-22 06:54:14 +0000541113.0625
Guido van Rossum02455691997-07-17 16:21:52 +0000542>>> round(_, 2)
Tim Petersbd695a72001-05-22 06:54:14 +0000543113.06
544>>>
Guido van Rossum02455691997-07-17 16:21:52 +0000545\end{verbatim}
546
547This variable should be treated as read-only by the user. Don't
548explicitly assign a value to it --- you would create an independent
549local variable with the same name masking the built-in variable with
550its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000551
Fred Drakeb7833d31998-09-11 16:21:55 +0000552\subsection{Strings \label{strings}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000553
Guido van Rossum02455691997-07-17 16:21:52 +0000554Besides numbers, Python can also manipulate strings, which can be
555expressed in several ways. They can be enclosed in single quotes or
556double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000557
Fred Drake8842e861998-02-13 07:16:30 +0000558\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000559>>> 'spam eggs'
560'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000561>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000562"doesn't"
563>>> "doesn't"
564"doesn't"
565>>> '"Yes," he said.'
566'"Yes," he said.'
567>>> "\"Yes,\" he said."
568'"Yes," he said.'
569>>> '"Isn\'t," she said.'
570'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000571\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000572
Fred Drakeba5c41d2001-09-06 18:41:15 +0000573String literals can span multiple lines in several ways. Continuation
574lines can be used, with a backslash as the last character on the line
575indicating that the next line is a logical continuation of the line:
Guido van Rossum02455691997-07-17 16:21:52 +0000576
577\begin{verbatim}
578hello = "This is a rather long string containing\n\
579several lines of text just as you would do in C.\n\
580 Note that whitespace at the beginning of the line is\
Fred Drakeba5c41d2001-09-06 18:41:15 +0000581 significant."
582
Guido van Rossum02455691997-07-17 16:21:52 +0000583print hello
584\end{verbatim}
585
Fred Drakeba5c41d2001-09-06 18:41:15 +0000586Note that newlines would still need to be embedded in the string using
587\code{\e n}; the newline following the trailing backslash is
588discarded. This example would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000589
Guido van Rossum02455691997-07-17 16:21:52 +0000590\begin{verbatim}
591This is a rather long string containing
592several lines of text just as you would do in C.
593 Note that whitespace at the beginning of the line is significant.
594\end{verbatim}
595
Fred Drakeba5c41d2001-09-06 18:41:15 +0000596If we make the string literal a ``raw'' string, however, the
597\code{\e n} sequences are not converted to newlines, but the backslash
598at the end of the line, and the newline character in the source, are
599both included in the string as data. Thus, the example:
600
601\begin{verbatim}
602hello = r"This is a rather long string containing\n\
603several lines of text much as you would do in C."
604
605print hello
606\end{verbatim}
607
608would print:
609
610\begin{verbatim}
611This is a rather long string containing\n\
612several lines of text much as you would do in C.
613\end{verbatim}
614
Guido van Rossum02455691997-07-17 16:21:52 +0000615Or, strings can be surrounded in a pair of matching triple-quotes:
Fred Drakeba5c41d2001-09-06 18:41:15 +0000616\code{"""} or \code{'\code{'}'}. End of lines do not need to be escaped
Guido van Rossum02455691997-07-17 16:21:52 +0000617when using triple-quotes, but they will be included in the string.
618
619\begin{verbatim}
620print """
621Usage: thingy [OPTIONS]
622 -h Display this usage message
623 -H hostname Hostname to connect to
624"""
625\end{verbatim}
626
627produces the following output:
628
Fred Drake8842e861998-02-13 07:16:30 +0000629\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000630Usage: thingy [OPTIONS]
631 -h Display this usage message
632 -H hostname Hostname to connect to
Fred Drake8842e861998-02-13 07:16:30 +0000633\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000634
Guido van Rossum02455691997-07-17 16:21:52 +0000635The interpreter prints the result of string operations in the same way
636as they are typed for input: inside quotes, and with quotes and other
637funny characters escaped by backslashes, to show the precise
638value. The string is enclosed in double quotes if the string contains
639a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000640quotes. (The \keyword{print} statement, described later, can be used
641to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000642
Fred Drake20082d92000-04-03 04:26:58 +0000643Strings can be concatenated (glued together) with the
644\code{+} operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000645
Fred Drake8842e861998-02-13 07:16:30 +0000646\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000647>>> word = 'Help' + 'A'
648>>> word
649'HelpA'
650>>> '<' + word*5 + '>'
651'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000652\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000653
Guido van Rossum02455691997-07-17 16:21:52 +0000654Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000655the first line above could also have been written \samp{word = 'Help'
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000656'A'}; this only works with two literals, not with arbitrary string
657expressions:
658
659\begin{verbatim}
Fred Drake0ba58151999-09-14 18:00:49 +0000660>>> import string
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000661>>> 'str' 'ing' # <- This is ok
662'string'
663>>> string.strip('str') + 'ing' # <- This is ok
664'string'
665>>> string.strip('str') 'ing' # <- This is invalid
Fred Drake13af4282001-09-21 21:10:05 +0000666 File "<stdin>", line 1, in ?
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000667 string.strip('str') 'ing'
668 ^
669SyntaxError: invalid syntax
670\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000671
Fred Drakeee84d591999-03-10 17:25:30 +0000672Strings can be subscripted (indexed); like in C, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000673of a string has subscript (index) 0. There is no separate character
674type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000675substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000676separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000677
Fred Drake8842e861998-02-13 07:16:30 +0000678\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000679>>> word[4]
680'A'
681>>> word[0:2]
682'He'
683>>> word[2:4]
684'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000685\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000686
Raymond Hettinger60de2e82003-03-12 04:46:52 +0000687Slice indices have useful defaults; an omitted first index defaults to
688zero, an omitted second index defaults to the size of the string being
689sliced.
690
691\begin{verbatim}
692>>> word[:2] # The first two characters
693'He'
694>>> word[2:] # All but the first two characters
695'lpA'
696\end{verbatim}
697
Fred Drake20082d92000-04-03 04:26:58 +0000698Unlike a C string, Python strings cannot be changed. Assigning to an
699indexed position in the string results in an error:
700
701\begin{verbatim}
702>>> word[0] = 'x'
Fred Drake162c6a62001-02-14 03:20:18 +0000703Traceback (most recent call last):
Fred Drake20082d92000-04-03 04:26:58 +0000704 File "<stdin>", line 1, in ?
705TypeError: object doesn't support item assignment
Fred Drake67fdaa42001-03-06 07:19:34 +0000706>>> word[:1] = 'Splat'
Fred Drake162c6a62001-02-14 03:20:18 +0000707Traceback (most recent call last):
Fred Drake20082d92000-04-03 04:26:58 +0000708 File "<stdin>", line 1, in ?
709TypeError: object doesn't support slice assignment
710\end{verbatim}
711
712However, creating a new string with the combined content is easy and
713efficient:
714
715\begin{verbatim}
716>>> 'x' + word[1:]
717'xelpA'
Fred Drake67fdaa42001-03-06 07:19:34 +0000718>>> 'Splat' + word[4]
Fred Drake20082d92000-04-03 04:26:58 +0000719'SplatA'
720\end{verbatim}
721
Fred Drake20082d92000-04-03 04:26:58 +0000722Here's a useful invariant of slice operations:
723\code{s[:i] + s[i:]} equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000724
Fred Drake8842e861998-02-13 07:16:30 +0000725\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000726>>> word[:2] + word[2:]
727'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000728>>> word[:3] + word[3:]
729'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000730\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000731
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000732Degenerate slice indices are handled gracefully: an index that is too
733large is replaced by the string size, an upper bound smaller than the
734lower bound returns an empty string.
735
Fred Drake8842e861998-02-13 07:16:30 +0000736\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000737>>> word[1:100]
738'elpA'
739>>> word[10:]
740''
741>>> word[2:1]
742''
Fred Drake8842e861998-02-13 07:16:30 +0000743\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000744
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000745Indices may be negative numbers, to start counting from the right.
746For example:
747
Fred Drake8842e861998-02-13 07:16:30 +0000748\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000749>>> word[-1] # The last character
750'A'
751>>> word[-2] # The last-but-one character
752'p'
753>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000754'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000755>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000756'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000757\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000758
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000759But note that -0 is really the same as 0, so it does not count from
760the right!
761
Fred Drake8842e861998-02-13 07:16:30 +0000762\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000763>>> word[-0] # (since -0 equals 0)
764'H'
Fred Drake8842e861998-02-13 07:16:30 +0000765\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000766
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000767Out-of-range negative slice indices are truncated, but don't try this
768for single-element (non-slice) indices:
769
Fred Drake8842e861998-02-13 07:16:30 +0000770\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000771>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000772'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000773>>> word[-10] # error
Fred Drake162c6a62001-02-14 03:20:18 +0000774Traceback (most recent call last):
Fred Drake13af4282001-09-21 21:10:05 +0000775 File "<stdin>", line 1, in ?
Guido van Rossum6938f061994-08-01 12:22:53 +0000776IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000777\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000778
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000779The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000780pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000781character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000782string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000783
Fred Drake8842e861998-02-13 07:16:30 +0000784\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000785 +---+---+---+---+---+
786 | H | e | l | p | A |
787 +---+---+---+---+---+
788 0 1 2 3 4 5
789-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000790\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000791
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000792The first row of numbers gives the position of the indices 0...5 in
793the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000794The slice from \var{i} to \var{j} consists of all characters between
795the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000796
Fred Drake20082d92000-04-03 04:26:58 +0000797For non-negative indices, the length of a slice is the difference of
Fred Drakeed514942001-07-06 17:28:39 +0000798the indices, if both are within bounds. For example, the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000799\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000800
Fred Drake8842e861998-02-13 07:16:30 +0000801The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000802
Fred Drake8842e861998-02-13 07:16:30 +0000803\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000804>>> s = 'supercalifragilisticexpialidocious'
805>>> len(s)
80634
Fred Drake8842e861998-02-13 07:16:30 +0000807\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000808
Fred Drake9dc30bb2000-04-06 14:17:03 +0000809
810\subsection{Unicode Strings \label{unicodeStrings}}
811\sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com}
812
Fred Drake30f76ff2000-06-30 16:06:19 +0000813Starting with Python 2.0 a new data type for storing text data is
Fred Drake9dc30bb2000-04-06 14:17:03 +0000814available to the programmer: the Unicode object. It can be used to
Fred Drake17f690f2001-07-14 02:14:42 +0000815store and manipulate Unicode data (see \url{http://www.unicode.org/})
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000816and integrates well with the existing string objects providing
Fred Drake9dc30bb2000-04-06 14:17:03 +0000817auto-conversions where necessary.
818
819Unicode has the advantage of providing one ordinal for every character
820in every script used in modern and ancient texts. Previously, there
821were only 256 possible ordinals for script characters and texts were
822typically bound to a code page which mapped the ordinals to script
823characters. This lead to very much confusion especially with respect
Fred Drake31b761e2000-09-29 15:17:36 +0000824to internationalization (usually written as \samp{i18n} ---
825\character{i} + 18 characters + \character{n}) of software. Unicode
826solves these problems by defining one code page for all scripts.
Fred Drake9dc30bb2000-04-06 14:17:03 +0000827
828Creating Unicode strings in Python is just as simple as creating
829normal strings:
830
831\begin{verbatim}
832>>> u'Hello World !'
833u'Hello World !'
834\end{verbatim}
835
836The small \character{u} in front of the quote indicates that an
837Unicode string is supposed to be created. If you want to include
838special characters in the string, you can do so by using the Python
839\emph{Unicode-Escape} encoding. The following example shows how:
840
841\begin{verbatim}
Tim Peters657ebef2000-11-29 05:51:59 +0000842>>> u'Hello\u0020World !'
Fred Drake9dc30bb2000-04-06 14:17:03 +0000843u'Hello World !'
844\end{verbatim}
845
Fred Drake4a6f1df2000-11-29 06:03:45 +0000846The escape sequence \code{\e u0020} indicates to insert the Unicode
Ka-Ping Yee54019962001-02-13 22:20:22 +0000847character with the ordinal value 0x0020 (the space character) at the
Fred Drake9dc30bb2000-04-06 14:17:03 +0000848given position.
849
850Other characters are interpreted by using their respective ordinal
Ka-Ping Yee54019962001-02-13 22:20:22 +0000851values directly as Unicode ordinals. If you have literal strings
852in the standard Latin-1 encoding that is used in many Western countries,
853you will find it convenient that the lower 256 characters
854of Unicode are the same as the 256 characters of Latin-1.
Fred Drake9dc30bb2000-04-06 14:17:03 +0000855
Ka-Ping Yee54019962001-02-13 22:20:22 +0000856For experts, there is also a raw mode just like the one for normal
857strings. You have to prefix the opening quote with 'ur' to have
Fred Drake9dc30bb2000-04-06 14:17:03 +0000858Python use the \emph{Raw-Unicode-Escape} encoding. It will only apply
Fred Drake4a6f1df2000-11-29 06:03:45 +0000859the above \code{\e uXXXX} conversion if there is an uneven number of
Fred Drake9dc30bb2000-04-06 14:17:03 +0000860backslashes in front of the small 'u'.
861
862\begin{verbatim}
863>>> ur'Hello\u0020World !'
864u'Hello World !'
865>>> ur'Hello\\u0020World !'
866u'Hello\\\\u0020World !'
867\end{verbatim}
868
Fred Drakeed514942001-07-06 17:28:39 +0000869The raw mode is most useful when you have to enter lots of
870backslashes, as can be necessary in regular expressions.
Fred Drake9dc30bb2000-04-06 14:17:03 +0000871
872Apart from these standard encodings, Python provides a whole set of
Thomas Woutersf9b526d2000-07-16 19:05:38 +0000873other ways of creating Unicode strings on the basis of a known
Fred Drake9dc30bb2000-04-06 14:17:03 +0000874encoding.
875
Ka-Ping Yee54019962001-02-13 22:20:22 +0000876The built-in function \function{unicode()}\bifuncindex{unicode} provides
877access to all registered Unicode codecs (COders and DECoders). Some of
878the more well known encodings which these codecs can convert are
879\emph{Latin-1}, \emph{ASCII}, \emph{UTF-8}, and \emph{UTF-16}.
880The latter two are variable-length encodings that store each Unicode
881character in one or more bytes. The default encoding is
882normally set to ASCII, which passes through characters in the range
8830 to 127 and rejects any other characters with an error.
884When a Unicode string is printed, written to a file, or converted
885with \function{str()}, conversion takes place using this default encoding.
Fred Drake9dc30bb2000-04-06 14:17:03 +0000886
887\begin{verbatim}
Ka-Ping Yee54019962001-02-13 22:20:22 +0000888>>> u"abc"
889u'abc'
890>>> str(u"abc")
891'abc'
Fred Drake9dc30bb2000-04-06 14:17:03 +0000892>>> u"äöü"
Ka-Ping Yee54019962001-02-13 22:20:22 +0000893u'\xe4\xf6\xfc'
894>>> str(u"äöü")
895Traceback (most recent call last):
896 File "<stdin>", line 1, in ?
Raymond Hettingera2f84ce2003-05-07 17:11:15 +0000897UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128)
Ka-Ping Yee54019962001-02-13 22:20:22 +0000898\end{verbatim}
899
900To convert a Unicode string into an 8-bit string using a specific
901encoding, Unicode objects provide an \function{encode()} method
902that takes one argument, the name of the encoding. Lowercase names
903for encodings are preferred.
904
905\begin{verbatim}
906>>> u"äöü".encode('utf-8')
907'\xc3\xa4\xc3\xb6\xc3\xbc'
Fred Drake9dc30bb2000-04-06 14:17:03 +0000908\end{verbatim}
909
910If you have data in a specific encoding and want to produce a
911corresponding Unicode string from it, you can use the
Ka-Ping Yee54019962001-02-13 22:20:22 +0000912\function{unicode()} function with the encoding name as the second
Fred Drake9dc30bb2000-04-06 14:17:03 +0000913argument.
914
915\begin{verbatim}
Ka-Ping Yee54019962001-02-13 22:20:22 +0000916>>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8')
917u'\xe4\xf6\xfc'
Fred Drake9dc30bb2000-04-06 14:17:03 +0000918\end{verbatim}
919
Fred Drakeb7833d31998-09-11 16:21:55 +0000920\subsection{Lists \label{lists}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000921
Fred Drakeeee08cd1997-12-04 15:43:15 +0000922Python knows a number of \emph{compound} data types, used to group
923together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000924can be written as a list of comma-separated values (items) between
925square brackets. List items need not all have the same type.
926
Fred Drake8842e861998-02-13 07:16:30 +0000927\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000928>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000929>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000930['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000931\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000932
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000933Like string indices, list indices start at 0, and lists can be sliced,
934concatenated and so on:
935
Fred Drake8842e861998-02-13 07:16:30 +0000936\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000937>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000938'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000939>>> a[3]
9401234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000941>>> a[-2]
942100
943>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000944['eggs', 100]
945>>> a[:2] + ['bacon', 2*2]
946['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000947>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000948['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000949\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000950
Fred Drakeeee08cd1997-12-04 15:43:15 +0000951Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000952individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000953
Fred Drake8842e861998-02-13 07:16:30 +0000954\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000955>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000956['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000957>>> a[2] = a[2] + 23
958>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000959['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000960\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000961
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000962Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000963of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000964
Fred Drake8842e861998-02-13 07:16:30 +0000965\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000966>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000967... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000968>>> a
969[1, 12, 123, 1234]
970>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000971... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000972>>> a
973[123, 1234]
974>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000975... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000976>>> a
977[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000978>>> a[:0] = a # Insert (a copy of) itself at the beginning
979>>> a
980[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000981\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000982
Fred Drake8842e861998-02-13 07:16:30 +0000983The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000984
Fred Drake8842e861998-02-13 07:16:30 +0000985\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000986>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00009878
Fred Drake8842e861998-02-13 07:16:30 +0000988\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000989
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000990It is possible to nest lists (create lists containing other lists),
991for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000992
Fred Drake8842e861998-02-13 07:16:30 +0000993\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000994>>> q = [2, 3]
995>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000996>>> len(p)
9973
998>>> p[1]
999[2, 3]
1000>>> p[1][0]
10012
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001002>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001003>>> p
1004[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001005>>> q
1006[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +00001007\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001008
Fred Drakeeee08cd1997-12-04 15:43:15 +00001009Note that in the last example, \code{p[1]} and \code{q} really refer to
1010the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001011
Fred Drakeb7833d31998-09-11 16:21:55 +00001012\section{First Steps Towards Programming \label{firstSteps}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001013
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001014Of course, we can use Python for more complicated tasks than adding
1015two and two together. For instance, we can write an initial
Fred Drake979d0412001-04-03 17:41:56 +00001016sub-sequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001017
Fred Drake8842e861998-02-13 07:16:30 +00001018\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001019>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +00001020... # the sum of two elements defines the next
1021... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001022>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001023... print b
1024... a, b = b, a+b
1025...
10261
10271
10282
10293
10305
10318
Fred Drake8842e861998-02-13 07:16:30 +00001032\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001033
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001034This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001035
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001036\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001037
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001038\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001039The first line contains a \emph{multiple assignment}: the variables
1040\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001041last line this is used again, demonstrating that the expressions on
1042the right-hand side are all evaluated first before any of the
Fred Drake20082d92000-04-03 04:26:58 +00001043assignments take place. The right-hand side expressions are evaluated
1044from the left to the right.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001045
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001046\item
Fred Drake8842e861998-02-13 07:16:30 +00001047The \keyword{while} loop executes as long as the condition (here:
Fred Drakeee84d591999-03-10 17:25:30 +00001048\code{b < 10}) remains true. In Python, like in C, any non-zero
Fred Drake8842e861998-02-13 07:16:30 +00001049integer value is true; zero is false. The condition may also be a
1050string or list value, in fact any sequence; anything with a non-zero
1051length is true, empty sequences are false. The test used in the
1052example is a simple comparison. The standard comparison operators are
Fred Drake20082d92000-04-03 04:26:58 +00001053written the same as in C: \code{<} (less than), \code{>} (greater than),
1054\code{==} (equal to), \code{<=} (less than or equal to),
1055\code{>=} (greater than or equal to) and \code{!=} (not equal to).
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001056
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001057\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001058The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001059way of grouping statements. Python does not (yet!) provide an
1060intelligent input line editing facility, so you have to type a tab or
1061space(s) for each indented line. In practice you will prepare more
1062complicated input for Python with a text editor; most text editors have
1063an auto-indent facility. When a compound statement is entered
1064interactively, it must be followed by a blank line to indicate
1065completion (since the parser cannot guess when you have typed the last
Fred Drake20082d92000-04-03 04:26:58 +00001066line). Note that each line within a basic block must be indented by
1067the same amount.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001068
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001069\item
Fred Drake8842e861998-02-13 07:16:30 +00001070The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001071given. It differs from just writing the expression you want to write
1072(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001073multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001074and a space is inserted between items, so you can format things nicely,
1075like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001076
Fred Drake8842e861998-02-13 07:16:30 +00001077\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001078>>> i = 256*256
1079>>> print 'The value of i is', i
1080The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +00001081\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001082
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001083A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001084
Fred Drake8842e861998-02-13 07:16:30 +00001085\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001086>>> a, b = 0, 1
1087>>> while b < 1000:
1088... print b,
1089... a, b = b, a+b
1090...
10911 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +00001092\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001093
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001094Note that the interpreter inserts a newline before it prints the next
1095prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001096
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001097\end{itemize}
1098
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001099
Fred Drakeb7833d31998-09-11 16:21:55 +00001100\chapter{More Control Flow Tools \label{moreControl}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001101
Fred Drake8842e861998-02-13 07:16:30 +00001102Besides the \keyword{while} statement just introduced, Python knows
1103the usual control flow statements known from other languages, with
1104some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001105
Fred Drakeb7833d31998-09-11 16:21:55 +00001106\section{\keyword{if} Statements \label{if}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001107
Fred Drake20082d92000-04-03 04:26:58 +00001108Perhaps the most well-known statement type is the
1109\keyword{if} statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001110
Fred Drake8842e861998-02-13 07:16:30 +00001111\begin{verbatim}
Fred Draked3ba10f2001-08-14 19:55:42 +00001112>>> x = int(raw_input("Please enter an integer: "))
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001113>>> if x < 0:
1114... x = 0
1115... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001116... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001117... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001118... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001119... print 'Single'
1120... else:
1121... print 'More'
1122...
Fred Drake8842e861998-02-13 07:16:30 +00001123\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001124
Fred Drake20082d92000-04-03 04:26:58 +00001125There can be zero or more \keyword{elif} parts, and the
1126\keyword{else} part is optional. The keyword `\keyword{elif}' is
1127short for `else if', and is useful to avoid excessive indentation. An
1128\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif} \ldots\ sequence
Fred Drake8842e861998-02-13 07:16:30 +00001129% Weird spacings happen here if the wrapping of the source text
1130% gets changed in the wrong way.
Fred Drake860106a2000-10-20 03:03:18 +00001131is a substitute for the \keyword{switch} or
1132\keyword{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001133
Fred Drakeb7833d31998-09-11 16:21:55 +00001134
1135\section{\keyword{for} Statements \label{for}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001136
Fred Drakef790b161998-11-30 20:37:24 +00001137The \keyword{for}\stindex{for} statement in Python differs a bit from
Fred Drakeee84d591999-03-10 17:25:30 +00001138what you may be used to in C or Pascal. Rather than always
Fred Drakef790b161998-11-30 20:37:24 +00001139iterating over an arithmetic progression of numbers (like in Pascal),
1140or giving the user the ability to define both the iteration step and
Fred Drake20082d92000-04-03 04:26:58 +00001141halting condition (as C), Python's
1142\keyword{for}\stindex{for} statement iterates over the items of any
Fred Drakeed514942001-07-06 17:28:39 +00001143sequence (a list or a string), in the order that they appear in
Fred Drake20082d92000-04-03 04:26:58 +00001144the sequence. For example (no pun intended):
Fred Drakef790b161998-11-30 20:37:24 +00001145% One suggestion was to give a real C example here, but that may only
1146% serve to confuse non-C programmers.
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001147
Fred Drake8842e861998-02-13 07:16:30 +00001148\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001149>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +00001150... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001151>>> for x in a:
1152... print x, len(x)
1153...
1154cat 3
1155window 6
1156defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +00001157\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001158
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001159It is not safe to modify the sequence being iterated over in the loop
Fred Drakeed514942001-07-06 17:28:39 +00001160(this can only happen for mutable sequence types, such as lists). If
1161you need to modify the list you are iterating over (for example, to
1162duplicate selected items) you must iterate over a copy. The slice
1163notation makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001164
Fred Drake8842e861998-02-13 07:16:30 +00001165\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001166>>> for x in a[:]: # make a slice copy of the entire list
1167... if len(x) > 6: a.insert(0, x)
1168...
1169>>> a
1170['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +00001171\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001172
Fred Drakeb7833d31998-09-11 16:21:55 +00001173
1174\section{The \function{range()} Function \label{range}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001175
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001176If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +00001177function \function{range()} comes in handy. It generates lists
Fred Drakeed514942001-07-06 17:28:39 +00001178containing arithmetic progressions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001179
Fred Drake8842e861998-02-13 07:16:30 +00001180\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001181>>> range(10)
1182[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +00001183\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001184
Fred Drake8842e861998-02-13 07:16:30 +00001185The given end point is never part of the generated list;
1186\code{range(10)} generates a list of 10 values, exactly the legal
1187indices for items of a sequence of length 10. It is possible to let
1188the range start at another number, or to specify a different increment
Fred Drake20082d92000-04-03 04:26:58 +00001189(even negative; sometimes this is called the `step'):
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001190
Fred Drake8842e861998-02-13 07:16:30 +00001191\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001192>>> range(5, 10)
1193[5, 6, 7, 8, 9]
1194>>> range(0, 10, 3)
1195[0, 3, 6, 9]
1196>>> range(-10, -100, -30)
1197[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +00001198\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001199
Fred Drake20082d92000-04-03 04:26:58 +00001200To iterate over the indices of a sequence, combine
1201\function{range()} and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001202
Fred Drake8842e861998-02-13 07:16:30 +00001203\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001204>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001205>>> for i in range(len(a)):
1206... print i, a[i]
1207...
12080 Mary
12091 had
12102 a
12113 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +000012124 lamb
Fred Drake8842e861998-02-13 07:16:30 +00001213\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001214
Fred Drake20082d92000-04-03 04:26:58 +00001215
Fred Drake391564f1998-04-01 23:11:56 +00001216\section{\keyword{break} and \keyword{continue} Statements, and
Fred Drakeb7833d31998-09-11 16:21:55 +00001217 \keyword{else} Clauses on Loops
1218 \label{break}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001219
Fred Drakeee84d591999-03-10 17:25:30 +00001220The \keyword{break} statement, like in C, breaks out of the smallest
Fred Drake8842e861998-02-13 07:16:30 +00001221enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001222
Fred Drakeee84d591999-03-10 17:25:30 +00001223The \keyword{continue} statement, also borrowed from C, continues
Fred Drake8842e861998-02-13 07:16:30 +00001224with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001225
Fred Drake8842e861998-02-13 07:16:30 +00001226Loop statements may have an \code{else} clause; it is executed when
1227the loop terminates through exhaustion of the list (with
1228\keyword{for}) or when the condition becomes false (with
1229\keyword{while}), but not when the loop is terminated by a
1230\keyword{break} statement. This is exemplified by the following loop,
1231which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001232
Fred Drake8842e861998-02-13 07:16:30 +00001233\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001234>>> for n in range(2, 10):
1235... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001236... if n % x == 0:
Fred Drake236ffba2003-08-16 06:30:47 +00001237... print n, 'equals', x, '*', n/x
1238... break
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001239... else:
Fred Drake236ffba2003-08-16 06:30:47 +00001240... # loop fell through without finding a factor
1241... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001242...
Guido van Rossum2292b8e1991-01-23 16:31:24 +000012432 is a prime number
12443 is a prime number
12454 equals 2 * 2
12465 is a prime number
12476 equals 2 * 3
12487 is a prime number
12498 equals 2 * 4
12509 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +00001251\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001252
Fred Drake31b761e2000-09-29 15:17:36 +00001253
Fred Drakeb7833d31998-09-11 16:21:55 +00001254\section{\keyword{pass} Statements \label{pass}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001255
Fred Drake8842e861998-02-13 07:16:30 +00001256The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001257It can be used when a statement is required syntactically but the
1258program requires no action.
1259For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001260
Fred Drake8842e861998-02-13 07:16:30 +00001261\begin{verbatim}
Raymond Hettingera6e16a82002-08-21 04:54:00 +00001262>>> while True:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001263... pass # Busy-wait for keyboard interrupt
1264...
Fred Drake8842e861998-02-13 07:16:30 +00001265\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001266
Fred Drake31b761e2000-09-29 15:17:36 +00001267
Fred Drakeb7833d31998-09-11 16:21:55 +00001268\section{Defining Functions \label{functions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001269
1270We can create a function that writes the Fibonacci series to an
1271arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001272
Fred Drake8842e861998-02-13 07:16:30 +00001273\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001274>>> def fib(n): # write Fibonacci series up to n
Fred Drake23d45f42001-12-20 23:54:56 +00001275... """Print a Fibonacci series up to n."""
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001276... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001277... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001278... print b,
1279... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001280...
1281>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001282... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000012831 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001284\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001285
Fred Drake8842e861998-02-13 07:16:30 +00001286The keyword \keyword{def} introduces a function \emph{definition}. It
1287must be followed by the function name and the parenthesized list of
1288formal parameters. The statements that form the body of the function
Fred Drake20082d92000-04-03 04:26:58 +00001289start at the next line, and must be indented. The first statement of
1290the function body can optionally be a string literal; this string
1291literal is the function's \index{documentation strings}documentation
1292string, or \dfn{docstring}.\index{docstrings}\index{strings, documentation}
1293
1294There are tools which use docstrings to automatically produce online
1295or printed documentation, or to let the user interactively browse
1296through code; it's good practice to include docstrings in code that
1297you write, so try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001298
Fred Drakeeee08cd1997-12-04 15:43:15 +00001299The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001300for the local variables of the function. More precisely, all variable
1301assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001302whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001303in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001304Thus, global variables cannot be directly assigned a value within a
1305function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001306they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001307
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001308The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001309the local symbol table of the called function when it is called; thus,
Fred Drake20082d92000-04-03 04:26:58 +00001310arguments are passed using \emph{call by value} (where the
1311\emph{value} is always an object \emph{reference}, not the value of
1312the object).\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001313 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001314 description, since if a mutable object is passed, the caller
Fred Drakeed514942001-07-06 17:28:39 +00001315 will see any changes the callee makes to it (items
Guido van Rossum6938f061994-08-01 12:22:53 +00001316 inserted into a list).
Fred Drake20082d92000-04-03 04:26:58 +00001317} When a function calls another function, a new local symbol table is
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001318created for that call.
1319
Fred Drake8842e861998-02-13 07:16:30 +00001320A function definition introduces the function name in the current
1321symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001322has a type that is recognized by the interpreter as a user-defined
1323function. This value can be assigned to another name which can then
1324also be used as a function. This serves as a general renaming
1325mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001326
Fred Drake8842e861998-02-13 07:16:30 +00001327\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001328>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001329<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001330>>> f = fib
1331>>> f(100)
13321 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001333\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001334
Fred Drakeeee08cd1997-12-04 15:43:15 +00001335You might object that \code{fib} is not a function but a procedure. In
Fred Drakeee84d591999-03-10 17:25:30 +00001336Python, like in C, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001337value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001338albeit a rather boring one. This value is called \code{None} (it's a
1339built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001340the interpreter if it would be the only value written. You can see it
1341if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001342
Fred Drake8842e861998-02-13 07:16:30 +00001343\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001344>>> print fib(0)
1345None
Fred Drake8842e861998-02-13 07:16:30 +00001346\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001347
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001348It is simple to write a function that returns a list of the numbers of
1349the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001350
Fred Drake8842e861998-02-13 07:16:30 +00001351\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001352>>> def fib2(n): # return Fibonacci series up to n
Fred Drake23d45f42001-12-20 23:54:56 +00001353... """Return a list containing the Fibonacci series up to n."""
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001354... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001355... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001356... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001357... result.append(b) # see below
1358... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001359... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001360...
1361>>> f100 = fib2(100) # call it
1362>>> f100 # write the result
1363[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001364\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +00001365
Guido van Rossum4410c751991-06-04 20:22:18 +00001366This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001367
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001368\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001369
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001370\item
Fred Drake8842e861998-02-13 07:16:30 +00001371The \keyword{return} statement returns with a value from a function.
Fred Drake0fe5af92001-01-19 22:34:59 +00001372\keyword{return} without an expression argument returns \code{None}.
1373Falling off the end of a procedure also returns \code{None}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001374
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001375\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001376The statement \code{result.append(b)} calls a \emph{method} of the list
1377object \code{result}. A method is a function that `belongs' to an
1378object and is named \code{obj.methodname}, where \code{obj} is some
1379object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001380of a method that is defined by the object's type. Different types
1381define different methods. Methods of different types may have the
1382same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001383own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001384in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001385The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001386list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001387example it is equivalent to \samp{result = result + [b]}, but more
1388efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001389
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001390\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001391
Fred Drakeb7833d31998-09-11 16:21:55 +00001392\section{More on Defining Functions \label{defining}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001393
Guido van Rossum02455691997-07-17 16:21:52 +00001394It is also possible to define functions with a variable number of
1395arguments. There are three forms, which can be combined.
1396
Fred Drakeb7833d31998-09-11 16:21:55 +00001397\subsection{Default Argument Values \label{defaultArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001398
1399The most useful form is to specify a default value for one or more
1400arguments. This creates a function that can be called with fewer
Fred Drakeed514942001-07-06 17:28:39 +00001401arguments than it is defined
Guido van Rossum02455691997-07-17 16:21:52 +00001402
1403\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001404def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
Raymond Hettingera6e16a82002-08-21 04:54:00 +00001405 while True:
Fred Drake8842e861998-02-13 07:16:30 +00001406 ok = raw_input(prompt)
1407 if ok in ('y', 'ye', 'yes'): return 1
1408 if ok in ('n', 'no', 'nop', 'nope'): return 0
1409 retries = retries - 1
1410 if retries < 0: raise IOError, 'refusenik user'
1411 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001412\end{verbatim}
1413
1414This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001415\code{ask_ok('Do you really want to quit?')} or like this:
1416\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001417
1418The default values are evaluated at the point of function definition
Fred Drakeed514942001-07-06 17:28:39 +00001419in the \emph{defining} scope, so that
Guido van Rossum02455691997-07-17 16:21:52 +00001420
1421\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001422i = 5
Fred Drake8b09f492001-09-06 18:21:30 +00001423
1424def f(arg=i):
1425 print arg
1426
Fred Drake8842e861998-02-13 07:16:30 +00001427i = 6
1428f()
Guido van Rossum02455691997-07-17 16:21:52 +00001429\end{verbatim}
1430
Fred Drakeeee08cd1997-12-04 15:43:15 +00001431will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001432
Guido van Rossumaee5e261998-08-07 17:45:09 +00001433\strong{Important warning:} The default value is evaluated only once.
1434This makes a difference when the default is a mutable object such as a
Fred Drake3a8fbe72003-06-18 17:14:29 +00001435list, dictionary, or instances of most classes. For example, the
1436following function accumulates the arguments passed to it on
1437subsequent calls:
Guido van Rossumaee5e261998-08-07 17:45:09 +00001438
1439\begin{verbatim}
Fred Drake8b09f492001-09-06 18:21:30 +00001440def f(a, L=[]):
1441 L.append(a)
1442 return L
1443
Guido van Rossumaee5e261998-08-07 17:45:09 +00001444print f(1)
1445print f(2)
1446print f(3)
1447\end{verbatim}
1448
1449This will print
1450
1451\begin{verbatim}
1452[1]
1453[1, 2]
1454[1, 2, 3]
1455\end{verbatim}
1456
1457If you don't want the default to be shared between subsequent calls,
1458you can write the function like this instead:
1459
1460\begin{verbatim}
Fred Drake8b09f492001-09-06 18:21:30 +00001461def f(a, L=None):
1462 if L is None:
1463 L = []
1464 L.append(a)
1465 return L
Guido van Rossumaee5e261998-08-07 17:45:09 +00001466\end{verbatim}
1467
Fred Drakeb7833d31998-09-11 16:21:55 +00001468\subsection{Keyword Arguments \label{keywordArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001469
1470Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001471keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001472instance, the following function:
1473
1474\begin{verbatim}
1475def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1476 print "-- This parrot wouldn't", action,
1477 print "if you put", voltage, "Volts through it."
1478 print "-- Lovely plumage, the", type
1479 print "-- It's", state, "!"
1480\end{verbatim}
1481
1482could be called in any of the following ways:
1483
1484\begin{verbatim}
1485parrot(1000)
1486parrot(action = 'VOOOOOM', voltage = 1000000)
1487parrot('a thousand', state = 'pushing up the daisies')
1488parrot('a million', 'bereft of life', 'jump')
1489\end{verbatim}
1490
1491but the following calls would all be invalid:
1492
1493\begin{verbatim}
1494parrot() # required argument missing
1495parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1496parrot(110, voltage=220) # duplicate value for argument
1497parrot(actor='John Cleese') # unknown keyword
1498\end{verbatim}
1499
1500In general, an argument list must have any positional arguments
1501followed by any keyword arguments, where the keywords must be chosen
1502from the formal parameter names. It's not important whether a formal
Fred Drakef1ad2071999-06-30 15:32:50 +00001503parameter has a default value or not. No argument may receive a
Guido van Rossum02455691997-07-17 16:21:52 +00001504value more than once --- formal parameter names corresponding to
1505positional arguments cannot be used as keywords in the same calls.
Fred Drakef1ad2071999-06-30 15:32:50 +00001506Here's an example that fails due to this restriction:
1507
1508\begin{verbatim}
1509>>> def function(a):
1510... pass
1511...
1512>>> function(0, a=0)
Fred Drake162c6a62001-02-14 03:20:18 +00001513Traceback (most recent call last):
Fred Drakef1ad2071999-06-30 15:32:50 +00001514 File "<stdin>", line 1, in ?
Raymond Hettingera02469f2003-05-07 17:49:36 +00001515TypeError: function() got multiple values for keyword argument 'a'
Fred Drakef1ad2071999-06-30 15:32:50 +00001516\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00001517
1518When a final formal parameter of the form \code{**\var{name}} is
1519present, it receives a dictionary containing all keyword arguments
1520whose keyword doesn't correspond to a formal parameter. This may be
Fred Drake20082d92000-04-03 04:26:58 +00001521combined with a formal parameter of the form
1522\code{*\var{name}} (described in the next subsection) which receives a
1523tuple containing the positional arguments beyond the formal parameter
1524list. (\code{*\var{name}} must occur before \code{**\var{name}}.)
1525For example, if we define a function like this:
Guido van Rossum02455691997-07-17 16:21:52 +00001526
1527\begin{verbatim}
1528def cheeseshop(kind, *arguments, **keywords):
1529 print "-- Do you have any", kind, '?'
1530 print "-- I'm sorry, we're all out of", kind
1531 for arg in arguments: print arg
1532 print '-'*40
Fred Drakec26467d2002-01-29 14:53:30 +00001533 keys = keywords.keys()
1534 keys.sort()
1535 for kw in keys: print kw, ':', keywords[kw]
Guido van Rossum02455691997-07-17 16:21:52 +00001536\end{verbatim}
1537
1538It could be called like this:
1539
1540\begin{verbatim}
1541cheeseshop('Limburger', "It's very runny, sir.",
1542 "It's really very, VERY runny, sir.",
1543 client='John Cleese',
1544 shopkeeper='Michael Palin',
1545 sketch='Cheese Shop Sketch')
1546\end{verbatim}
1547
1548and of course it would print:
1549
1550\begin{verbatim}
1551-- Do you have any Limburger ?
1552-- I'm sorry, we're all out of Limburger
1553It's very runny, sir.
1554It's really very, VERY runny, sir.
1555----------------------------------------
1556client : John Cleese
1557shopkeeper : Michael Palin
1558sketch : Cheese Shop Sketch
1559\end{verbatim}
1560
Fred Drakec26467d2002-01-29 14:53:30 +00001561Note that the \method{sort()} method of the list of keyword argument
1562names is called before printing the contents of the \code{keywords}
1563dictionary; if this is not done, the order in which the arguments are
1564printed is undefined.
1565
Fred Drake31b761e2000-09-29 15:17:36 +00001566
Fred Drakeb7833d31998-09-11 16:21:55 +00001567\subsection{Arbitrary Argument Lists \label{arbitraryArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001568
1569Finally, the least frequently used option is to specify that a
1570function can be called with an arbitrary number of arguments. These
1571arguments will be wrapped up in a tuple. Before the variable number
1572of arguments, zero or more normal arguments may occur.
1573
1574\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001575def fprintf(file, format, *args):
1576 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001577\end{verbatim}
1578
Fred Drakea594baf1998-04-03 05:16:31 +00001579
Raymond Hettinger0eec0872003-08-08 23:32:46 +00001580\subsection{Unpacking Argument Lists \label{unpacking-arguments}}
1581
1582The reverse situation occurs when the arguments are already in a list
1583or tuple but need to be unpacked for a function call requiring separate
1584positional arguments. For instance, the built-in \function{range()}
1585function expects separate \var{start} and \var{stop} arguments. If they
1586are not available separately, write the function call with the
1587\code{*}-operator to unpack the arguments out of a list or tuple:
1588
1589\begin{verbatim}
1590>>> range(3, 6) # normal call with separate arguments
1591[3, 4, 5]
1592>>> args = [3, 6]
1593>>> range(*args) # call with arguments unpacked from a list
1594[3, 4, 5]
1595\end{verbatim}
1596
1597
Fred Drakeb7833d31998-09-11 16:21:55 +00001598\subsection{Lambda Forms \label{lambda}}
Fred Drakea594baf1998-04-03 05:16:31 +00001599
1600By popular demand, a few features commonly found in functional
1601programming languages and Lisp have been added to Python. With the
1602\keyword{lambda} keyword, small anonymous functions can be created.
1603Here's a function that returns the sum of its two arguments:
1604\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1605objects are required. They are syntactically restricted to a single
1606expression. Semantically, they are just syntactic sugar for a normal
1607function definition. Like nested function definitions, lambda forms
Fred Drakefcf94682001-12-03 21:47:37 +00001608can reference variables from the containing scope:
Fred Drakea594baf1998-04-03 05:16:31 +00001609
1610\begin{verbatim}
Tim Petersc1134652000-11-27 06:38:04 +00001611>>> def make_incrementor(n):
Fred Drakefcf94682001-12-03 21:47:37 +00001612... return lambda x: x + n
Tim Petersc1134652000-11-27 06:38:04 +00001613...
1614>>> f = make_incrementor(42)
1615>>> f(0)
161642
1617>>> f(1)
161843
Fred Drakea594baf1998-04-03 05:16:31 +00001619\end{verbatim}
1620
Fred Drake20082d92000-04-03 04:26:58 +00001621
Fred Drakeb7833d31998-09-11 16:21:55 +00001622\subsection{Documentation Strings \label{docstrings}}
Fred Drakea594baf1998-04-03 05:16:31 +00001623
1624There are emerging conventions about the content and formatting of
1625documentation strings.
Fred Drake20082d92000-04-03 04:26:58 +00001626\index{docstrings}\index{documentation strings}
1627\index{strings, documentation}
Fred Drakea594baf1998-04-03 05:16:31 +00001628
1629The first line should always be a short, concise summary of the
1630object's purpose. For brevity, it should not explicitly state the
1631object's name or type, since these are available by other means
1632(except if the name happens to be a verb describing a function's
1633operation). This line should begin with a capital letter and end with
1634a period.
1635
1636If there are more lines in the documentation string, the second line
1637should be blank, visually separating the summary from the rest of the
Fred Drake4b1a07a1999-03-12 18:21:32 +00001638description. The following lines should be one or more paragraphs
1639describing the object's calling conventions, its side effects, etc.
Fred Drakea594baf1998-04-03 05:16:31 +00001640
1641The Python parser does not strip indentation from multi-line string
1642literals in Python, so tools that process documentation have to strip
Fred Drake20082d92000-04-03 04:26:58 +00001643indentation if desired. This is done using the following convention.
1644The first non-blank line \emph{after} the first line of the string
1645determines the amount of indentation for the entire documentation
1646string. (We can't use the first line since it is generally adjacent
1647to the string's opening quotes so its indentation is not apparent in
1648the string literal.) Whitespace ``equivalent'' to this indentation is
1649then stripped from the start of all lines of the string. Lines that
1650are indented less should not occur, but if they occur all their
1651leading whitespace should be stripped. Equivalence of whitespace
1652should be tested after expansion of tabs (to 8 spaces, normally).
1653
1654Here is an example of a multi-line docstring:
1655
1656\begin{verbatim}
1657>>> def my_function():
1658... """Do nothing, but document it.
1659...
1660... No, really, it doesn't do anything.
1661... """
1662... pass
1663...
1664>>> print my_function.__doc__
1665Do nothing, but document it.
1666
1667 No, really, it doesn't do anything.
1668
1669\end{verbatim}
Fred Drakea594baf1998-04-03 05:16:31 +00001670
1671
1672
Fred Drakeb7833d31998-09-11 16:21:55 +00001673\chapter{Data Structures \label{structures}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001674
1675This chapter describes some things you've learned about already in
1676more detail, and adds some new things as well.
1677
Fred Drake20082d92000-04-03 04:26:58 +00001678
Fred Drakeb7833d31998-09-11 16:21:55 +00001679\section{More on Lists \label{moreLists}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001680
1681The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001682of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001683
Fred Drake55ad7f82002-06-11 02:56:17 +00001684\begin{methoddesc}[list]{append}{x}
Fred Drake20082d92000-04-03 04:26:58 +00001685Add an item to the end of the list;
Fred Drake55ad7f82002-06-11 02:56:17 +00001686equivalent to \code{a[len(a):] = [\var{x}]}.
1687\end{methoddesc}
Fred Drake20082d92000-04-03 04:26:58 +00001688
Fred Drake55ad7f82002-06-11 02:56:17 +00001689\begin{methoddesc}[list]{extend}{L}
Fred Drake20082d92000-04-03 04:26:58 +00001690Extend the list by appending all the items in the given list;
Fred Drake55ad7f82002-06-11 02:56:17 +00001691equivalent to \code{a[len(a):] = \var{L}}.
1692\end{methoddesc}
Fred Drake20082d92000-04-03 04:26:58 +00001693
Fred Drake55ad7f82002-06-11 02:56:17 +00001694\begin{methoddesc}[list]{insert}{i, x}
1695Insert an item at a given position. The first argument is the index
1696of the element before which to insert, so \code{a.insert(0, \var{x})}
1697inserts at the front of the list, and \code{a.insert(len(a), \var{x})}
1698is equivalent to \code{a.append(\var{x})}.
1699\end{methoddesc}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001700
Fred Drake55ad7f82002-06-11 02:56:17 +00001701\begin{methoddesc}[list]{remove}{x}
1702Remove the first item from the list whose value is \var{x}.
Fred Drake20082d92000-04-03 04:26:58 +00001703It is an error if there is no such item.
Fred Drake55ad7f82002-06-11 02:56:17 +00001704\end{methoddesc}
Fred Drake20082d92000-04-03 04:26:58 +00001705
Fred Drake55ad7f82002-06-11 02:56:17 +00001706\begin{methoddesc}[list]{pop}{\optional{i}}
Fred Drake20082d92000-04-03 04:26:58 +00001707Remove the item at the given position in the list, and return it. If
1708no index is specified, \code{a.pop()} returns the last item in the
Fred Drake55ad7f82002-06-11 02:56:17 +00001709list. The item is also removed from the list. (The square brackets
1710around the \var{i} in the method signature denote that the parameter
1711is optional, not that you should type square brackets at that
1712position. You will see this notation frequently in the
1713\citetitle[../lib/lib.html]{Python Library Reference}.)
1714\end{methoddesc}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001715
Fred Drake55ad7f82002-06-11 02:56:17 +00001716\begin{methoddesc}[list]{index}{x}
1717Return the index in the list of the first item whose value is \var{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001718It is an error if there is no such item.
Fred Drake55ad7f82002-06-11 02:56:17 +00001719\end{methoddesc}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001720
Fred Drake55ad7f82002-06-11 02:56:17 +00001721\begin{methoddesc}[list]{count}{x}
1722Return the number of times \var{x} appears in the list.
1723\end{methoddesc}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001724
Fred Drake55ad7f82002-06-11 02:56:17 +00001725\begin{methoddesc}[list]{sort}{}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001726Sort the items of the list, in place.
Fred Drake55ad7f82002-06-11 02:56:17 +00001727\end{methoddesc}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001728
Fred Drake55ad7f82002-06-11 02:56:17 +00001729\begin{methoddesc}[list]{reverse}{}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001730Reverse the elements of the list, in place.
Fred Drake55ad7f82002-06-11 02:56:17 +00001731\end{methoddesc}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001732
Fred Drake20082d92000-04-03 04:26:58 +00001733An example that uses most of the list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001734
Fred Drake8842e861998-02-13 07:16:30 +00001735\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001736>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001737>>> print a.count(333), a.count(66.6), a.count('x')
17382 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001739>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001740>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001741>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001742[66.6, 333, -1, 333, 1, 1234.5, 333]
1743>>> a.index(333)
17441
1745>>> a.remove(333)
1746>>> a
1747[66.6, -1, 333, 1, 1234.5, 333]
1748>>> a.reverse()
1749>>> a
1750[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001751>>> a.sort()
1752>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001753[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001754\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001755
Fred Drake20082d92000-04-03 04:26:58 +00001756
1757\subsection{Using Lists as Stacks \label{lists-as-stacks}}
Fred Drake67fdaa42001-03-06 07:19:34 +00001758\sectionauthor{Ka-Ping Yee}{ping@lfw.org}
Fred Drake20082d92000-04-03 04:26:58 +00001759
1760The list methods make it very easy to use a list as a stack, where the
1761last element added is the first element retrieved (``last-in,
1762first-out''). To add an item to the top of the stack, use
1763\method{append()}. To retrieve an item from the top of the stack, use
1764\method{pop()} without an explicit index. For example:
1765
1766\begin{verbatim}
1767>>> stack = [3, 4, 5]
1768>>> stack.append(6)
1769>>> stack.append(7)
1770>>> stack
1771[3, 4, 5, 6, 7]
1772>>> stack.pop()
17737
1774>>> stack
1775[3, 4, 5, 6]
1776>>> stack.pop()
17776
1778>>> stack.pop()
17795
1780>>> stack
1781[3, 4]
1782\end{verbatim}
1783
1784
1785\subsection{Using Lists as Queues \label{lists-as-queues}}
Fred Drake67fdaa42001-03-06 07:19:34 +00001786\sectionauthor{Ka-Ping Yee}{ping@lfw.org}
Fred Drake20082d92000-04-03 04:26:58 +00001787
1788You can also use a list conveniently as a queue, where the first
1789element added is the first element retrieved (``first-in,
1790first-out''). To add an item to the back of the queue, use
1791\method{append()}. To retrieve an item from the front of the queue,
1792use \method{pop()} with \code{0} as the index. For example:
1793
1794\begin{verbatim}
1795>>> queue = ["Eric", "John", "Michael"]
1796>>> queue.append("Terry") # Terry arrives
1797>>> queue.append("Graham") # Graham arrives
1798>>> queue.pop(0)
1799'Eric'
1800>>> queue.pop(0)
1801'John'
1802>>> queue
1803['Michael', 'Terry', 'Graham']
1804\end{verbatim}
1805
1806
Fred Drakeb7833d31998-09-11 16:21:55 +00001807\subsection{Functional Programming Tools \label{functional}}
Guido van Rossum02455691997-07-17 16:21:52 +00001808
1809There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001810lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001811
Fred Drake8842e861998-02-13 07:16:30 +00001812\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1813the same type, if possible) consisting of those items from the
1814sequence for which \code{\var{function}(\var{item})} is true. For
1815example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001816
1817\begin{verbatim}
Fred Drakeee84d591999-03-10 17:25:30 +00001818>>> def f(x): return x % 2 != 0 and x % 3 != 0
Fred Drake8842e861998-02-13 07:16:30 +00001819...
1820>>> filter(f, range(2, 25))
1821[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001822\end{verbatim}
1823
Fred Drake8842e861998-02-13 07:16:30 +00001824\samp{map(\var{function}, \var{sequence})} calls
1825\code{\var{function}(\var{item})} for each of the sequence's items and
1826returns a list of the return values. For example, to compute some
1827cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001828
1829\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001830>>> def cube(x): return x*x*x
1831...
1832>>> map(cube, range(1, 11))
1833[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001834\end{verbatim}
1835
1836More than one sequence may be passed; the function must then have as
1837many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001838corresponding item from each sequence (or \code{None} if some sequence
Neil Schemenauer90b182c2003-08-14 22:57:46 +00001839is shorter than another). For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001840
1841\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001842>>> seq = range(8)
Neil Schemenauer90b182c2003-08-14 22:57:46 +00001843>>> def add(x, y): return x+y
Fred Drake8842e861998-02-13 07:16:30 +00001844...
Neil Schemenauer90b182c2003-08-14 22:57:46 +00001845>>> map(add, seq, seq)
1846[0, 2, 4, 6, 8, 10, 12, 14]
Guido van Rossum02455691997-07-17 16:21:52 +00001847\end{verbatim}
1848
Fred Drake8842e861998-02-13 07:16:30 +00001849\samp{reduce(\var{func}, \var{sequence})} returns a single value
1850constructed by calling the binary function \var{func} on the first two
1851items of the sequence, then on the result and the next item, and so
1852on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001853
1854\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001855>>> def add(x,y): return x+y
1856...
1857>>> reduce(add, range(1, 11))
185855
Guido van Rossum02455691997-07-17 16:21:52 +00001859\end{verbatim}
1860
1861If there's only one item in the sequence, its value is returned; if
1862the sequence is empty, an exception is raised.
1863
1864A third argument can be passed to indicate the starting value. In this
1865case the starting value is returned for an empty sequence, and the
1866function is first applied to the starting value and the first sequence
1867item, then to the result and the next item, and so on. For example,
1868
1869\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001870>>> def sum(seq):
1871... def add(x,y): return x+y
1872... return reduce(add, seq, 0)
1873...
1874>>> sum(range(1, 11))
187555
1876>>> sum([])
18770
Guido van Rossum02455691997-07-17 16:21:52 +00001878\end{verbatim}
1879
Fred Drake03e929e2003-04-22 14:30:53 +00001880Don't use this example's definition of \function{sum()}: since summing
1881numbers is such a common need, a built-in function
1882\code{sum(\var{sequence})} is already provided, and works exactly like
1883this.
1884\versionadded{2.3}
Fred Drake31b761e2000-09-29 15:17:36 +00001885
Skip Montanaro803d6e52000-08-12 18:09:51 +00001886\subsection{List Comprehensions}
1887
Skip Montanaro46dfa5f2000-08-22 02:43:07 +00001888List comprehensions provide a concise way to create lists without resorting
1889to use of \function{map()}, \function{filter()} and/or \keyword{lambda}.
1890The resulting list definition tends often to be clearer than lists built
1891using those constructs. Each list comprehension consists of an expression
Fred Drake33fd5f72002-06-26 21:25:15 +00001892followed by a \keyword{for} clause, then zero or more \keyword{for} or
Skip Montanaro46dfa5f2000-08-22 02:43:07 +00001893\keyword{if} clauses. The result will be a list resulting from evaluating
1894the expression in the context of the \keyword{for} and \keyword{if} clauses
1895which follow it. If the expression would evaluate to a tuple, it must be
1896parenthesized.
Skip Montanaro803d6e52000-08-12 18:09:51 +00001897
1898\begin{verbatim}
Fred Drake1aebadf2000-08-16 21:44:03 +00001899>>> freshfruit = [' banana', ' loganberry ', 'passion fruit ']
1900>>> [weapon.strip() for weapon in freshfruit]
1901['banana', 'loganberry', 'passion fruit']
Skip Montanaro803d6e52000-08-12 18:09:51 +00001902>>> vec = [2, 4, 6]
Fred Drake1aebadf2000-08-16 21:44:03 +00001903>>> [3*x for x in vec]
Skip Montanaro803d6e52000-08-12 18:09:51 +00001904[6, 12, 18]
Fred Drake1aebadf2000-08-16 21:44:03 +00001905>>> [3*x for x in vec if x > 3]
1906[12, 18]
1907>>> [3*x for x in vec if x < 2]
1908[]
Skip Montanaro46dfa5f2000-08-22 02:43:07 +00001909>>> [[x,x**2] for x in vec]
1910[[2, 4], [4, 16], [6, 36]]
1911>>> [x, x**2 for x in vec] # error - parens required for tuples
Fred Drake13af4282001-09-21 21:10:05 +00001912 File "<stdin>", line 1, in ?
Skip Montanaro46dfa5f2000-08-22 02:43:07 +00001913 [x, x**2 for x in vec]
1914 ^
1915SyntaxError: invalid syntax
1916>>> [(x, x**2) for x in vec]
1917[(2, 4), (4, 16), (6, 36)]
Skip Montanaro803d6e52000-08-12 18:09:51 +00001918>>> vec1 = [2, 4, 6]
1919>>> vec2 = [4, 3, -9]
Fred Drake1aebadf2000-08-16 21:44:03 +00001920>>> [x*y for x in vec1 for y in vec2]
Skip Montanaro803d6e52000-08-12 18:09:51 +00001921[8, 6, -18, 16, 12, -36, 24, 18, -54]
Fred Drake1aebadf2000-08-16 21:44:03 +00001922>>> [x+y for x in vec1 for y in vec2]
Skip Montanaro803d6e52000-08-12 18:09:51 +00001923[6, 5, -7, 8, 7, -5, 10, 9, -3]
Fred Drake1da50f62001-12-03 18:54:33 +00001924>>> [vec1[i]*vec2[i] for i in range(len(vec1))]
1925[8, 12, -54]
Skip Montanaro803d6e52000-08-12 18:09:51 +00001926\end{verbatim}
1927
Raymond Hettinger44c42b92002-09-06 18:06:04 +00001928To make list comprehensions match the behavior of \keyword{for}
1929loops, assignments to the loop variable remain visible outside
1930of the comprehension:
1931
1932\begin{verbatim}
1933>>> x = 100 # this gets overwritten
1934>>> [x**3 for x in range(5)]
1935[0, 1, 8, 27, 64]
Raymond Hettingera02469f2003-05-07 17:49:36 +00001936>>> x # the final value for range(5)
19374
Raymond Hettinger44c42b92002-09-06 18:06:04 +00001938\end{verbatim}
1939
Fred Drake31b761e2000-09-29 15:17:36 +00001940
Fred Drakeb7833d31998-09-11 16:21:55 +00001941\section{The \keyword{del} statement \label{del}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001942
1943There is a way to remove an item from a list given its index instead
Fred Drake81f7eb62000-08-12 20:08:04 +00001944of its value: the \keyword{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001945remove slices from a list (which we did earlier by assignment of an
1946empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001947
Fred Drake8842e861998-02-13 07:16:30 +00001948\begin{verbatim}
Raymond Hettingera02469f2003-05-07 17:49:36 +00001949>>> a = [-1, 1, 66.6, 333, 333, 1234.5]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001950>>> del a[0]
1951>>> a
1952[1, 66.6, 333, 333, 1234.5]
1953>>> del a[2:4]
1954>>> a
1955[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001956\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001957
1958\keyword{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001959
Fred Drake8842e861998-02-13 07:16:30 +00001960\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001961>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001962\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001963
Fred Drakeeee08cd1997-12-04 15:43:15 +00001964Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001965another value is assigned to it). We'll find other uses for
1966\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001967
Fred Drake31b761e2000-09-29 15:17:36 +00001968
Fred Drakeb7833d31998-09-11 16:21:55 +00001969\section{Tuples and Sequences \label{tuples}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001970
Fred Drakeed514942001-07-06 17:28:39 +00001971We saw that lists and strings have many common properties, such as
Fred Drakeeee08cd1997-12-04 15:43:15 +00001972indexing and slicing operations. They are two examples of
1973\emph{sequence} data types. Since Python is an evolving language,
1974other sequence data types may be added. There is also another
1975standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001976
1977A tuple consists of a number of values separated by commas, for
1978instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001979
Fred Drake8842e861998-02-13 07:16:30 +00001980\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001981>>> t = 12345, 54321, 'hello!'
1982>>> t[0]
198312345
1984>>> t
1985(12345, 54321, 'hello!')
1986>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001987... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001988>>> u
1989((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001990\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001991
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001992As you see, on output tuples are alway enclosed in parentheses, so
1993that nested tuples are interpreted correctly; they may be input with
1994or without surrounding parentheses, although often parentheses are
1995necessary anyway (if the tuple is part of a larger expression).
1996
Fred Drakeed514942001-07-06 17:28:39 +00001997Tuples have many uses. For example: (x, y) coordinate pairs, employee
1998records from a database, etc. Tuples, like strings, are immutable: it
1999is not possible to assign to the individual items of a tuple (you can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002000simulate much of the same effect with slicing and concatenation,
Fred Drake31b761e2000-09-29 15:17:36 +00002001though). It is also possible to create tuples which contain mutable
2002objects, such as lists.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002003
2004A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002005items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002006tuples are constructed by an empty pair of parentheses; a tuple with
2007one item is constructed by following a value with a comma
2008(it is not sufficient to enclose a single value in parentheses).
2009Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002010
Fred Drake8842e861998-02-13 07:16:30 +00002011\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002012>>> empty = ()
2013>>> singleton = 'hello', # <-- note trailing comma
2014>>> len(empty)
20150
2016>>> len(singleton)
20171
2018>>> singleton
2019('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00002020\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002021
Fred Drakeeee08cd1997-12-04 15:43:15 +00002022The statement \code{t = 12345, 54321, 'hello!'} is an example of
2023\emph{tuple packing}: the values \code{12345}, \code{54321} and
2024\code{'hello!'} are packed together in a tuple. The reverse operation
Fred Drakeed514942001-07-06 17:28:39 +00002025is also possible:
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>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00002029\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002030
Fred Drake31b761e2000-09-29 15:17:36 +00002031This is called, appropriately enough, \emph{sequence unpacking}.
2032Sequence unpacking requires that the list of variables on the left
2033have the same number of elements as the length of the sequence. Note
2034that multiple assignment is really just a combination of tuple packing
2035and sequence unpacking!
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002036
Fred Drake31b761e2000-09-29 15:17:36 +00002037There is a small bit of asymmetry here: packing multiple values
2038always creates a tuple, and unpacking works for any sequence.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002039
Guido van Rossumaee5e261998-08-07 17:45:09 +00002040% XXX Add a bit on the difference between tuples and lists.
Fred Drake31b761e2000-09-29 15:17:36 +00002041
Guido van Rossumaee5e261998-08-07 17:45:09 +00002042
Fred Drakeb7833d31998-09-11 16:21:55 +00002043\section{Dictionaries \label{dictionaries}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002044
Fred Drakeeee08cd1997-12-04 15:43:15 +00002045Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002046Dictionaries are sometimes found in other languages as ``associative
2047memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002048indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Fred Drakef1ad2071999-06-30 15:32:50 +00002049which can be any immutable type; strings and numbers can always be
Guido van Rossum02455691997-07-17 16:21:52 +00002050keys. Tuples can be used as keys if they contain only strings,
Fred Drake31b761e2000-09-29 15:17:36 +00002051numbers, or tuples; if a tuple contains any mutable object either
2052directly or indirectly, it cannot be used as a key. You can't use
2053lists as keys, since lists can be modified in place using their
2054\method{append()} and \method{extend()} methods, as well as slice and
2055indexed assignments.
Guido van Rossum02455691997-07-17 16:21:52 +00002056
Guido van Rossum6938f061994-08-01 12:22:53 +00002057It is best to think of a dictionary as an unordered set of
Fred Drake31b761e2000-09-29 15:17:36 +00002058\emph{key: value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002059(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00002060A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002061Placing a comma-separated list of key:value pairs within the
2062braces adds initial key:value pairs to the dictionary; this is also the
2063way dictionaries are written on output.
2064
2065The main operations on a dictionary are storing a value with some key
2066and extracting the value given the key. It is also possible to delete
2067a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00002068with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002069If you store using a key that is already in use, the old value
2070associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00002071value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002072
Fred Drake20082d92000-04-03 04:26:58 +00002073The \code{keys()} method of a dictionary object returns a list of all
2074the keys used in the dictionary, in random order (if you want it
2075sorted, just apply the \code{sort()} method to the list of keys). To
2076check whether a single key is in the dictionary, use the
2077\code{has_key()} method of the dictionary.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002078
2079Here is a small example using a dictionary:
2080
Fred Drake8842e861998-02-13 07:16:30 +00002081\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002082>>> tel = {'jack': 4098, 'sape': 4139}
2083>>> tel['guido'] = 4127
2084>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00002085{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002086>>> tel['jack']
20874098
2088>>> del tel['sape']
2089>>> tel['irv'] = 4127
2090>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00002091{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002092>>> tel.keys()
2093['guido', 'irv', 'jack']
2094>>> tel.has_key('guido')
Raymond Hettingera02469f2003-05-07 17:49:36 +00002095True
Fred Drake8842e861998-02-13 07:16:30 +00002096\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002097
Raymond Hettinger07dc9182002-06-25 15:13:18 +00002098The \function{dict()} contructor builds dictionaries directly from
2099lists of key-value pairs stored as tuples. When the pairs form a
2100pattern, list comprehensions can compactly specify the key-value list.
2101
2102\begin{verbatim}
2103>>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)])
2104{'sape': 4139, 'jack': 4098, 'guido': 4127}
2105>>> dict([(x, x**2) for x in vec]) # use a list comprehension
2106{2: 4, 4: 16, 6: 36}
2107\end{verbatim}
2108
Fred Drake38f71972002-04-26 20:29:44 +00002109
2110\section{Looping Techniques \label{loopidioms}}
2111
2112When looping through dictionaries, the key and corresponding value can
2113be retrieved at the same time using the \method{items()} method.
2114
2115\begin{verbatim}
2116>>> knights = {'gallahad': 'the pure', 'robin': 'the brave'}
2117>>> for k, v in knights.items():
2118... print k, v
2119...
2120gallahad the pure
2121robin the brave
2122\end{verbatim}
2123
2124When looping through a sequence, the position index and corresponding
2125value can be retrieved at the same time using the
2126\function{enumerate()} function.
2127
2128\begin{verbatim}
2129>>> for i, v in enumerate(['tic', 'tac', 'toe']):
2130... print i, v
2131...
21320 tic
21331 tac
21342 toe
2135\end{verbatim}
2136
2137To loop over two or more sequences at the same time, the entries
2138can be paired with the \function{zip()} function.
2139
2140\begin{verbatim}
2141>>> questions = ['name', 'quest', 'favorite color']
2142>>> answers = ['lancelot', 'the holy grail', 'blue']
2143>>> for q, a in zip(questions, answers):
2144... print 'What is your %s? It is %s.' % (q, a)
2145...
Raymond Hettinger7951f602002-06-25 03:17:03 +00002146What is your name? It is lancelot.
2147What is your quest? It is the holy grail.
2148What is your favorite color? It is blue.
Fred Drake38f71972002-04-26 20:29:44 +00002149\end{verbatim}
2150
2151
Fred Drakeb7833d31998-09-11 16:21:55 +00002152\section{More on Conditions \label{conditions}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002153
Fred Drakeeee08cd1997-12-04 15:43:15 +00002154The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002155contain other operators besides comparisons.
2156
Fred Drakeeee08cd1997-12-04 15:43:15 +00002157The comparison operators \code{in} and \code{not in} check whether a value
2158occurs (does not occur) in a sequence. The operators \code{is} and
2159\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002160only matters for mutable objects like lists. All comparison operators
2161have the same priority, which is lower than that of all numerical
2162operators.
2163
Fred Drakeed514942001-07-06 17:28:39 +00002164Comparisons can be chained. For example, \code{a < b == c} tests
2165whether \code{a} is less than \code{b} and moreover \code{b} equals
2166\code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002167
Fred Drakeeee08cd1997-12-04 15:43:15 +00002168Comparisons may be combined by the Boolean operators \code{and} and
2169\code{or}, and the outcome of a comparison (or of any other Boolean
2170expression) may be negated with \code{not}. These all have lower
2171priorities than comparison operators again; between them, \code{not} has
2172the highest priority, and \code{or} the lowest, so that
2173\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 +00002174course, parentheses can be used to express the desired composition.
2175
Fred Drakeeee08cd1997-12-04 15:43:15 +00002176The Boolean operators \code{and} and \code{or} are so-called
Fred Drake6cb64f92002-03-08 00:54:43 +00002177\emph{short-circuit} operators: their arguments are evaluated from
2178left to right, and evaluation stops as soon as the outcome is
2179determined. For example, if \code{A} and \code{C} are true but
2180\code{B} is false, \code{A and B and C} does not evaluate the
2181expression \code{C}. In general, the return value of a short-circuit
2182operator, when used as a general value and not as a Boolean, is the
2183last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002184
2185It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00002186expression to a variable. For example,
2187
Fred Drake8842e861998-02-13 07:16:30 +00002188\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00002189>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
2190>>> non_null = string1 or string2 or string3
2191>>> non_null
2192'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00002193\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002194
Fred Drakeee84d591999-03-10 17:25:30 +00002195Note that in Python, unlike C, assignment cannot occur inside expressions.
Fred Drake20082d92000-04-03 04:26:58 +00002196C programmers may grumble about this, but it avoids a common class of
2197problems encountered in C programs: typing \code{=} in an expression when
2198\code{==} was intended.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002199
Fred Drake31b761e2000-09-29 15:17:36 +00002200
Fred Drakeb7833d31998-09-11 16:21:55 +00002201\section{Comparing Sequences and Other Types \label{comparing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002202
2203Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00002204sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002205first the first two items are compared, and if they differ this
2206determines the outcome of the comparison; if they are equal, the next
2207two items are compared, and so on, until either sequence is exhausted.
2208If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00002209the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002210items of two sequences compare equal, the sequences are considered
Fred Drake979d0412001-04-03 17:41:56 +00002211equal. If one sequence is an initial sub-sequence of the other, the
Fred Drake20c94912001-08-01 17:17:13 +00002212shorter sequence is the smaller (lesser) one. Lexicographical
2213ordering for strings uses the \ASCII{} ordering for individual
2214characters. Some examples of comparisons between sequences with the
2215same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002216
Fred Drake8842e861998-02-13 07:16:30 +00002217\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002218(1, 2, 3) < (1, 2, 4)
2219[1, 2, 3] < [1, 2, 4]
2220'ABC' < 'C' < 'Pascal' < 'Python'
2221(1, 2, 3, 4) < (1, 2, 4)
2222(1, 2) < (1, 2, -1)
Fred Drake511281a1999-04-16 13:17:04 +00002223(1, 2, 3) == (1.0, 2.0, 3.0)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002224(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00002225\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002226
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002227Note that comparing objects of different types is legal. The outcome
2228is deterministic but arbitrary: the types are ordered by their name.
2229Thus, a list is always smaller than a string, a string is always
2230smaller than a tuple, etc. Mixed numeric types are compared according
Fred Drake93aa0f21999-04-05 21:39:17 +00002231to their numeric value, so 0 equals 0.0, etc.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002232 The rules for comparing objects of different types should
2233 not be relied upon; they may change in a future version of
2234 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002235}
2236
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002237
Fred Drakeb7833d31998-09-11 16:21:55 +00002238\chapter{Modules \label{modules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002239
Guido van Rossum4410c751991-06-04 20:22:18 +00002240If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002241definitions you have made (functions and variables) are lost.
2242Therefore, if you want to write a somewhat longer program, you are
2243better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00002244and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00002245\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002246into several files for easier maintenance. You may also want to use a
2247handy function that you've written in several programs without copying
2248its definition into each program.
2249
Guido van Rossum4410c751991-06-04 20:22:18 +00002250To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002251them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002252Such a file is called a \emph{module}; definitions from a module can be
2253\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002254collection of variables that you have access to in a script
2255executed at the top level
2256and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002257
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002258A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00002259file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00002260a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00002261the global variable \code{__name__}. For instance, use your favorite text
2262editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00002263with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002264
Fred Drake8842e861998-02-13 07:16:30 +00002265\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002266# Fibonacci numbers module
2267
2268def fib(n): # write Fibonacci series up to n
2269 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002270 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00002271 print b,
2272 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002273
2274def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002275 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002276 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002277 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00002278 result.append(b)
2279 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002280 return result
Fred Drake8842e861998-02-13 07:16:30 +00002281\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002282
Guido van Rossum4410c751991-06-04 20:22:18 +00002283Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002284following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002285
Fred Drake8842e861998-02-13 07:16:30 +00002286\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002287>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00002288\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002289
Fred Drakef1ad2071999-06-30 15:32:50 +00002290This does not enter the names of the functions defined in \code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002291directly in the current symbol table; it only enters the module name
Fred Drakef1ad2071999-06-30 15:32:50 +00002292\code{fibo} there.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002293Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002294
Fred Drake8842e861998-02-13 07:16:30 +00002295\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002296>>> fibo.fib(1000)
22971 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
2298>>> fibo.fib2(100)
2299[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00002300>>> fibo.__name__
2301'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00002302\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +00002303
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002304If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002305
Fred Drake8842e861998-02-13 07:16:30 +00002306\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002307>>> fib = fibo.fib
2308>>> fib(500)
23091 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00002310\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002311
Guido van Rossum02455691997-07-17 16:21:52 +00002312
Fred Drakeb7833d31998-09-11 16:21:55 +00002313\section{More on Modules \label{moreModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002314
2315A module can contain executable statements as well as function
Fred Drake20082d92000-04-03 04:26:58 +00002316definitions.
2317These statements are intended to initialize the module.
2318They are executed only the
2319\emph{first} time the module is imported somewhere.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002320 In fact function definitions are also `statements' that are
2321 `executed'; the execution enters the function name in the
2322 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002323}
2324
2325Each module has its own private symbol table, which is used as the
2326global symbol table by all functions defined in the module.
2327Thus, the author of a module can use global variables in the module
2328without worrying about accidental clashes with a user's global
2329variables.
2330On the other hand, if you know what you are doing you can touch a
2331module's global variables with the same notation used to refer to its
2332functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00002333\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002334
Fred Drake20082d92000-04-03 04:26:58 +00002335Modules can import other modules. It is customary but not required to
2336place all \keyword{import} statements at the beginning of a module (or
2337script, for that matter). The imported module names are placed in the
2338importing module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002339
Fred Drake20082d92000-04-03 04:26:58 +00002340There is a variant of the \keyword{import} statement that imports
2341names from a module directly into the importing module's symbol
2342table. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002343
Fred Drake8842e861998-02-13 07:16:30 +00002344\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002345>>> from fibo import fib, fib2
2346>>> fib(500)
23471 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00002348\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002349
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002350This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00002351in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002352defined).
2353
2354There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002355
Fred Drake8842e861998-02-13 07:16:30 +00002356\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002357>>> from fibo import *
2358>>> fib(500)
23591 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00002360\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002361
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002362This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00002363(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002364
Guido van Rossum02455691997-07-17 16:21:52 +00002365
Fred Drake31b761e2000-09-29 15:17:36 +00002366\subsection{The Module Search Path \label{searchPath}}
Guido van Rossumaee5e261998-08-07 17:45:09 +00002367
Fred Drake391564f1998-04-01 23:11:56 +00002368\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00002369When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00002370for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00002371and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00002372the environment variable \envvar{PYTHONPATH}. This has the same syntax as
Fred Drakeed514942001-07-06 17:28:39 +00002373the shell variable \envvar{PATH}, that is, a list of
Fred Drake391564f1998-04-01 23:11:56 +00002374directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00002375is not found there, the search continues in an installation-dependent
Fred Drakec37b65e2001-11-28 07:26:15 +00002376default path; on \UNIX, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00002377
2378Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002379variable \code{sys.path} which is initialized from the directory
2380containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00002381\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00002382Python programs that know what they're doing to modify or replace the
Fred Drakeecd81572001-12-04 19:47:46 +00002383module search path. Note that because the directory containing the
2384script being run is on the search path, it is important that the
2385script not have the same name as a standard module, or Python will
2386attempt to load the script as a module when that module is imported.
2387This will generally be an error. See section~\ref{standardModules},
2388``Standard Modules.'' for more information.
2389
Guido van Rossum02455691997-07-17 16:21:52 +00002390
2391\subsection{``Compiled'' Python files}
2392
2393As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00002394use a lot of standard modules, if a file called \file{spam.pyc} exists
2395in the directory where \file{spam.py} is found, this is assumed to
Guido van Rossum13c8ef61998-05-29 19:12:23 +00002396contain an already-``byte-compiled'' version of the module \module{spam}.
Fred Drake8842e861998-02-13 07:16:30 +00002397The modification time of the version of \file{spam.py} used to create
Fred Drake20082d92000-04-03 04:26:58 +00002398\file{spam.pyc} is recorded in \file{spam.pyc}, and the
2399\file{.pyc} file is ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00002400
Fred Drake20082d92000-04-03 04:26:58 +00002401Normally, you don't need to do anything to create the
2402\file{spam.pyc} file. Whenever \file{spam.py} is successfully
2403compiled, an attempt is made to write the compiled version to
2404\file{spam.pyc}. It is not an error if this attempt fails; if for any
2405reason the file is not written completely, the resulting
2406\file{spam.pyc} file will be recognized as invalid and thus ignored
2407later. The contents of the \file{spam.pyc} file are platform
2408independent, so a Python module directory can be shared by machines of
2409different architectures.
Guido van Rossum02455691997-07-17 16:21:52 +00002410
Guido van Rossum13c8ef61998-05-29 19:12:23 +00002411Some tips for experts:
2412
2413\begin{itemize}
2414
2415\item
Fred Drake37f15741999-11-10 16:21:37 +00002416When the Python interpreter is invoked with the \programopt{-O} flag,
Michael W. Hudsondd32a912002-08-15 14:59:02 +00002417optimized code is generated and stored in \file{.pyo} files. The
2418optimizer currently doesn't help much; it only removes
2419\keyword{assert} statements. When \programopt{-O} is used, \emph{all}
2420bytecode is optimized; \code{.pyc} files are ignored and \code{.py}
2421files are compiled to optimized bytecode.
Guido van Rossum13c8ef61998-05-29 19:12:23 +00002422
2423\item
Fred Drake37f15741999-11-10 16:21:37 +00002424Passing two \programopt{-O} flags to the Python interpreter
2425(\programopt{-OO}) will cause the bytecode compiler to perform
2426optimizations that could in some rare cases result in malfunctioning
2427programs. Currently only \code{__doc__} strings are removed from the
2428bytecode, resulting in more compact \file{.pyo} files. Since some
2429programs may rely on having these available, you should only use this
2430option if you know what you're doing.
Guido van Rossum6b86a421999-01-28 15:07:47 +00002431
2432\item
Fred Drake20082d92000-04-03 04:26:58 +00002433A program doesn't run any faster when it is read from a \file{.pyc} or
2434\file{.pyo} file than when it is read from a \file{.py} file; the only
2435thing that's faster about \file{.pyc} or \file{.pyo} files is the
2436speed with which they are loaded.
Guido van Rossum13c8ef61998-05-29 19:12:23 +00002437
2438\item
Guido van Rossum002f7aa1998-06-28 19:16:38 +00002439When a script is run by giving its name on the command line, the
2440bytecode for the script is never written to a \file{.pyc} or
2441\file{.pyo} file. Thus, the startup time of a script may be reduced
2442by moving most of its code to a module and having a small bootstrap
Fred Drake31b761e2000-09-29 15:17:36 +00002443script that imports that module. It is also possible to name a
2444\file{.pyc} or \file{.pyo} file directly on the command line.
Guido van Rossum002f7aa1998-06-28 19:16:38 +00002445
2446\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00002447It is possible to have a file called \file{spam.pyc} (or
Fred Drake31b761e2000-09-29 15:17:36 +00002448\file{spam.pyo} when \programopt{-O} is used) without a file
2449\file{spam.py} for the same module. This can be used to distribute a
2450library of Python code in a form that is moderately hard to reverse
Guido van Rossum13c8ef61998-05-29 19:12:23 +00002451engineer.
2452
2453\item
2454The module \module{compileall}\refstmodindex{compileall} can create
Fred Drake37f15741999-11-10 16:21:37 +00002455\file{.pyc} files (or \file{.pyo} files when \programopt{-O} is used) for
Guido van Rossum13c8ef61998-05-29 19:12:23 +00002456all modules in a directory.
2457
2458\end{itemize}
2459
Guido van Rossum02455691997-07-17 16:21:52 +00002460
Fred Drakeb7833d31998-09-11 16:21:55 +00002461\section{Standard Modules \label{standardModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002462
Guido van Rossum4410c751991-06-04 20:22:18 +00002463Python comes with a library of standard modules, described in a separate
Fred Drake37f15741999-11-10 16:21:37 +00002464document, the \citetitle[../lib/lib.html]{Python Library Reference}
2465(``Library Reference'' hereafter). Some modules are built into the
2466interpreter; these provide access to operations that are not part of
2467the core of the language but are nevertheless built in, either for
2468efficiency or to provide access to operating system primitives such as
Fred Drakeed514942001-07-06 17:28:39 +00002469system calls. The set of such modules is a configuration option which
2470also dependson the underlying platform For example,
Fred Drake37f15741999-11-10 16:21:37 +00002471the \module{amoeba} module is only provided on systems that somehow
Fred Drake8842e861998-02-13 07:16:30 +00002472support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00002473attention: \module{sys}\refstmodindex{sys}, which is built into every
Fred Drakeee84d591999-03-10 17:25:30 +00002474Python interpreter. The variables \code{sys.ps1} and
2475\code{sys.ps2} define the strings used as primary and secondary
2476prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002477
Fred Drake8842e861998-02-13 07:16:30 +00002478\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002479>>> import sys
2480>>> sys.ps1
2481'>>> '
2482>>> sys.ps2
2483'... '
2484>>> sys.ps1 = 'C> '
2485C> print 'Yuck!'
2486Yuck!
Raymond Hettingera02469f2003-05-07 17:49:36 +00002487C>
2488
Fred Drake8842e861998-02-13 07:16:30 +00002489\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002490
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002491These two variables are only defined if the interpreter is in
2492interactive mode.
2493
Fred Drakeee84d591999-03-10 17:25:30 +00002494The variable \code{sys.path} is a list of strings that determine the
2495interpreter's search path for modules. It is initialized to a default
2496path taken from the environment variable \envvar{PYTHONPATH}, or from
2497a built-in default if \envvar{PYTHONPATH} is not set. You can modify
Fred Drakeed514942001-07-06 17:28:39 +00002498it using standard list operations:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002499
Fred Drake8842e861998-02-13 07:16:30 +00002500\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002501>>> import sys
2502>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00002503\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002504
Fred Drakeb7833d31998-09-11 16:21:55 +00002505\section{The \function{dir()} Function \label{dir}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002506
Fred Drake8842e861998-02-13 07:16:30 +00002507The built-in function \function{dir()} is used to find out which names
2508a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002509
Fred Drake8842e861998-02-13 07:16:30 +00002510\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002511>>> import fibo, sys
2512>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00002513['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002514>>> dir(sys)
Fred Drakeecd81572001-12-04 19:47:46 +00002515['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__',
Guido van Rossum46d3dc32003-03-01 03:20:41 +00002516 '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv',
2517 'builtin_module_names', 'byteorder', 'callstats', 'copyright',
2518 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook',
2519 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags',
2520 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode',
2521 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache',
2522 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags',
2523 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout',
2524 'version', 'version_info', 'warnoptions']
Fred Drake8842e861998-02-13 07:16:30 +00002525\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002526
Fred Drake8842e861998-02-13 07:16:30 +00002527Without arguments, \function{dir()} lists the names you have defined
2528currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002529
Fred Drake8842e861998-02-13 07:16:30 +00002530\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002531>>> a = [1, 2, 3, 4, 5]
2532>>> import fibo, sys
2533>>> fib = fibo.fib
2534>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00002535['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00002536\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002537
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002538Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002539
Fred Drake8842e861998-02-13 07:16:30 +00002540\function{dir()} does not list the names of built-in functions and
2541variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00002542standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002543
Fred Drake8842e861998-02-13 07:16:30 +00002544\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00002545>>> import __builtin__
2546>>> dir(__builtin__)
Fred Drakeecd81572001-12-04 19:47:46 +00002547['ArithmeticError', 'AssertionError', 'AttributeError',
2548 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError',
Neal Norwitzd68f5172002-05-29 15:54:55 +00002549 'Exception', 'False', 'FloatingPointError', 'IOError', 'ImportError',
Fred Drakeecd81572001-12-04 19:47:46 +00002550 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2551 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented',
2552 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning',
Neal Norwitzd68f5172002-05-29 15:54:55 +00002553 'PendingDeprecationWarning', 'ReferenceError',
2554 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration',
2555 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError',
2556 'True', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning',
2557 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__',
2558 '__import__', '__name__', 'abs', 'apply', 'bool', 'buffer',
2559 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex',
2560 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod',
2561 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float',
2562 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id',
2563 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter',
2564 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min',
2565 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit',
2566 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round',
Alex Martellia70b1912003-04-22 08:12:33 +00002567 'setattr', 'slice', 'staticmethod', 'str', 'string', 'sum', 'super',
Neal Norwitzd68f5172002-05-29 15:54:55 +00002568 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip']
Fred Drake8842e861998-02-13 07:16:30 +00002569\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002570
Fred Drake31b761e2000-09-29 15:17:36 +00002571
Fred Drakeb7833d31998-09-11 16:21:55 +00002572\section{Packages \label{packages}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002573
2574Packages are a way of structuring Python's module namespace
Fred Drakeb7833d31998-09-11 16:21:55 +00002575by using ``dotted module names''. For example, the module name
2576\module{A.B} designates a submodule named \samp{B} in a package named
2577\samp{A}. Just like the use of modules saves the authors of different
2578modules from having to worry about each other's global variable names,
2579the use of dotted module names saves the authors of multi-module
Fred Drake20082d92000-04-03 04:26:58 +00002580packages like NumPy or the Python Imaging Library from having to worry
2581about each other's module names.
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002582
2583Suppose you want to design a collection of modules (a ``package'') for
2584the uniform handling of sound files and sound data. There are many
2585different sound file formats (usually recognized by their extension,
Fred Drakeed514942001-07-06 17:28:39 +00002586for example: \file{.wav}, \file{.aiff}, \file{.au}), so you may need
2587to create and maintain a growing collection of modules for the
2588conversion between the various file formats. There are also many
2589different operations you might want to perform on sound data (such as
2590mixing, adding echo, applying an equalizer function, creating an
2591artificial stereo effect), so in addition you will be writing a
2592never-ending stream of modules to perform these operations. Here's a
2593possible structure for your package (expressed in terms of a
2594hierarchical filesystem):
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002595
2596\begin{verbatim}
2597Sound/ Top-level package
2598 __init__.py Initialize the sound package
2599 Formats/ Subpackage for file format conversions
2600 __init__.py
2601 wavread.py
2602 wavwrite.py
2603 aiffread.py
2604 aiffwrite.py
2605 auread.py
2606 auwrite.py
2607 ...
2608 Effects/ Subpackage for sound effects
2609 __init__.py
2610 echo.py
2611 surround.py
2612 reverse.py
2613 ...
2614 Filters/ Subpackage for filters
2615 __init__.py
2616 equalizer.py
2617 vocoder.py
2618 karaoke.py
2619 ...
2620\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +00002621
Raymond Hettinger7fbd0122002-10-26 03:13:57 +00002622When importing the package, Python searchs through the directories
2623on \code{sys.path} looking for the package subdirectory.
2624
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002625The \file{__init__.py} files are required to make Python treat the
2626directories as containing packages; this is done to prevent
2627directories with a common name, such as \samp{string}, from
2628unintentionally hiding valid modules that occur later on the module
2629search path. In the simplest case, \file{__init__.py} can just be an
2630empty file, but it can also execute initialization code for the
2631package or set the \code{__all__} variable, described later.
2632
2633Users of the package can import individual modules from the
2634package, for example:
2635
2636\begin{verbatim}
2637import Sound.Effects.echo
2638\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +00002639
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002640This loads the submodule \module{Sound.Effects.echo}. It must be referenced
Fred Drakeed514942001-07-06 17:28:39 +00002641with its full name.
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002642
2643\begin{verbatim}
2644Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
2645\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +00002646
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002647An alternative way of importing the submodule is:
2648
2649\begin{verbatim}
2650from Sound.Effects import echo
2651\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +00002652
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002653This also loads the submodule \module{echo}, and makes it available without
2654its package prefix, so it can be used as follows:
2655
2656\begin{verbatim}
2657echo.echofilter(input, output, delay=0.7, atten=4)
2658\end{verbatim}
2659
2660Yet another variation is to import the desired function or variable directly:
2661
2662\begin{verbatim}
2663from Sound.Effects.echo import echofilter
2664\end{verbatim}
2665
2666Again, this loads the submodule \module{echo}, but this makes its function
Fred Drake20082d92000-04-03 04:26:58 +00002667\function{echofilter()} directly available:
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002668
2669\begin{verbatim}
2670echofilter(input, output, delay=0.7, atten=4)
2671\end{verbatim}
2672
2673Note that when using \code{from \var{package} import \var{item}}, the
Fred Drake20082d92000-04-03 04:26:58 +00002674item can be either a submodule (or subpackage) of the package, or some
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002675other name defined in the package, like a function, class or
2676variable. The \code{import} statement first tests whether the item is
2677defined in the package; if not, it assumes it is a module and attempts
Fred Drake20082d92000-04-03 04:26:58 +00002678to load it. If it fails to find it, an
2679\exception{ImportError} exception is raised.
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002680
2681Contrarily, when using syntax like \code{import
2682\var{item.subitem.subsubitem}}, each item except for the last must be
2683a package; the last item can be a module or a package but can't be a
2684class or function or variable defined in the previous item.
2685
Fred Drakeb7833d31998-09-11 16:21:55 +00002686\subsection{Importing * From a Package \label{pkg-import-star}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002687%The \code{__all__} Attribute
2688
2689Now what happens when the user writes \code{from Sound.Effects import
2690*}? Ideally, one would hope that this somehow goes out to the
2691filesystem, finds which submodules are present in the package, and
2692imports them all. Unfortunately, this operation does not work very
2693well on Mac and Windows platforms, where the filesystem does not
2694always have accurate information about the case of a filename! On
2695these platforms, there is no guaranteed way to know whether a file
2696\file{ECHO.PY} should be imported as a module \module{echo},
2697\module{Echo} or \module{ECHO}. (For example, Windows 95 has the
2698annoying practice of showing all file names with a capitalized first
2699letter.) The DOS 8+3 filename restriction adds another interesting
2700problem for long module names.
2701
2702The only solution is for the package author to provide an explicit
2703index of the package. The import statement uses the following
Fred Drake20082d92000-04-03 04:26:58 +00002704convention: if a package's \file{__init__.py} code defines a list
2705named \code{__all__}, it is taken to be the list of module names that
2706should be imported when \code{from \var{package} import *} is
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002707encountered. It is up to the package author to keep this list
2708up-to-date when a new version of the package is released. Package
2709authors may also decide not to support it, if they don't see a use for
2710importing * from their package. For example, the file
Fred Drake20082d92000-04-03 04:26:58 +00002711\file{Sounds/Effects/__init__.py} could contain the following code:
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002712
2713\begin{verbatim}
2714__all__ = ["echo", "surround", "reverse"]
2715\end{verbatim}
2716
2717This would mean that \code{from Sound.Effects import *} would
2718import the three named submodules of the \module{Sound} package.
2719
2720If \code{__all__} is not defined, the statement \code{from Sound.Effects
2721import *} does \emph{not} import all submodules from the package
2722\module{Sound.Effects} into the current namespace; it only ensures that the
2723package \module{Sound.Effects} has been imported (possibly running its
2724initialization code, \file{__init__.py}) and then imports whatever names are
2725defined in the package. This includes any names defined (and
2726submodules explicitly loaded) by \file{__init__.py}. It also includes any
2727submodules of the package that were explicitly loaded by previous
Fred Drakeed514942001-07-06 17:28:39 +00002728import statements. Consider this code:
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002729
2730\begin{verbatim}
2731import Sound.Effects.echo
2732import Sound.Effects.surround
2733from Sound.Effects import *
2734\end{verbatim}
2735
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002736In this example, the echo and surround modules are imported in the
Fred Drake20082d92000-04-03 04:26:58 +00002737current namespace because they are defined in the
2738\module{Sound.Effects} package when the \code{from...import} statement
2739is executed. (This also works when \code{__all__} is defined.)
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002740
Fred Drake55803bc2002-10-22 21:00:44 +00002741Note that in general the practice of importing \code{*} from a module or
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002742package is frowned upon, since it often causes poorly readable code.
2743However, it is okay to use it to save typing in interactive sessions,
2744and certain modules are designed to export only names that follow
2745certain patterns.
2746
2747Remember, there is nothing wrong with using \code{from Package
2748import specific_submodule}! In fact, this is the
2749recommended notation unless the importing module needs to use
2750submodules with the same name from different packages.
2751
2752
2753\subsection{Intra-package References}
2754
2755The submodules often need to refer to each other. For example, the
2756\module{surround} module might use the \module{echo} module. In fact, such references
2757are so common that the \code{import} statement first looks in the
2758containing package before looking in the standard module search path.
2759Thus, the surround module can simply use \code{import echo} or
2760\code{from echo import echofilter}. If the imported module is not
2761found in the current package (the package of which the current module
2762is a submodule), the \code{import} statement looks for a top-level module
2763with the given name.
2764
Fred Drake20082d92000-04-03 04:26:58 +00002765When packages are structured into subpackages (as with the
2766\module{Sound} package in the example), there's no shortcut to refer
2767to submodules of sibling packages - the full name of the subpackage
2768must be used. For example, if the module
2769\module{Sound.Filters.vocoder} needs to use the \module{echo} module
2770in the \module{Sound.Effects} package, it can use \code{from
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002771Sound.Effects import echo}.
2772
2773%(One could design a notation to refer to parent packages, similar to
Fred Drakec37b65e2001-11-28 07:26:15 +00002774%the use of ".." to refer to the parent directory in \UNIX{} and Windows
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002775%filesystems. In fact, the \module{ni} module, which was the
2776%ancestor of this package system, supported this using \code{__} for
2777%the package containing the current module,
2778%\code{__.__} for the parent package, and so on. This feature was dropped
2779%because of its awkwardness; since most packages will have a relative
2780%shallow substructure, this is no big loss.)
2781
Fred Drake55803bc2002-10-22 21:00:44 +00002782\subsection{Packages in Multiple Directories}
2783
2784Packages support one more special attribute, \member{__path__}. This
2785is initialized to be a list containing the name of the directory
2786holding the package's \file{__init__.py} before the code in that file
2787is executed. This variable can be modified; doing so affects future
2788searches for modules and subpackages contained in the package.
2789
2790While this feature is not often needed, it can be used to extend the
2791set of modules found in a package.
2792
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002793
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002794
Fred Drakeb7833d31998-09-11 16:21:55 +00002795\chapter{Input and Output \label{io}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002796
Guido van Rossum02455691997-07-17 16:21:52 +00002797There are several ways to present the output of a program; data can be
2798printed in a human-readable form, or written to a file for future use.
2799This chapter will discuss some of the possibilities.
2800
Fred Drakeb7833d31998-09-11 16:21:55 +00002801
2802\section{Fancier Output Formatting \label{formatting}}
2803
Fred Drakeeee08cd1997-12-04 15:43:15 +00002804So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00002805statements} and the \keyword{print} statement. (A third way is using
2806the \method{write()} method of file objects; the standard output file
2807can be referenced as \code{sys.stdout}. See the Library Reference for
2808more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002809
2810Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00002811simply printing space-separated values. There are two ways to format
2812your output; the first way is to do all the string handling yourself;
2813using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00002814lay-out you can imagine. The standard module
2815\module{string}\refstmodindex{string} contains some useful operations
Fred Drake20082d92000-04-03 04:26:58 +00002816for padding strings to a given column width; these will be discussed
2817shortly. The second way is to use the \code{\%} operator with a
2818string as the left argument. The \code{\%} operator interprets the
Fred Drakecc97f8c2001-01-01 20:33:06 +00002819left argument much like a \cfunction{sprintf()}-style format
Fred Drake20082d92000-04-03 04:26:58 +00002820string to be applied to the right argument, and returns the string
2821resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002822
2823One question remains, of course: how do you convert values to strings?
Fred Drake6016dbe2001-12-04 19:20:43 +00002824Luckily, Python has ways to convert any value to a string: pass it to
Skip Montanarob4f12422003-05-07 15:29:12 +00002825the \function{repr()} or \function{str()} functions. Reverse quotes
2826(\code{``}) are equivalent to \function{repr()}, but their use is
2827discouraged.
Fred Drake6016dbe2001-12-04 19:20:43 +00002828
2829The \function{str()} function is meant to return representations of
2830values which are fairly human-readable, while \function{repr()} is
2831meant to generate representations which can be read by the interpreter
2832(or will force a \exception{SyntaxError} if there is not equivalent
2833syntax). For objects which don't have a particular representation for
2834human consumption, \function{str()} will return the same value as
2835\function{repr()}. Many values, such as numbers or structures like
2836lists and dictionaries, have the same representation using either
2837function. Strings and floating point numbers, in particular, have two
2838distinct representations.
2839
2840Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002841
Fred Drake8842e861998-02-13 07:16:30 +00002842\begin{verbatim}
Fred Drake6016dbe2001-12-04 19:20:43 +00002843>>> s = 'Hello, world.'
2844>>> str(s)
2845'Hello, world.'
Skip Montanarob4f12422003-05-07 15:29:12 +00002846>>> repr(s)
Fred Drake6016dbe2001-12-04 19:20:43 +00002847"'Hello, world.'"
2848>>> str(0.1)
2849'0.1'
Skip Montanarob4f12422003-05-07 15:29:12 +00002850>>> repr(0.1)
Fred Drake6016dbe2001-12-04 19:20:43 +00002851'0.10000000000000001'
Tim Petersbd695a72001-05-22 06:54:14 +00002852>>> x = 10 * 3.25
Fred Drake8b0b8402001-05-21 16:55:39 +00002853>>> y = 200 * 200
Skip Montanarob4f12422003-05-07 15:29:12 +00002854>>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002855>>> print s
Tim Petersbd695a72001-05-22 06:54:14 +00002856The value of x is 32.5, and y is 40000...
Skip Montanarob4f12422003-05-07 15:29:12 +00002857>>> # The repr() of a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00002858... hello = 'hello, world\n'
Skip Montanarob4f12422003-05-07 15:29:12 +00002859>>> hellos = repr(hello)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002860>>> print hellos
Fred Drake0c149612001-04-12 04:26:24 +00002861'hello, world\n'
Skip Montanarob4f12422003-05-07 15:29:12 +00002862>>> # The argument to repr() may be any Python object:
Skip Montanaro45a9c932003-05-07 16:01:43 +00002863... repr((x, y, ('spam', 'eggs')))
Skip Montanarob4f12422003-05-07 15:29:12 +00002864"(32.5, 40000, ('spam', 'eggs'))"
2865>>> # reverse quotes are convenient in interactive sessions:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002866... `x, y, ('spam', 'eggs')`
Tim Petersbd695a72001-05-22 06:54:14 +00002867"(32.5, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00002868\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002869
Guido van Rossum6938f061994-08-01 12:22:53 +00002870Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002871
Fred Drake8842e861998-02-13 07:16:30 +00002872\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002873>>> import string
2874>>> for x in range(1, 11):
Skip Montanarob4f12422003-05-07 15:29:12 +00002875... print string.rjust(repr(x), 2), string.rjust(repr(x*x), 3),
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002876... # Note trailing comma on previous line
Skip Montanarob4f12422003-05-07 15:29:12 +00002877... print string.rjust(repr(x*x*x), 4)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002878...
2879 1 1 1
2880 2 4 8
2881 3 9 27
2882 4 16 64
2883 5 25 125
2884 6 36 216
2885 7 49 343
2886 8 64 512
2887 9 81 729
288810 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002889>>> for x in range(1,11):
2890... print '%2d %3d %4d' % (x, x*x, x*x*x)
2891...
2892 1 1 1
2893 2 4 8
2894 3 9 27
2895 4 16 64
2896 5 25 125
2897 6 36 216
2898 7 49 343
2899 8 64 512
2900 9 81 729
290110 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002902\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002903
Fred Drake8842e861998-02-13 07:16:30 +00002904(Note that one space between each column was added by the way
2905\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002906
Fred Drake8842e861998-02-13 07:16:30 +00002907This example demonstrates the function \function{string.rjust()},
2908which right-justifies a string in a field of a given width by padding
2909it with spaces on the left. There are similar functions
2910\function{string.ljust()} and \function{string.center()}. These
2911functions do not write anything, they just return a new string. If
2912the input string is too long, they don't truncate it, but return it
2913unchanged; this will mess up your column lay-out but that's usually
2914better than the alternative, which would be lying about a value. (If
2915you really want truncation you can always add a slice operation, as in
2916\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002917
Fred Drake8842e861998-02-13 07:16:30 +00002918There is another function, \function{string.zfill()}, which pads a
2919numeric string on the left with zeros. It understands about plus and
2920minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002921
Fred Drake8842e861998-02-13 07:16:30 +00002922\begin{verbatim}
Fred Drake0ba58151999-09-14 18:00:49 +00002923>>> import string
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002924>>> string.zfill('12', 5)
2925'00012'
2926>>> string.zfill('-3.14', 7)
2927'-003.14'
2928>>> string.zfill('3.14159265359', 5)
2929'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002930\end{verbatim}
Fred Drake31b761e2000-09-29 15:17:36 +00002931
Guido van Rossum02455691997-07-17 16:21:52 +00002932Using the \code{\%} operator looks like this:
2933
2934\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002935>>> import math
2936>>> print 'The value of PI is approximately %5.3f.' % math.pi
2937The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002938\end{verbatim}
2939
Fred Drakeed514942001-07-06 17:28:39 +00002940If there is more than one format in the string, you need to pass a
2941tuple as right operand, as in this example:
Guido van Rossum02455691997-07-17 16:21:52 +00002942
2943\begin{verbatim}
Fred Drake20082d92000-04-03 04:26:58 +00002944>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678}
Fred Drake8842e861998-02-13 07:16:30 +00002945>>> for name, phone in table.items():
2946... print '%-10s ==> %10d' % (name, phone)
2947...
2948Jack ==> 4098
Fred Drake69fbf332000-04-04 19:53:06 +00002949Dcab ==> 7678
Fred Drake8842e861998-02-13 07:16:30 +00002950Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002951\end{verbatim}
2952
Fred Drakeee84d591999-03-10 17:25:30 +00002953Most formats work exactly as in C and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002954type; however, if you don't you get an exception, not a core dump.
Fred Drakedb70d061998-11-17 21:59:04 +00002955The \code{\%s} format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002956not a string object, it is converted to string using the
2957\function{str()} built-in function. Using \code{*} to pass the width
2958or precision in as a separate (integer) argument is supported. The
Fred Drakeee84d591999-03-10 17:25:30 +00002959C formats \code{\%n} and \code{\%p} are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002960
2961If you have a really long format string that you don't want to split
2962up, it would be nice if you could reference the variables to be
2963formatted by name instead of by position. This can be done by using
Fred Drakeed514942001-07-06 17:28:39 +00002964form \code{\%(name)format}, as shown here:
Guido van Rossum02455691997-07-17 16:21:52 +00002965
2966\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002967>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2968>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2969Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002970\end{verbatim}
2971
2972This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002973\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002974local variables.
2975
Fred Drakeb7833d31998-09-11 16:21:55 +00002976\section{Reading and Writing Files \label{files}}
Fred Drake6c2176e1998-02-26 21:47:54 +00002977
Guido van Rossum02455691997-07-17 16:21:52 +00002978% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002979\function{open()}\bifuncindex{open} returns a file
2980object\obindex{file}, and is most commonly used with two arguments:
2981\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002982
Fred Drake8842e861998-02-13 07:16:30 +00002983\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002984>>> f=open('/tmp/workfile', 'w')
2985>>> print f
2986<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002987\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002988
Guido van Rossum02455691997-07-17 16:21:52 +00002989The first argument is a string containing the filename. The second
2990argument is another string containing a few characters describing the
2991way in which the file will be used. \var{mode} can be \code{'r'} when
2992the file will only be read, \code{'w'} for only writing (an existing
2993file with the same name will be erased), and \code{'a'} opens the file
2994for appending; any data written to the file is automatically added to
2995the end. \code{'r+'} opens the file for both reading and writing.
2996The \var{mode} argument is optional; \code{'r'} will be assumed if
2997it's omitted.
2998
Fred Drake391564f1998-04-01 23:11:56 +00002999On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00003000mode opens the file in binary mode, so there are also modes like
3001\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
3002distinction between text and binary files; the end-of-line characters
3003in text files are automatically altered slightly when data is read or
3004written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00003005\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
3006\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00003007writing such files. (Note that the precise semantics of text mode on
Fred Drakeee84d591999-03-10 17:25:30 +00003008the Macintosh depends on the underlying C library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00003009
Fred Drakeb7833d31998-09-11 16:21:55 +00003010\subsection{Methods of File Objects \label{fileMethods}}
Guido van Rossum02455691997-07-17 16:21:52 +00003011
3012The rest of the examples in this section will assume that a file
3013object called \code{f} has already been created.
3014
3015To read a file's contents, call \code{f.read(\var{size})}, which reads
3016some quantity of data and returns it as a string. \var{size} is an
3017optional numeric argument. When \var{size} is omitted or negative,
3018the entire contents of the file will be read and returned; it's your
3019problem if the file is twice as large as your machine's memory.
3020Otherwise, at most \var{size} bytes are read and returned. If the end
3021of the file has been reached, \code{f.read()} will return an empty
3022string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00003023\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003024>>> f.read()
Fred Drake0c149612001-04-12 04:26:24 +00003025'This is the entire file.\n'
Guido van Rossum02455691997-07-17 16:21:52 +00003026>>> f.read()
3027''
Fred Drake8842e861998-02-13 07:16:30 +00003028\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003029
Guido van Rossum02455691997-07-17 16:21:52 +00003030\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00003031character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00003032omitted on the last line of the file if the file doesn't end in a
3033newline. This makes the return value unambiguous; if
3034\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00003035been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00003036string containing only a single newline.
3037
Fred Drake8842e861998-02-13 07:16:30 +00003038\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003039>>> f.readline()
Fred Drake0c149612001-04-12 04:26:24 +00003040'This is the first line of the file.\n'
Guido van Rossum02455691997-07-17 16:21:52 +00003041>>> f.readline()
Fred Drake0c149612001-04-12 04:26:24 +00003042'Second line of the file\n'
Guido van Rossum02455691997-07-17 16:21:52 +00003043>>> f.readline()
3044''
Fred Drake8842e861998-02-13 07:16:30 +00003045\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003046
Fred Drake343ad7a2000-09-22 04:12:27 +00003047\code{f.readlines()} returns a list containing all the lines of data
3048in the file. If given an optional parameter \var{sizehint}, it reads
3049that many bytes from the file and enough more to complete a line, and
3050returns the lines from that. This is often used to allow efficient
3051reading of a large file by lines, but without having to load the
3052entire file in memory. Only complete lines will be returned.
Guido van Rossum02455691997-07-17 16:21:52 +00003053
Fred Drake8842e861998-02-13 07:16:30 +00003054\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003055>>> f.readlines()
Fred Drake0c149612001-04-12 04:26:24 +00003056['This is the first line of the file.\n', 'Second line of the file\n']
Fred Drake8842e861998-02-13 07:16:30 +00003057\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003058
Guido van Rossum02455691997-07-17 16:21:52 +00003059\code{f.write(\var{string})} writes the contents of \var{string} to
3060the file, returning \code{None}.
3061
Fred Drake8842e861998-02-13 07:16:30 +00003062\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003063>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00003064\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003065
Guido van Rossum02455691997-07-17 16:21:52 +00003066\code{f.tell()} returns an integer giving the file object's current
3067position in the file, measured in bytes from the beginning of the
3068file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00003069\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00003070computed from adding \var{offset} to a reference point; the reference
Fred Drake20082d92000-04-03 04:26:58 +00003071point is selected by the \var{from_what} argument. A
3072\var{from_what} value of 0 measures from the beginning of the file, 1
3073uses the current file position, and 2 uses the end of the file as the
3074reference point. \var{from_what} can be omitted and defaults to 0,
3075using the beginning of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00003076
Fred Drake8842e861998-02-13 07:16:30 +00003077\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003078>>> f=open('/tmp/workfile', 'r+')
3079>>> f.write('0123456789abcdef')
Fred Drakea8159162001-10-16 03:25:00 +00003080>>> f.seek(5) # Go to the 6th byte in the file
Guido van Rossum02455691997-07-17 16:21:52 +00003081>>> f.read(1)
3082'5'
3083>>> f.seek(-3, 2) # Go to the 3rd byte before the end
3084>>> f.read(1)
3085'd'
Fred Drake8842e861998-02-13 07:16:30 +00003086\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003087
Guido van Rossum02455691997-07-17 16:21:52 +00003088When you're done with a file, call \code{f.close()} to close it and
3089free up any system resources taken up by the open file. After calling
3090\code{f.close()}, attempts to use the file object will automatically fail.
3091
Fred Drake8842e861998-02-13 07:16:30 +00003092\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003093>>> f.close()
3094>>> f.read()
Fred Drake162c6a62001-02-14 03:20:18 +00003095Traceback (most recent call last):
Guido van Rossum02455691997-07-17 16:21:52 +00003096 File "<stdin>", line 1, in ?
3097ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00003098\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003099
Fred Drake20082d92000-04-03 04:26:58 +00003100File objects have some additional methods, such as
3101\method{isatty()} and \method{truncate()} which are less frequently
3102used; consult the Library Reference for a complete guide to file
3103objects.
Guido van Rossum02455691997-07-17 16:21:52 +00003104
Fred Drakeb7833d31998-09-11 16:21:55 +00003105\subsection{The \module{pickle} Module \label{pickle}}
Fred Drake391564f1998-04-01 23:11:56 +00003106\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00003107
3108Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00003109bit more effort, since the \method{read()} method only returns
3110strings, which will have to be passed to a function like
3111\function{string.atoi()}, which takes a string like \code{'123'} and
3112returns its numeric value 123. However, when you want to save more
3113complex data types like lists, dictionaries, or class instances,
3114things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00003115
3116Rather than have users be constantly writing and debugging code to
3117save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00003118\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00003119any Python object (even some forms of Python code!), and convert it to
3120a string representation; this process is called \dfn{pickling}.
3121Reconstructing the object from the string representation is called
3122\dfn{unpickling}. Between pickling and unpickling, the string
3123representing the object may have been stored in a file or data, or
3124sent over a network connection to some distant machine.
3125
3126If you have an object \code{x}, and a file object \code{f} that's been
3127opened for writing, the simplest way to pickle the object takes only
3128one line of code:
3129
Fred Drake8842e861998-02-13 07:16:30 +00003130\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003131pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00003132\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003133
Fred Drake8842e861998-02-13 07:16:30 +00003134To unpickle the object again, if \code{f} is a file object which has
3135been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00003136
Fred Drake8842e861998-02-13 07:16:30 +00003137\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003138x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00003139\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003140
Guido van Rossum02455691997-07-17 16:21:52 +00003141(There are other variants of this, used when pickling many objects or
3142when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00003143complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00003144
Fred Drake20082d92000-04-03 04:26:58 +00003145\module{pickle} is the standard way to make Python objects which can
3146be stored and reused by other programs or by a future invocation of
3147the same program; the technical term for this is a
3148\dfn{persistent} object. Because \module{pickle} is so widely used,
3149many authors who write Python extensions take care to ensure that new
3150data types such as matrices can be properly pickled and unpickled.
Guido van Rossum02455691997-07-17 16:21:52 +00003151
Guido van Rossum6fc178f1991-08-16 09:13:42 +00003152
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003153
Fred Drakeb7833d31998-09-11 16:21:55 +00003154\chapter{Errors and Exceptions \label{errors}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00003155
3156Until now error messages haven't been more than mentioned, but if you
3157have tried out the examples you have probably seen some. There are
Fred Drake20082d92000-04-03 04:26:58 +00003158(at least) two distinguishable kinds of errors:
3159\emph{syntax errors} and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00003160
Fred Drakeb7833d31998-09-11 16:21:55 +00003161\section{Syntax Errors \label{syntaxErrors}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003162
3163Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00003164kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003165
Fred Drake8842e861998-02-13 07:16:30 +00003166\begin{verbatim}
Raymond Hettingera6e16a82002-08-21 04:54:00 +00003167>>> while True print 'Hello world'
Fred Drake13af4282001-09-21 21:10:05 +00003168 File "<stdin>", line 1, in ?
Raymond Hettingera6e16a82002-08-21 04:54:00 +00003169 while True print 'Hello world'
3170 ^
Guido van Rossum6938f061994-08-01 12:22:53 +00003171SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00003172\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003173
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003174The parser repeats the offending line and displays a little `arrow'
Fred Drake20082d92000-04-03 04:26:58 +00003175pointing at the earliest point in the line where the error was
3176detected. The error is caused by (or at least detected at) the token
3177\emph{preceding} the arrow: in the example, the error is detected at
3178the keyword \keyword{print}, since a colon (\character{:}) is missing
3179before it. File name and line number are printed so you know where to
3180look in case the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003181
Fred Drakeb7833d31998-09-11 16:21:55 +00003182\section{Exceptions \label{exceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003183
Guido van Rossum6fc178f1991-08-16 09:13:42 +00003184Even if a statement or expression is syntactically correct, it may
3185cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00003186Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00003187not unconditionally fatal: you will soon learn how to handle them in
3188Python programs. Most exceptions are not handled by programs,
3189however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003190
Fred Drake8842e861998-02-13 07:16:30 +00003191\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003192>>> 10 * (1/0)
Fred Drake162c6a62001-02-14 03:20:18 +00003193Traceback (most recent call last):
Fred Drake13af4282001-09-21 21:10:05 +00003194 File "<stdin>", line 1, in ?
Raymond Hettingera02469f2003-05-07 17:49:36 +00003195ZeroDivisionError: integer division or modulo by zero
Guido van Rossume5f8b601995-01-04 19:12:49 +00003196>>> 4 + spam*3
Fred Drake162c6a62001-02-14 03:20:18 +00003197Traceback (most recent call last):
Fred Drake13af4282001-09-21 21:10:05 +00003198 File "<stdin>", line 1, in ?
Andrew M. Kuchlinge7bd8762002-05-02 14:31:55 +00003199NameError: name 'spam' is not defined
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003200>>> '2' + 2
Fred Drake162c6a62001-02-14 03:20:18 +00003201Traceback (most recent call last):
Fred Drake13af4282001-09-21 21:10:05 +00003202 File "<stdin>", line 1, in ?
Raymond Hettingera02469f2003-05-07 17:49:36 +00003203TypeError: cannot concatenate 'str' and 'int' objects
Fred Drake8842e861998-02-13 07:16:30 +00003204\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003205
Guido van Rossumb2c65561993-05-12 08:53:36 +00003206The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003207Exceptions come in different types, and the type is printed as part of
3208the message: the types in the example are
Fred Drake20082d92000-04-03 04:26:58 +00003209\exception{ZeroDivisionError}, \exception{NameError} and
Fred Drake8842e861998-02-13 07:16:30 +00003210\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00003211The string printed as the exception type is the name of the built-in
3212name for the exception that occurred. This is true for all built-in
3213exceptions, but need not be true for user-defined exceptions (although
3214it is a useful convention).
3215Standard exception names are built-in identifiers (not reserved
3216keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003217
Guido van Rossumb2c65561993-05-12 08:53:36 +00003218The rest of the line is a detail whose interpretation depends on the
3219exception type; its meaning is dependent on the exception type.
3220
3221The preceding part of the error message shows the context where the
3222exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00003223In general it contains a stack backtrace listing source lines; however,
3224it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003225
Fred Drake860106a2000-10-20 03:03:18 +00003226The \citetitle[../lib/module-exceptions.html]{Python Library
3227Reference} lists the built-in exceptions and their meanings.
Fred Drake20082d92000-04-03 04:26:58 +00003228
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003229
Fred Drakeb7833d31998-09-11 16:21:55 +00003230\section{Handling Exceptions \label{handling}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003231
3232It is possible to write programs that handle selected exceptions.
Fred Drake20082d92000-04-03 04:26:58 +00003233Look at the following example, which asks the user for input until a
3234valid integer has been entered, but allows the user to interrupt the
3235program (using \kbd{Control-C} or whatever the operating system
3236supports); note that a user-generated interruption is signalled by
3237raising the \exception{KeyboardInterrupt} exception.
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003238
Fred Drake8842e861998-02-13 07:16:30 +00003239\begin{verbatim}
Raymond Hettingera6e16a82002-08-21 04:54:00 +00003240>>> while True:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003241... try:
Fred Drake20082d92000-04-03 04:26:58 +00003242... x = int(raw_input("Please enter a number: "))
3243... break
3244... except ValueError:
3245... print "Oops! That was no valid number. Try again..."
Guido van Rossum02455691997-07-17 16:21:52 +00003246...
Fred Drake8842e861998-02-13 07:16:30 +00003247\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003248
Fred Drake8842e861998-02-13 07:16:30 +00003249The \keyword{try} statement works as follows.
Fred Drake20082d92000-04-03 04:26:58 +00003250
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003251\begin{itemize}
3252\item
Fred Drake20082d92000-04-03 04:26:58 +00003253First, the \emph{try clause} (the statement(s) between the
3254\keyword{try} and \keyword{except} keywords) is executed.
3255
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003256\item
Fred Drake20082d92000-04-03 04:26:58 +00003257If no exception occurs, the \emph{except\ clause} is skipped and
3258execution of the \keyword{try} statement is finished.
3259
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003260\item
Fred Drake20082d92000-04-03 04:26:58 +00003261If an exception occurs during execution of the try clause, the rest of
3262the clause is skipped. Then if its type matches the exception named
3263after the \keyword{except} keyword, the rest of the try clause is
3264skipped, the except clause is executed, and then execution continues
3265after the \keyword{try} statement.
3266
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003267\item
3268If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00003269except clause, it is passed on to outer \keyword{try} statements; if
Fred Drake20082d92000-04-03 04:26:58 +00003270no handler is found, it is an \emph{unhandled exception} and execution
3271stops with a message as shown above.
3272
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003273\end{itemize}
Fred Drake20082d92000-04-03 04:26:58 +00003274
Fred Drake8842e861998-02-13 07:16:30 +00003275A \keyword{try} statement may have more than one except clause, to
Fred Drake20082d92000-04-03 04:26:58 +00003276specify handlers for different exceptions. At most one handler will
3277be executed. Handlers only handle exceptions that occur in the
3278corresponding try clause, not in other handlers of the same
Fred Drakeed514942001-07-06 17:28:39 +00003279\keyword{try} statement. An except clause may name multiple exceptions
3280as a parenthesized list, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003281
Fred Drake8842e861998-02-13 07:16:30 +00003282\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003283... except (RuntimeError, TypeError, NameError):
3284... pass
Fred Drake8842e861998-02-13 07:16:30 +00003285\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003286
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003287The last except clause may omit the exception name(s), to serve as a
Fred Drake20082d92000-04-03 04:26:58 +00003288wildcard. Use this with extreme caution, since it is easy to mask a
3289real programming error in this way! It can also be used to print an
3290error message and then re-raise the exception (allowing a caller to
3291handle the exception as well):
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003292
Fred Drake20082d92000-04-03 04:26:58 +00003293\begin{verbatim}
3294import string, sys
3295
3296try:
3297 f = open('myfile.txt')
3298 s = f.readline()
3299 i = int(string.strip(s))
3300except IOError, (errno, strerror):
3301 print "I/O error(%s): %s" % (errno, strerror)
3302except ValueError:
3303 print "Could not convert data to an integer."
3304except:
3305 print "Unexpected error:", sys.exc_info()[0]
3306 raise
3307\end{verbatim}
Fred Drake2900ff91999-08-24 22:14:57 +00003308
Fred Drake8842e861998-02-13 07:16:30 +00003309The \keyword{try} \ldots\ \keyword{except} statement has an optional
Fred Drakee99d1db2000-04-17 14:56:31 +00003310\emph{else clause}, which, when present, must follow all except
3311clauses. It is useful for code that must be executed if the try
3312clause does not raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00003313
3314\begin{verbatim}
Guido van Rossuma4289a71998-07-07 20:18:06 +00003315for arg in sys.argv[1:]:
Fred Drake8842e861998-02-13 07:16:30 +00003316 try:
3317 f = open(arg, 'r')
3318 except IOError:
3319 print 'cannot open', arg
3320 else:
3321 print arg, 'has', len(f.readlines()), 'lines'
3322 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00003323\end{verbatim}
3324
Fred Drakee99d1db2000-04-17 14:56:31 +00003325The use of the \keyword{else} clause is better than adding additional
3326code to the \keyword{try} clause because it avoids accidentally
3327catching an exception that wasn't raised by the code being protected
3328by the \keyword{try} \ldots\ \keyword{except} statement.
3329
Guido van Rossum02455691997-07-17 16:21:52 +00003330
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003331When an exception occurs, it may have an associated value, also known as
Thomas Woutersf9b526d2000-07-16 19:05:38 +00003332the exception's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003333The presence and type of the argument depend on the exception type.
Raymond Hettinger6122d022003-07-12 01:05:37 +00003334
3335The except clause may specify a variable after the exception name (or list).
3336The variable is bound to an exception instance with the arguments stored
3337in \code{instance.args}. For convenience, the exception instance
3338defines \method{__getitem__} and \method{__str__} so the arguments can
3339be accessed or printed directly without having to reference \code{.args}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003340
Fred Drake8842e861998-02-13 07:16:30 +00003341\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003342>>> try:
Raymond Hettinger6122d022003-07-12 01:05:37 +00003343... raise Exception('spam', 'eggs')
3344... except Exception, inst:
3345... print type(inst) # the exception instance
Raymond Hettingerb233e542003-07-15 23:16:01 +00003346... print inst.args # arguments stored in .args
Raymond Hettinger6122d022003-07-12 01:05:37 +00003347... print inst # __str__ allows args to printed directly
3348... x, y = inst # __getitem__ allows args to be unpacked directly
3349... print 'x =', x
3350... print 'y =', y
3351...
3352<type 'instance'>
3353('spam', 'eggs')
3354('spam', 'eggs')
3355x = spam
3356y = eggs
Fred Drake8842e861998-02-13 07:16:30 +00003357\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003358
Guido van Rossumb2c65561993-05-12 08:53:36 +00003359If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003360(`detail') of the message for unhandled exceptions.
3361
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003362Exception handlers don't just handle exceptions if they occur
3363immediately in the try clause, but also if they occur inside functions
3364that are called (even indirectly) in the try clause.
3365For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003366
Fred Drake8842e861998-02-13 07:16:30 +00003367\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003368>>> def this_fails():
3369... x = 1/0
3370...
3371>>> try:
3372... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00003373... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003374... print 'Handling run-time error:', detail
3375...
Guido van Rossumb2c65561993-05-12 08:53:36 +00003376Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00003377\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003378
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003379
Fred Drakeb7833d31998-09-11 16:21:55 +00003380\section{Raising Exceptions \label{raising}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003381
Fred Drake8842e861998-02-13 07:16:30 +00003382The \keyword{raise} statement allows the programmer to force a
3383specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003384For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003385
Fred Drake8842e861998-02-13 07:16:30 +00003386\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00003387>>> raise NameError, 'HiThere'
Fred Drake162c6a62001-02-14 03:20:18 +00003388Traceback (most recent call last):
Fred Drake13af4282001-09-21 21:10:05 +00003389 File "<stdin>", line 1, in ?
Guido van Rossumb2c65561993-05-12 08:53:36 +00003390NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00003391\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003392
Fred Drake8842e861998-02-13 07:16:30 +00003393The first argument to \keyword{raise} names the exception to be
3394raised. The optional second argument specifies the exception's
3395argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003396
Fred Drake13af4282001-09-21 21:10:05 +00003397If you need to determine whether an exception was raised but don't
3398intend to handle it, a simpler form of the \keyword{raise} statement
3399allows you to re-raise the exception:
3400
3401\begin{verbatim}
3402>>> try:
3403... raise NameError, 'HiThere'
3404... except NameError:
3405... print 'An exception flew by!'
3406... raise
3407...
3408An exception flew by!
3409Traceback (most recent call last):
3410 File "<stdin>", line 2, in ?
3411NameError: HiThere
3412\end{verbatim}
3413
Guido van Rossum02455691997-07-17 16:21:52 +00003414
Fred Drakeb7833d31998-09-11 16:21:55 +00003415\section{User-defined Exceptions \label{userExceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003416
Fred Drake13af4282001-09-21 21:10:05 +00003417Programs may name their own exceptions by creating a new exception
3418class. Exceptions should typically be derived from the
3419\exception{Exception} class, either directly or indirectly. For
3420example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003421
Fred Drake8842e861998-02-13 07:16:30 +00003422\begin{verbatim}
Fred Drake13af4282001-09-21 21:10:05 +00003423>>> class MyError(Exception):
Fred Drake20082d92000-04-03 04:26:58 +00003424... def __init__(self, value):
3425... self.value = value
3426... def __str__(self):
Skip Montanarob4f12422003-05-07 15:29:12 +00003427... return repr(self.value)
Fred Drake20082d92000-04-03 04:26:58 +00003428...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003429>>> try:
Fred Drake20082d92000-04-03 04:26:58 +00003430... raise MyError(2*2)
3431... except MyError, e:
3432... print 'My exception occurred, value:', e.value
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003433...
Guido van Rossum6938f061994-08-01 12:22:53 +00003434My exception occurred, value: 4
Fred Drake13af4282001-09-21 21:10:05 +00003435>>> raise MyError, 'oops!'
Fred Drake162c6a62001-02-14 03:20:18 +00003436Traceback (most recent call last):
Fred Drake13af4282001-09-21 21:10:05 +00003437 File "<stdin>", line 1, in ?
3438__main__.MyError: 'oops!'
Fred Drake8842e861998-02-13 07:16:30 +00003439\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003440
Fred Drake13af4282001-09-21 21:10:05 +00003441Exception classes can be defined which do anything any other class can
3442do, but are usually kept simple, often only offering a number of
3443attributes that allow information about the error to be extracted by
3444handlers for the exception. When creating a module which can raise
3445several distinct errors, a common practice is to create a base class
3446for exceptions defined by that module, and subclass that to create
3447specific exception classes for different error conditions:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003448
Fred Drake13af4282001-09-21 21:10:05 +00003449\begin{verbatim}
3450class Error(Exception):
3451 """Base class for exceptions in this module."""
3452 pass
3453
3454class InputError(Error):
3455 """Exception raised for errors in the input.
3456
3457 Attributes:
3458 expression -- input expression in which the error occurred
3459 message -- explanation of the error
3460 """
3461
3462 def __init__(self, expression, message):
3463 self.expression = expression
3464 self.message = message
3465
3466class TransitionError(Error):
3467 """Raised when an operation attempts a state transition that's not
3468 allowed.
3469
3470 Attributes:
3471 previous -- state at beginning of transition
3472 next -- attempted new state
3473 message -- explanation of why the specific transition is not allowed
3474 """
3475
3476 def __init__(self, previous, next, message):
3477 self.previous = previous
3478 self.next = next
3479 self.message = message
3480\end{verbatim}
3481
3482Most exceptions are defined with names that end in ``Error,'' similar
3483to the naming of the standard exceptions.
3484
3485Many standard modules define their own exceptions to report errors
3486that may occur in functions they define. More information on classes
3487is presented in chapter \ref{classes}, ``Classes.''
Fred Drake20082d92000-04-03 04:26:58 +00003488
Guido van Rossum02455691997-07-17 16:21:52 +00003489
Fred Drakeb7833d31998-09-11 16:21:55 +00003490\section{Defining Clean-up Actions \label{cleanup}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003491
Fred Drake8842e861998-02-13 07:16:30 +00003492The \keyword{try} statement has another optional clause which is
3493intended to define clean-up actions that must be executed under all
3494circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00003495
Fred Drake8842e861998-02-13 07:16:30 +00003496\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003497>>> try:
3498... raise KeyboardInterrupt
3499... finally:
3500... print 'Goodbye, world!'
3501...
3502Goodbye, world!
Fred Drake162c6a62001-02-14 03:20:18 +00003503Traceback (most recent call last):
Fred Drake13af4282001-09-21 21:10:05 +00003504 File "<stdin>", line 2, in ?
Guido van Rossumb2c65561993-05-12 08:53:36 +00003505KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00003506\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00003507
Fred Drake8842e861998-02-13 07:16:30 +00003508A \emph{finally clause} is executed whether or not an exception has
3509occurred in the try clause. When an exception has occurred, it is
3510re-raised after the finally clause is executed. The finally clause is
3511also executed ``on the way out'' when the \keyword{try} statement is
3512left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00003513
Fred Drake13af4282001-09-21 21:10:05 +00003514The code in the finally clause is useful for releasing external
3515resources (such as files or network connections), regardless of
3516whether or not the use of the resource was successful.
3517
Fred Drake8842e861998-02-13 07:16:30 +00003518A \keyword{try} statement must either have one or more except clauses
3519or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003520
Fred Drake13af4282001-09-21 21:10:05 +00003521
Fred Drakeb7833d31998-09-11 16:21:55 +00003522\chapter{Classes \label{classes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003523
3524Python's class mechanism adds classes to the language with a minimum
3525of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00003526found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003527do not put an absolute barrier between definition and user, but rather
3528rely on the politeness of the user not to ``break into the
3529definition.'' The most important features of classes are retained
3530with full power, however: the class inheritance mechanism allows
3531multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00003532base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003533same name. Objects can contain an arbitrary amount of private data.
3534
Guido van Rossum16d6e711994-08-08 12:30:22 +00003535In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00003536\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00003537no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003538shorthands for referencing the object's members from its methods: the
3539method function is declared with an explicit first argument
3540representing the object, which is provided implicitly by the call. As
3541in Smalltalk, classes themselves are objects, albeit in the wider
3542sense of the word: in Python, all data types are objects. This
Fred Drake20082d92000-04-03 04:26:58 +00003543provides semantics for importing and renaming. But, just like in
3544\Cpp{} or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00003545extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003546built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00003547subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003548
Fred Drakeb7833d31998-09-11 16:21:55 +00003549\section{A Word About Terminology \label{terminology}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003550
Fred Drake391564f1998-04-01 23:11:56 +00003551Lacking universally accepted terminology to talk about classes, I will
3552make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003553terms, since its object-oriented semantics are closer to those of
Fred Drakec37b65e2001-11-28 07:26:15 +00003554Python than \Cpp, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003555
3556I also have to warn you that there's a terminological pitfall for
3557object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00003558necessarily mean a class instance. Like \Cpp{} and Modula-3, and
3559unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00003560built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00003561exotic types like files aren't. However, \emph{all} Python types
3562share a little bit of common semantics that is best described by using
3563the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003564
3565Objects have individuality, and multiple names (in multiple scopes)
3566can be bound to the same object. This is known as aliasing in other
3567languages. This is usually not appreciated on a first glance at
3568Python, and can be safely ignored when dealing with immutable basic
3569types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00003570(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003571objects such as lists, dictionaries, and most types representing
3572entities outside the program (files, windows, etc.). This is usually
3573used to the benefit of the program, since aliases behave like pointers
3574in some respects. For example, passing an object is cheap since only
3575a pointer is passed by the implementation; and if a function modifies
3576an object passed as an argument, the caller will see the change --- this
Raymond Hettingerccd615c2003-06-30 04:27:31 +00003577eliminates the need for two different argument passing mechanisms as in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003578Pascal.
3579
3580
Fred Drakeb7833d31998-09-11 16:21:55 +00003581\section{Python Scopes and Name Spaces \label{scopes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003582
3583Before introducing classes, I first have to tell you something about
3584Python's scope rules. Class definitions play some neat tricks with
Fred Drake13494372000-09-12 16:23:48 +00003585namespaces, and you need to know how scopes and namespaces work to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003586fully understand what's going on. Incidentally, knowledge about this
3587subject is useful for any advanced Python programmer.
3588
3589Let's begin with some definitions.
3590
Fred Drake13494372000-09-12 16:23:48 +00003591A \emph{namespace} is a mapping from names to objects. Most
3592namespaces are currently implemented as Python dictionaries, but
3593that's normally not noticeable in any way (except for performance),
3594and it may change in the future. Examples of namespaces are: the set
3595of built-in names (functions such as \function{abs()}, and built-in
3596exception names); the global names in a module; and the local names in
3597a function invocation. In a sense the set of attributes of an object
3598also form a namespace. The important thing to know about namespaces
3599is that there is absolutely no relation between names in different
3600namespaces; for instance, two different modules may both define a
3601function ``maximize'' without confusion --- users of the modules must
3602prefix it with the module name.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003603
Fred Drakeeee08cd1997-12-04 15:43:15 +00003604By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00003605dot --- for example, in the expression \code{z.real}, \code{real} is
3606an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003607names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00003608\code{modname.funcname}, \code{modname} is a module object and
3609\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003610be a straightforward mapping between the module's attributes and the
Fred Drake13494372000-09-12 16:23:48 +00003611global names defined in the module: they share the same namespace!
3612\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00003613 Except for one thing. Module objects have a secret read-only
Fred Drake13494372000-09-12 16:23:48 +00003614 attribute called \member{__dict__} which returns the dictionary
3615 used to implement the module's namespace; the name
3616 \member{__dict__} is an attribute but not a global name.
3617 Obviously, using this violates the abstraction of namespace
Guido van Rossum6938f061994-08-01 12:22:53 +00003618 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00003619 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003620}
3621
3622Attributes may be read-only or writable. In the latter case,
3623assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00003624you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drakeed514942001-07-06 17:28:39 +00003625also be deleted with the \keyword{del} statement. For example,
3626\samp{del modname.the_answer} will remove the attribute
3627\member{the_answer} from the object named by \code{modname}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003628
3629Name spaces are created at different moments and have different
Fred Drake13494372000-09-12 16:23:48 +00003630lifetimes. The namespace containing the built-in names is created
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003631when the Python interpreter starts up, and is never deleted. The
Fred Drake13494372000-09-12 16:23:48 +00003632global namespace for a module is created when the module definition
3633is read in; normally, module namespaces also last until the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003634interpreter quits. The statements executed by the top-level
3635invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00003636interactively, are considered part of a module called
Fred Drake13494372000-09-12 16:23:48 +00003637\module{__main__}, so they have their own global namespace. (The
Fred Drake8842e861998-02-13 07:16:30 +00003638built-in names actually also live in a module; this is called
3639\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003640
Fred Drake13494372000-09-12 16:23:48 +00003641The local namespace for a function is created when the function is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003642called, and deleted when the function returns or raises an exception
3643that is not handled within the function. (Actually, forgetting would
3644be a better way to describe what actually happens.) Of course,
Fred Drake13494372000-09-12 16:23:48 +00003645recursive invocations each have their own local namespace.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003646
Fred Drake13494372000-09-12 16:23:48 +00003647A \emph{scope} is a textual region of a Python program where a
3648namespace is directly accessible. ``Directly accessible'' here means
3649that an unqualified reference to a name attempts to find the name in
3650the namespace.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003651
3652Although scopes are determined statically, they are used dynamically.
Raymond Hettinger861bb022002-08-07 16:09:48 +00003653At any time during execution, there are at least three nested scopes whose
3654namespaces are directly accessible: the innermost scope, which is searched
Raymond Hettingerae7ef572002-08-07 20:20:52 +00003655first, contains the local names; the namespaces of any enclosing
3656functions, which are searched starting with the nearest enclosing scope;
3657the middle scope, searched next, contains the current module's global names;
3658and the outermost scope (searched last) is the namespace containing built-in
3659names.
Raymond Hettinger861bb022002-08-07 16:09:48 +00003660
3661If a name is declared global, then all references and assignments go
3662directly to the middle scope containing the module's global names.
3663Otherwise, all variables found outside of the innermost scope are read-only.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003664
3665Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00003666current function. Outside of functions, the local scope references
Fred Drake13494372000-09-12 16:23:48 +00003667the same namespace as the global scope: the module's namespace.
3668Class definitions place yet another namespace in the local scope.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003669
3670It is important to realize that scopes are determined textually: the
Fred Drake13494372000-09-12 16:23:48 +00003671global scope of a function defined in a module is that module's
3672namespace, no matter from where or by what alias the function is
3673called. On the other hand, the actual search for names is done
3674dynamically, at run time --- however, the language definition is
3675evolving towards static name resolution, at ``compile'' time, so don't
3676rely on dynamic name resolution! (In fact, local variables are
3677already determined statically.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003678
3679A special quirk of Python is that assignments always go into the
3680innermost scope. Assignments do not copy data --- they just
3681bind names to objects. The same is true for deletions: the statement
Fred Drake13494372000-09-12 16:23:48 +00003682\samp{del x} removes the binding of \code{x} from the namespace
Fred Drake391564f1998-04-01 23:11:56 +00003683referenced by the local scope. In fact, all operations that introduce
3684new names use the local scope: in particular, import statements and
3685function definitions bind the module or function name in the local
3686scope. (The \keyword{global} statement can be used to indicate that
3687particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003688
3689
Fred Drakeb7833d31998-09-11 16:21:55 +00003690\section{A First Look at Classes \label{firstClasses}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003691
3692Classes introduce a little bit of new syntax, three new object types,
3693and some new semantics.
3694
3695
Fred Drakeb7833d31998-09-11 16:21:55 +00003696\subsection{Class Definition Syntax \label{classDefinition}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003697
3698The simplest form of class definition looks like this:
3699
3700\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003701class ClassName:
3702 <statement-1>
3703 .
3704 .
3705 .
3706 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003707\end{verbatim}
3708
Fred Drake20082d92000-04-03 04:26:58 +00003709Class definitions, like function definitions
3710(\keyword{def} statements) must be executed before they have any
3711effect. (You could conceivably place a class definition in a branch
3712of an \keyword{if} statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003713
3714In practice, the statements inside a class definition will usually be
3715function definitions, but other statements are allowed, and sometimes
3716useful --- we'll come back to this later. The function definitions
3717inside a class normally have a peculiar form of argument list,
3718dictated by the calling conventions for methods --- again, this is
3719explained later.
3720
Fred Drake13494372000-09-12 16:23:48 +00003721When a class definition is entered, a new namespace is created, and
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003722used as the local scope --- thus, all assignments to local variables
Fred Drake13494372000-09-12 16:23:48 +00003723go into this new namespace. In particular, function definitions bind
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003724the name of the new function here.
3725
Fred Drakeeee08cd1997-12-04 15:43:15 +00003726When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003727object} is created. This is basically a wrapper around the contents
Fred Drake13494372000-09-12 16:23:48 +00003728of the namespace created by the class definition; we'll learn more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003729about class objects in the next section. The original local scope
3730(the one in effect just before the class definitions was entered) is
Fred Drakea594baf1998-04-03 05:16:31 +00003731reinstated, and the class object is bound here to the class name given
3732in the class definition header (\class{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003733
3734
Fred Drakeb7833d31998-09-11 16:21:55 +00003735\subsection{Class Objects \label{classObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003736
3737Class objects support two kinds of operations: attribute references
3738and instantiation.
3739
Fred Drakeeee08cd1997-12-04 15:43:15 +00003740\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00003741attribute references in Python: \code{obj.name}. Valid attribute
Fred Drake13494372000-09-12 16:23:48 +00003742names are all the names that were in the class's namespace when the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003743class object was created. So, if the class definition looked like
3744this:
3745
3746\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003747class MyClass:
3748 "A simple example class"
3749 i = 12345
Fred Drake88e66252001-06-29 17:50:57 +00003750 def f(self):
Fred Drake8842e861998-02-13 07:16:30 +00003751 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003752\end{verbatim}
3753
Fred Drake8842e861998-02-13 07:16:30 +00003754then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Fred Drake20082d92000-04-03 04:26:58 +00003755references, returning an integer and a method object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00003756Class attributes can also be assigned to, so you can change the value
Fred Drake20082d92000-04-03 04:26:58 +00003757of \code{MyClass.i} by assignment. \member{__doc__} is also a valid
3758attribute, returning the docstring belonging to the class: \code{"A
Raymond Hettingerfa6cce12003-07-11 18:58:11 +00003759simple example class"}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003760
Fred Drakeeee08cd1997-12-04 15:43:15 +00003761Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003762the class object is a parameterless function that returns a new
Fred Drake20082d92000-04-03 04:26:58 +00003763instance of the class. For example (assuming the above class):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003764
3765\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003766x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003767\end{verbatim}
3768
Fred Drakeeee08cd1997-12-04 15:43:15 +00003769creates a new \emph{instance} of the class and assigns this object to
3770the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003771
Fred Drake20082d92000-04-03 04:26:58 +00003772The instantiation operation (``calling'' a class object) creates an
3773empty object. Many classes like to create objects in a known initial
3774state. Therefore a class may define a special method named
3775\method{__init__()}, like this:
3776
3777\begin{verbatim}
3778 def __init__(self):
3779 self.data = []
3780\end{verbatim}
3781
3782When a class defines an \method{__init__()} method, class
3783instantiation automatically invokes \method{__init__()} for the
3784newly-created class instance. So in this example, a new, initialized
3785instance can be obtained by:
3786
3787\begin{verbatim}
3788x = MyClass()
3789\end{verbatim}
3790
3791Of course, the \method{__init__()} method may have arguments for
3792greater flexibility. In that case, arguments given to the class
3793instantiation operator are passed on to \method{__init__()}. For
3794example,
3795
3796\begin{verbatim}
3797>>> class Complex:
3798... def __init__(self, realpart, imagpart):
3799... self.r = realpart
3800... self.i = imagpart
3801...
Tim Petersbd695a72001-05-22 06:54:14 +00003802>>> x = Complex(3.0, -4.5)
Fred Drake20082d92000-04-03 04:26:58 +00003803>>> x.r, x.i
3804(3.0, -4.5)
3805\end{verbatim}
3806
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003807
Fred Drakeb7833d31998-09-11 16:21:55 +00003808\subsection{Instance Objects \label{instanceObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003809
3810Now what can we do with instance objects? The only operations
3811understood by instance objects are attribute references. There are
3812two kinds of valid attribute names.
3813
Fred Drakeeee08cd1997-12-04 15:43:15 +00003814The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00003815``instance variables'' in Smalltalk, and to ``data members'' in
Fred Drakec37b65e2001-11-28 07:26:15 +00003816\Cpp. Data attributes need not be declared; like local variables,
Fred Drake8842e861998-02-13 07:16:30 +00003817they spring into existence when they are first assigned to. For
3818example, if \code{x} is the instance of \class{MyClass} created above,
3819the following piece of code will print the value \code{16}, without
3820leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003821
3822\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003823x.counter = 1
3824while x.counter < 10:
3825 x.counter = x.counter * 2
3826print x.counter
3827del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003828\end{verbatim}
3829
3830The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00003831are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003832object. (In Python, the term method is not unique to class instances:
Fred Drakeed514942001-07-06 17:28:39 +00003833other object types can have methods as well. For example, list objects have
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003834methods called append, insert, remove, sort, and so on. However,
3835below, we'll use the term method exclusively to mean methods of class
3836instance objects, unless explicitly stated otherwise.)
3837
3838Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00003839definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003840objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00003841example, \code{x.f} is a valid method reference, since
3842\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00003843\code{MyClass.i} is not. But \code{x.f} is not the same thing as
Fred Drake20082d92000-04-03 04:26:58 +00003844\code{MyClass.f} --- it is a \obindex{method}\emph{method object}, not
3845a function object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003846
3847
Fred Drakeb7833d31998-09-11 16:21:55 +00003848\subsection{Method Objects \label{methodObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003849
Fred Drakeed514942001-07-06 17:28:39 +00003850Usually, a method is called immediately:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003851
3852\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003853x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003854\end{verbatim}
3855
Fred Drake8842e861998-02-13 07:16:30 +00003856In our example, this will return the string \code{'hello world'}.
Fred Drakeee84d591999-03-10 17:25:30 +00003857However, it is not necessary to call a method right away:
3858\code{x.f} is a method object, and can be stored away and called at a
3859later time. For example:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003860
3861\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003862xf = x.f
Raymond Hettingera6e16a82002-08-21 04:54:00 +00003863while True:
Fred Drake8842e861998-02-13 07:16:30 +00003864 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003865\end{verbatim}
3866
Fred Drake8842e861998-02-13 07:16:30 +00003867will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003868
3869What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00003870that \code{x.f()} was called without an argument above, even though
3871the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003872happened to the argument? Surely Python raises an exception when a
3873function that requires an argument is called without any --- even if
3874the argument isn't actually used...
3875
3876Actually, you may have guessed the answer: the special thing about
3877methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00003878function. In our example, the call \code{x.f()} is exactly equivalent
3879to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00003880\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003881with an argument list that is created by inserting the method's object
3882before the first argument.
3883
3884If you still don't understand how methods work, a look at the
3885implementation can perhaps clarify matters. When an instance
3886attribute is referenced that isn't a data attribute, its class is
3887searched. If the name denotes a valid class attribute that is a
3888function object, a method object is created by packing (pointers to)
3889the instance object and the function object just found together in an
3890abstract object: this is the method object. When the method object is
3891called with an argument list, it is unpacked again, a new argument
3892list is constructed from the instance object and the original argument
3893list, and the function object is called with this new argument list.
3894
3895
Fred Drakeb7833d31998-09-11 16:21:55 +00003896\section{Random Remarks \label{remarks}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003897
3898[These should perhaps be placed more carefully...]
3899
3900
3901Data attributes override method attributes with the same name; to
3902avoid accidental name conflicts, which may cause hard-to-find bugs in
3903large programs, it is wise to use some kind of convention that
Fred Drakeed514942001-07-06 17:28:39 +00003904minimizes the chance of conflicts. Possible conventions include
3905capitalizing method names, prefixing data attribute names with a small
3906unique string (perhaps just an underscore), or using verbs for methods
3907and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003908
3909
3910Data attributes may be referenced by methods as well as by ordinary
3911users (``clients'') of an object. In other words, classes are not
3912usable to implement pure abstract data types. In fact, nothing in
3913Python makes it possible to enforce data hiding --- it is all based
3914upon convention. (On the other hand, the Python implementation,
Fred Drakeee84d591999-03-10 17:25:30 +00003915written in C, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003916access to an object if necessary; this can be used by extensions to
Fred Drakeee84d591999-03-10 17:25:30 +00003917Python written in C.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003918
3919
3920Clients should use data attributes with care --- clients may mess up
3921invariants maintained by the methods by stamping on their data
3922attributes. Note that clients may add data attributes of their own to
3923an instance object without affecting the validity of the methods, as
3924long as name conflicts are avoided --- again, a naming convention can
3925save a lot of headaches here.
3926
3927
3928There is no shorthand for referencing data attributes (or other
3929methods!) from within methods. I find that this actually increases
3930the readability of methods: there is no chance of confusing local
3931variables and instance variables when glancing through a method.
3932
3933
3934Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00003935\code{self}. This is nothing more than a convention: the name
3936\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003937however, that by not following the convention your code may be less
3938readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00003939a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003940convention.)
3941
3942
3943Any function object that is a class attribute defines a method for
3944instances of that class. It is not necessary that the function
3945definition is textually enclosed in the class definition: assigning a
3946function object to a local variable in the class is also ok. For
3947example:
3948
3949\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003950# Function defined outside the class
3951def f1(self, x, y):
3952 return min(x, x+y)
3953
3954class C:
3955 f = f1
3956 def g(self):
3957 return 'hello world'
3958 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003959\end{verbatim}
3960
Fred Drake8842e861998-02-13 07:16:30 +00003961Now \code{f}, \code{g} and \code{h} are all attributes of class
3962\class{C} that refer to function objects, and consequently they are all
3963methods of instances of \class{C} --- \code{h} being exactly equivalent
3964to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003965the reader of a program.
3966
3967
3968Methods may call other methods by using method attributes of the
Fred Drakeed514942001-07-06 17:28:39 +00003969\code{self} argument:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003970
3971\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003972class Bag:
Fred Drake20082d92000-04-03 04:26:58 +00003973 def __init__(self):
Fred Drake8842e861998-02-13 07:16:30 +00003974 self.data = []
3975 def add(self, x):
3976 self.data.append(x)
3977 def addtwice(self, x):
3978 self.add(x)
3979 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003980\end{verbatim}
3981
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003982Methods may reference global names in the same way as ordinary
3983functions. The global scope associated with a method is the module
3984containing the class definition. (The class itself is never used as a
3985global scope!) While one rarely encounters a good reason for using
3986global data in a method, there are many legitimate uses of the global
3987scope: for one thing, functions and modules imported into the global
3988scope can be used by methods, as well as functions and classes defined
3989in it. Usually, the class containing the method is itself defined in
3990this global scope, and in the next section we'll find some good
3991reasons why a method would want to reference its own class!
3992
3993
Fred Drakeb7833d31998-09-11 16:21:55 +00003994\section{Inheritance \label{inheritance}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003995
3996Of course, a language feature would not be worthy of the name ``class''
3997without supporting inheritance. The syntax for a derived class
3998definition looks as follows:
3999
4000\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00004001class DerivedClassName(BaseClassName):
4002 <statement-1>
4003 .
4004 .
4005 .
4006 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004007\end{verbatim}
4008
Fred Drake8842e861998-02-13 07:16:30 +00004009The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004010the derived class definition. Instead of a base class name, an
4011expression is also allowed. This is useful when the base class is
Fred Drakeed514942001-07-06 17:28:39 +00004012defined in another module,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004013
4014\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00004015class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004016\end{verbatim}
4017
4018Execution of a derived class definition proceeds the same as for a
4019base class. When the class object is constructed, the base class is
4020remembered. This is used for resolving attribute references: if a
4021requested attribute is not found in the class, it is searched in the
4022base class. This rule is applied recursively if the base class itself
4023is derived from some other class.
4024
4025There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00004026\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004027references are resolved as follows: the corresponding class attribute
4028is searched, descending down the chain of base classes if necessary,
4029and the method reference is valid if this yields a function object.
4030
4031Derived classes may override methods of their base classes. Because
4032methods have no special privileges when calling other methods of the
4033same object, a method of a base class that calls another method
4034defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00004035a derived class that overrides it. (For \Cpp{} programmers: all methods
Fred Drake20082d92000-04-03 04:26:58 +00004036in Python are effectively \keyword{virtual}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004037
4038An overriding method in a derived class may in fact want to extend
4039rather than simply replace the base class method of the same name.
4040There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00004041call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004042occasionally useful to clients as well. (Note that this only works if
4043the base class is defined or imported directly in the global scope.)
4044
4045
Fred Drakeb7833d31998-09-11 16:21:55 +00004046\subsection{Multiple Inheritance \label{multiple}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004047
Guido van Rossum6938f061994-08-01 12:22:53 +00004048Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004049class definition with multiple base classes looks as follows:
4050
4051\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00004052class DerivedClassName(Base1, Base2, Base3):
4053 <statement-1>
4054 .
4055 .
4056 .
4057 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004058\end{verbatim}
4059
4060The only rule necessary to explain the semantics is the resolution
4061rule used for class attribute references. This is depth-first,
4062left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00004063\class{DerivedClassName}, it is searched in \class{Base1}, then
4064(recursively) in the base classes of \class{Base1}, and only if it is
4065not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004066
Fred Drake8842e861998-02-13 07:16:30 +00004067(To some people breadth first --- searching \class{Base2} and
4068\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004069natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00004070attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004071one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00004072a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004073rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00004074\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004075
4076It is clear that indiscriminate use of multiple inheritance is a
4077maintenance nightmare, given the reliance in Python on conventions to
4078avoid accidental name conflicts. A well-known problem with multiple
4079inheritance is a class derived from two classes that happen to have a
4080common base class. While it is easy enough to figure out what happens
4081in this case (the instance will have a single copy of ``instance
4082variables'' or data attributes used by the common base class), it is
4083not clear that these semantics are in any way useful.
4084
4085
Fred Drakeb7833d31998-09-11 16:21:55 +00004086\section{Private Variables \label{private}}
Guido van Rossum02455691997-07-17 16:21:52 +00004087
Fred Drakea594baf1998-04-03 05:16:31 +00004088There is limited support for class-private
Guido van Rossum02455691997-07-17 16:21:52 +00004089identifiers. Any identifier of the form \code{__spam} (at least two
4090leading underscores, at most one trailing underscore) is now textually
4091replaced with \code{_classname__spam}, where \code{classname} is the
4092current class name with leading underscore(s) stripped. This mangling
4093is done without regard of the syntactic position of the identifier, so
4094it can be used to define class-private instance and class variables,
4095methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00004096private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00004097may occur when the mangled name would be longer than 255 characters.
4098Outside classes, or when the class name consists of only underscores,
4099no mangling occurs.
4100
4101Name mangling is intended to give classes an easy way to define
4102``private'' instance variables and methods, without having to worry
4103about instance variables defined by derived classes, or mucking with
4104instance variables by code outside the class. Note that the mangling
4105rules are designed mostly to avoid accidents; it still is possible for
4106a determined soul to access or modify a variable that is considered
Fred Drakeed514942001-07-06 17:28:39 +00004107private. This can even be useful in special circumstances, such as in
4108the debugger, and that's one reason why this loophole is not closed.
4109(Buglet: derivation of a class with the same name as the base class
4110makes use of private variables of the base class possible.)
Guido van Rossum02455691997-07-17 16:21:52 +00004111
4112Notice that code passed to \code{exec}, \code{eval()} or
4113\code{evalfile()} does not consider the classname of the invoking
4114class to be the current class; this is similar to the effect of the
4115\code{global} statement, the effect of which is likewise restricted to
4116code that is byte-compiled together. The same restriction applies to
4117\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
4118when referencing \code{__dict__} directly.
4119
Guido van Rossum02455691997-07-17 16:21:52 +00004120
Fred Drakeb7833d31998-09-11 16:21:55 +00004121\section{Odds and Ends \label{odds}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004122
4123Sometimes it is useful to have a data type similar to the Pascal
Fred Drakeee84d591999-03-10 17:25:30 +00004124``record'' or C ``struct'', bundling together a couple of named data
Fred Drakeed514942001-07-06 17:28:39 +00004125items. An empty class definition will do nicely:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004126
4127\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00004128class Employee:
4129 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004130
Fred Drake8842e861998-02-13 07:16:30 +00004131john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004132
Fred Drake8842e861998-02-13 07:16:30 +00004133# Fill the fields of the record
4134john.name = 'John Doe'
4135john.dept = 'computer lab'
4136john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004137\end{verbatim}
4138
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004139A piece of Python code that expects a particular abstract data type
4140can often be passed a class that emulates the methods of that data
4141type instead. For instance, if you have a function that formats some
4142data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00004143\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00004144buffer instead, and pass it as an argument.% (Unfortunately, this
4145%technique has its limitations: a class can't define operations that
4146%are accessed by special syntax such as sequence subscripting or
4147%arithmetic operators, and assigning such a ``pseudo-file'' to
4148%\code{sys.stdin} will not cause the interpreter to read further input
4149%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004150
4151
Fred Drake8842e861998-02-13 07:16:30 +00004152Instance method objects have attributes, too: \code{m.im_self} is the
4153object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00004154function object corresponding to the method.
4155
Raymond Hettingerfa6cce12003-07-11 18:58:11 +00004156
4157\section{Exceptions Are Classes Too\label{exceptionClasses}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00004158
Raymond Hettinger8ee00602003-07-01 06:19:34 +00004159User-defined exceptions are identified by classes as well. Using this
4160mechanism it is possible to create extensible hierarchies of exceptions.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004161
4162There are two new valid (semantic) forms for the raise statement:
4163
4164\begin{verbatim}
4165raise Class, instance
4166
4167raise instance
4168\end{verbatim}
4169
Fred Drake20082d92000-04-03 04:26:58 +00004170In the first form, \code{instance} must be an instance of
4171\class{Class} or of a class derived from it. The second form is a
4172shorthand for:
Guido van Rossum194e57c1995-02-15 15:51:38 +00004173
4174\begin{verbatim}
4175raise instance.__class__, instance
4176\end{verbatim}
4177
Raymond Hettinger8ee00602003-07-01 06:19:34 +00004178A class in an except clause is compatible with an exception if it is the same
Guido van Rossum194e57c1995-02-15 15:51:38 +00004179class or a base class thereof (but not the other way around --- an
4180except clause listing a derived class is not compatible with a base
4181class). For example, the following code will print B, C, D in that
4182order:
4183
4184\begin{verbatim}
4185class B:
4186 pass
4187class C(B):
4188 pass
4189class D(C):
4190 pass
4191
4192for c in [B, C, D]:
4193 try:
4194 raise c()
4195 except D:
4196 print "D"
4197 except C:
4198 print "C"
4199 except B:
4200 print "B"
4201\end{verbatim}
4202
Fred Drakeee84d591999-03-10 17:25:30 +00004203Note that if the except clauses were reversed (with
4204\samp{except B} first), it would have printed B, B, B --- the first
4205matching except clause is triggered.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004206
4207When an error message is printed for an unhandled exception which is a
4208class, the class name is printed, then a colon and a space, and
4209finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00004210\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004211
Guido van Rossum194e57c1995-02-15 15:51:38 +00004212
Raymond Hettingerfa6cce12003-07-11 18:58:11 +00004213\section{Iterators\label{iterators}}
4214
4215By now, you've probably noticed that most container objects can looped over
4216using a \code{for} statement:
4217
4218\begin{verbatim}
4219for element in [1, 2, 3]:
4220 print element
4221for element in (1, 2, 3):
4222 print element
4223for key in {'one':1, 'two':2}:
4224 print key
4225for char in "123":
4226 print char
4227for line in open("myfile.txt"):
4228 print line
4229\end{verbatim}
4230
4231This style of access is clear, concise, and convenient. The use of iterators
4232pervades and unifies Python. Behind the scenes, the \code{for} statement calls
4233\function{iter()} on the container object. The function returns an iterator
4234object that defines the method \method{next()} which accesses elements in the
4235container one at a time. When there are no more elements, \method{next()}
4236raises a \exception{StopIteration} exception which tells the \code{for} loop
4237to terminate. This example shows how it all works:
4238
4239\begin{verbatim}
4240>>> s = 'abc'
4241>>> it = iter(s)
4242>>> it
4243<iterator object at 0x00A1DB50>
4244>>> it.next()
4245'a'
4246>>> it.next()
4247'b'
4248>>> it.next()
4249'c'
4250>>> it.next()
4251
4252Traceback (most recent call last):
4253 File "<pyshell#6>", line 1, in -toplevel-
4254 it.next()
4255StopIteration
4256\end{verbatim}
4257
4258Having seen the mechanics behind the iterator protocol, it is easy to add
4259iterator behavior to your classes. Define a \method{__iter__()} method
4260which returns an object with a \method{next()} method. If the class defines
4261\method{next()}, then \method{__iter__()} can just return \code{self}:
4262
4263\begin{verbatim}
4264>>> class Reverse:
4265 "Iterator for looping over a sequence backwards"
4266 def __init__(self, data):
4267 self.data = data
4268 self.index = len(data)
4269 def __iter__(self):
4270 return self
4271 def next(self):
4272 if self.index == 0:
4273 raise StopIteration
4274 self.index = self.index - 1
4275 return self.data[self.index]
4276
4277>>> for char in Reverse('spam'):
4278 print char
4279
4280m
4281a
4282p
4283s
4284\end{verbatim}
4285
4286
4287\section{Generators\label{generators}}
4288
4289Generators are a simple and powerful tool for creating iterators. They are
4290written like regular functions but use the \keyword{yield} statement whenever
4291they want to return data. Each time the \method{next()} is called, the
4292generator resumes where it left-off (it remembers all the data values and
4293which statement was last executed). An example shows that generators can
4294be trivially easy to create:
4295
4296\begin{verbatim}
4297>>> def reverse(data):
4298 for index in range(len(data)-1, -1, -1):
4299 yield data[index]
4300
4301>>> for char in reverse('golf'):
4302 print char
4303
4304f
4305l
4306o
4307g
4308\end{verbatim}
4309
4310Anything that can be done with generators can also be done with class based
4311iterators as described in the previous section. What makes generators so
4312compact is that the \method{__iter__()} and \method{next()} methods are
4313created automatically.
4314
Raymond Hettingerb233e542003-07-15 23:16:01 +00004315Another key feature is that the local variables and execution state
Raymond Hettingerfa6cce12003-07-11 18:58:11 +00004316are automatically saved between calls. This made the function easier to write
4317and much more clear than an approach using class variables like
4318\code{self.index} and \code{self.data}.
4319
4320In addition to automatic method creation and saving program state, when
4321generators terminate, they automatically raise \exception{StopIteration}.
4322In combination, these features make it easy to create iterators with no
4323more effort than writing a regular function.
4324
4325
Fred Drakeb7833d31998-09-11 16:21:55 +00004326\chapter{What Now? \label{whatNow}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00004327
Fred Drake979d0412001-04-03 17:41:56 +00004328Reading this tutorial has probably reinforced your interest in using
4329Python --- you should be eager to apply Python to solve your
4330real-world problems. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00004331
Fred Drake979d0412001-04-03 17:41:56 +00004332You should read, or at least page through, the
4333\citetitle[../lib/lib.html]{Python Library Reference},
Guido van Rossum02455691997-07-17 16:21:52 +00004334which gives complete (though terse) reference material about types,
4335functions, and modules that can save you a lot of time when writing
4336Python programs. The standard Python distribution includes a
Fred Drakeee84d591999-03-10 17:25:30 +00004337\emph{lot} of code in both C and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00004338\UNIX{} mailboxes, retrieve documents via HTTP, generate random
4339numbers, parse command-line options, write CGI programs, compress
4340data, and a lot more; skimming through the Library Reference will give
4341you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004342
Fred Drake518e55c2000-07-27 20:55:12 +00004343The major Python Web site is \url{http://www.python.org/}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00004344code, documentation, and pointers to Python-related pages around the
Fred Drake17f690f2001-07-14 02:14:42 +00004345Web. This Web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00004346world, such as Europe, Japan, and Australia; a mirror may be faster
4347than the main site, depending on your geographical location. A more
Fred Drakec0fcbc11999-04-29 02:30:04 +00004348informal site is \url{http://starship.python.net/}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00004349bunch of Python-related personal home pages; many people have
Raymond Hettinger8ee00602003-07-01 06:19:34 +00004350downloadable software there. Many more user-created Python modules
4351can be found in a third-party repository at
4352\url{http://www.vex.net/parnassus}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004353
Guido van Rossum02455691997-07-17 16:21:52 +00004354For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00004355newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
Fred Drake518e55c2000-07-27 20:55:12 +00004356list at \email{python-list@python.org}. The newsgroup and mailing list
Fred Drake391564f1998-04-01 23:11:56 +00004357are gatewayed, so messages posted to one will automatically be
Raymond Hettinger8ee00602003-07-01 06:19:34 +00004358forwarded to the other. There are around 120 postings a day (with peaks
4359up to several hundred),
Fred Drake391564f1998-04-01 23:11:56 +00004360% Postings figure based on average of last six months activity as
Fred Drake518e55c2000-07-27 20:55:12 +00004361% reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182
4362% days = 116.9 msgs / day and steadily increasing.
Fred Drake391564f1998-04-01 23:11:56 +00004363asking (and answering) questions, suggesting new features, and
4364announcing new modules. Before posting, be sure to check the list of
4365Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00004366\url{http://www.python.org/doc/FAQ.html}, or look for it in the
Fred Drake518e55c2000-07-27 20:55:12 +00004367\file{Misc/} directory of the Python source distribution. Mailing
4368list archives are available at \url{http://www.python.org/pipermail/}.
4369The FAQ answers many of the questions that come up again and again,
4370and may already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004371
Guido van Rossum194e57c1995-02-15 15:51:38 +00004372
Fred Drakea594baf1998-04-03 05:16:31 +00004373\appendix
Guido van Rossum194e57c1995-02-15 15:51:38 +00004374
Fred Draked0c71372002-10-28 19:28:22 +00004375\chapter{Interactive Input Editing and History Substitution\label{interacting}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00004376
Guido van Rossum02455691997-07-17 16:21:52 +00004377Some versions of the Python interpreter support editing of the current
4378input line and history substitution, similar to facilities found in
4379the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00004380\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00004381editing. This library has its own documentation which I won't
Fred Drakecc09e8d1998-12-28 21:21:36 +00004382duplicate here; however, the basics are easily explained. The
4383interactive editing and history described here are optionally
4384available in the \UNIX{} and CygWin versions of the interpreter.
4385
4386This chapter does \emph{not} document the editing facilities of Mark
4387Hammond's PythonWin package or the Tk-based environment, IDLE,
4388distributed with Python. The command line history recall which
4389operates within DOS boxes on NT and some other DOS and Windows flavors
4390is yet another beast.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004391
Fred Drakeb7833d31998-09-11 16:21:55 +00004392\section{Line Editing \label{lineEditing}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00004393
Guido van Rossum02455691997-07-17 16:21:52 +00004394If supported, input line editing is active whenever the interpreter
4395prints a primary or secondary prompt. The current line can be edited
4396using the conventional Emacs control characters. The most important
Fred Drake5443c492000-07-08 05:18:54 +00004397of these are: \kbd{C-A} (Control-A) moves the cursor to the beginning
4398of the line, \kbd{C-E} to the end, \kbd{C-B} moves it one position to
4399the left, \kbd{C-F} to the right. Backspace erases the character to
4400the left of the cursor, \kbd{C-D} the character to its right.
4401\kbd{C-K} kills (erases) the rest of the line to the right of the
4402cursor, \kbd{C-Y} yanks back the last killed string.
4403\kbd{C-underscore} undoes the last change you made; it can be repeated
4404for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004405
Fred Drakeb7833d31998-09-11 16:21:55 +00004406\section{History Substitution \label{history}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00004407
Guido van Rossum02455691997-07-17 16:21:52 +00004408History substitution works as follows. All non-empty input lines
4409issued are saved in a history buffer, and when a new prompt is given
Fred Drake5443c492000-07-08 05:18:54 +00004410you are positioned on a new line at the bottom of this buffer.
4411\kbd{C-P} moves one line up (back) in the history buffer,
4412\kbd{C-N} moves one down. Any line in the history buffer can be
4413edited; an asterisk appears in front of the prompt to mark a line as
4414modified. Pressing the \kbd{Return} key passes the current line to
4415the interpreter. \kbd{C-R} starts an incremental reverse search;
4416\kbd{C-S} starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004417
Fred Drakeb7833d31998-09-11 16:21:55 +00004418\section{Key Bindings \label{keyBindings}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00004419
Guido van Rossum02455691997-07-17 16:21:52 +00004420The key bindings and some other parameters of the Readline library can
4421be customized by placing commands in an initialization file called
Fred Drake5443c492000-07-08 05:18:54 +00004422\file{\~{}/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00004423
Fred Drake8842e861998-02-13 07:16:30 +00004424\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00004425key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00004426\end{verbatim}
4427
Guido van Rossum02455691997-07-17 16:21:52 +00004428or
Guido van Rossum194e57c1995-02-15 15:51:38 +00004429
Fred Drake8842e861998-02-13 07:16:30 +00004430\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00004431"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00004432\end{verbatim}
4433
Guido van Rossum02455691997-07-17 16:21:52 +00004434and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00004435
Fred Drake8842e861998-02-13 07:16:30 +00004436\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00004437set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00004438\end{verbatim}
4439
Guido van Rossum02455691997-07-17 16:21:52 +00004440For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00004441
Fred Drake8842e861998-02-13 07:16:30 +00004442\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00004443# I prefer vi-style editing:
4444set editing-mode vi
Fred Drake5443c492000-07-08 05:18:54 +00004445
Guido van Rossum02455691997-07-17 16:21:52 +00004446# Edit using a single line:
4447set horizontal-scroll-mode On
Fred Drake5443c492000-07-08 05:18:54 +00004448
Guido van Rossum02455691997-07-17 16:21:52 +00004449# Rebind some keys:
4450Meta-h: backward-kill-word
4451"\C-u": universal-argument
4452"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00004453\end{verbatim}
4454
Fred Drake5443c492000-07-08 05:18:54 +00004455Note that the default binding for \kbd{Tab} in Python is to insert a
4456\kbd{Tab} character instead of Readline's default filename completion
4457function. If you insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00004458
Fred Drake8842e861998-02-13 07:16:30 +00004459\begin{verbatim}
Fred Drake5443c492000-07-08 05:18:54 +00004460Tab: complete
Fred Drake8842e861998-02-13 07:16:30 +00004461\end{verbatim}
4462
Fred Drake5443c492000-07-08 05:18:54 +00004463in your \file{\~{}/.inputrc}. (Of course, this makes it harder to
4464type indented continuation lines.)
Guido van Rossum194e57c1995-02-15 15:51:38 +00004465
Fred Drake72389881998-04-13 01:31:10 +00004466Automatic completion of variable and module names is optionally
4467available. To enable it in the interpreter's interactive mode, add
Fred Drake5443c492000-07-08 05:18:54 +00004468the following to your startup file:\footnote{
4469 Python will execute the contents of a file identified by the
4470 \envvar{PYTHONSTARTUP} environment variable when you start an
4471 interactive interpreter.}
Fred Drake20082d92000-04-03 04:26:58 +00004472\refstmodindex{rlcompleter}\refbimodindex{readline}
Fred Drake72389881998-04-13 01:31:10 +00004473
4474\begin{verbatim}
4475import rlcompleter, readline
4476readline.parse_and_bind('tab: complete')
4477\end{verbatim}
4478
Fred Drake01815522001-07-18 19:21:12 +00004479This binds the \kbd{Tab} key to the completion function, so hitting
4480the \kbd{Tab} key twice suggests completions; it looks at Python
4481statement names, the current local variables, and the available module
4482names. For dotted expressions such as \code{string.a}, it will
Raymond Hettingerc7a26562003-08-12 00:01:17 +00004483evaluate the expression up to the final \character{.} and then
Fred Drake01815522001-07-18 19:21:12 +00004484suggest completions from the attributes of the resulting object. Note
4485that this may execute application-defined code if an object with a
Fred Drake72389881998-04-13 01:31:10 +00004486\method{__getattr__()} method is part of the expression.
4487
Fred Drake01815522001-07-18 19:21:12 +00004488A more capable startup file might look like this example. Note that
4489this deletes the names it creates once they are no longer needed; this
4490is done since the startup file is executed in the same namespace as
4491the interactive commands, and removing the names avoids creating side
4492effects in the interactive environments. You may find it convenient
4493to keep some of the imported modules, such as \module{os}, which turn
4494out to be needed in most sessions with the interpreter.
4495
4496\begin{verbatim}
4497# Add auto-completion and a stored history file of commands to your Python
4498# interactive interpreter. Requires Python 2.0+, readline. Autocomplete is
4499# bound to the Esc key by default (you can change it - see readline docs).
4500#
4501# Store the file in ~/.pystartup, and set an environment variable to point
Raymond Hettingerfa6cce12003-07-11 18:58:11 +00004502# to it: "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash.
Fred Drake01815522001-07-18 19:21:12 +00004503#
4504# Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the
4505# full path to your home directory.
4506
4507import atexit
4508import os
4509import readline
4510import rlcompleter
4511
4512historyPath = os.path.expanduser("~/.pyhistory")
4513
4514def save_history(historyPath=historyPath):
4515 import readline
4516 readline.write_history_file(historyPath)
4517
4518if os.path.exists(historyPath):
4519 readline.read_history_file(historyPath)
4520
4521atexit.register(save_history)
4522del os, atexit, readline, rlcompleter, save_history, historyPath
4523\end{verbatim}
4524
Fred Drake72389881998-04-13 01:31:10 +00004525
Fred Drakeb7833d31998-09-11 16:21:55 +00004526\section{Commentary \label{commentary}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00004527
Fred Drake5443c492000-07-08 05:18:54 +00004528This facility is an enormous step forward compared to earlier versions
4529of the interpreter; however, some wishes are left: It would be nice if
4530the proper indentation were suggested on continuation lines (the
4531parser knows if an indent token is required next). The completion
4532mechanism might use the interpreter's symbol table. A command to
4533check (or even suggest) matching parentheses, quotes, etc., would also
4534be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00004535
Guido van Rossum97662c81996-08-23 15:35:47 +00004536
Fred Draked0c71372002-10-28 19:28:22 +00004537\chapter{Floating Point Arithmetic: Issues and Limitations\label{fp-issues}}
4538\sectionauthor{Tim Peters}{tim_one@email.msn.com}
Fred Drake417d6672001-06-08 16:24:58 +00004539
4540Floating-point numbers are represented in computer hardware as
4541base 2 (binary) fractions. For example, the decimal fraction
4542
4543\begin{verbatim}
45440.125
4545\end{verbatim}
4546
4547has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction
4548
4549\begin{verbatim}
45500.001
4551\end{verbatim}
4552
4553has value 0/2 + 0/4 + 1/8. These two fractions have identical values,
4554the only real difference being that the first is written in base 10
4555fractional notation, and the second in base 2.
4556
4557Unfortunately, most decimal fractions cannot be represented exactly as
4558binary fractions. A consequence is that, in general, the decimal
4559floating-point numbers you enter are only approximated by the binary
4560floating-point numbers actually stored in the machine.
4561
4562The problem is easier to understand at first in base 10. Consider the
4563fraction 1/3. You can approximate that as a base 10 fraction:
4564
4565\begin{verbatim}
45660.3
4567\end{verbatim}
4568
4569or, better,
4570
4571\begin{verbatim}
45720.33
4573\end{verbatim}
4574
4575or, better,
4576
4577\begin{verbatim}
45780.333
4579\end{verbatim}
4580
4581and so on. No matter how many digits you're willing to write down, the
4582result will never be exactly 1/3, but will be an increasingly better
4583approximation to 1/3.
4584
4585In the same way, no matter how many base 2 digits you're willing to
4586use, the decimal value 0.1 cannot be represented exactly as a base 2
4587fraction. In base 2, 1/10 is the infinitely repeating fraction
4588
4589\begin{verbatim}
45900.0001100110011001100110011001100110011001100110011...
4591\end{verbatim}
4592
4593Stop at any finite number of bits, and you get an approximation. This
4594is why you see things like:
4595
4596\begin{verbatim}
4597>>> 0.1
45980.10000000000000001
4599\end{verbatim}
4600
4601On most machines today, that is what you'll see if you enter 0.1 at
4602a Python prompt. You may not, though, because the number of bits
4603used by the hardware to store floating-point values can vary across
4604machines, and Python only prints a decimal approximation to the true
4605decimal value of the binary approximation stored by the machine. On
4606most machines, if Python were to print the true decimal value of
4607the binary approximation stored for 0.1, it would have to display
4608
4609\begin{verbatim}
4610>>> 0.1
46110.1000000000000000055511151231257827021181583404541015625
4612\end{verbatim}
4613
4614instead! The Python prompt (implicitly) uses the builtin
4615\function{repr()} function to obtain a string version of everything it
4616displays. For floats, \code{repr(\var{float})} rounds the true
4617decimal value to 17 significant digits, giving
4618
4619\begin{verbatim}
46200.10000000000000001
4621\end{verbatim}
4622
4623\code{repr(\var{float})} produces 17 significant digits because it
4624turns out that's enough (on most machines) so that
4625\code{eval(repr(\var{x})) == \var{x}} exactly for all finite floats
4626\var{x}, but rounding to 16 digits is not enough to make that true.
4627
4628Note that this is in the very nature of binary floating-point: this is
4629not a bug in Python, it is not a bug in your code either, and you'll
4630see the same kind of thing in all languages that support your
Tim Petersfa9e2732001-06-17 21:57:17 +00004631hardware's floating-point arithmetic (although some languages may
4632not \emph{display} the difference by default, or in all output modes).
Fred Drake417d6672001-06-08 16:24:58 +00004633
4634Python's builtin \function{str()} function produces only 12
4635significant digits, and you may wish to use that instead. It's
4636unusual for \code{eval(str(\var{x}))} to reproduce \var{x}, but the
4637output may be more pleasant to look at:
4638
4639\begin{verbatim}
4640>>> print str(0.1)
46410.1
4642\end{verbatim}
4643
4644It's important to realize that this is, in a real sense, an illusion:
4645the value in the machine is not exactly 1/10, you're simply rounding
4646the \emph{display} of the true machine value.
4647
4648Other surprises follow from this one. For example, after seeing
4649
4650\begin{verbatim}
4651>>> 0.1
46520.10000000000000001
4653\end{verbatim}
4654
4655you may be tempted to use the \function{round()} function to chop it
4656back to the single digit you expect. But that makes no difference:
4657
4658\begin{verbatim}
4659>>> round(0.1, 1)
46600.10000000000000001
4661\end{verbatim}
4662
4663The problem is that the binary floating-point value stored for "0.1"
4664was already the best possible binary approximation to 1/10, so trying
4665to round it again can't make it better: it was already as good as it
4666gets.
4667
4668Another consequence is that since 0.1 is not exactly 1/10, adding 0.1
4669to itself 10 times may not yield exactly 1.0, either:
4670
4671\begin{verbatim}
4672>>> sum = 0.0
4673>>> for i in range(10):
4674... sum += 0.1
4675...
4676>>> sum
46770.99999999999999989
4678\end{verbatim}
4679
4680Binary floating-point arithmetic holds many surprises like this. The
4681problem with "0.1" is explained in precise detail below, in the
4682"Representation Error" section. See
4683\citetitle[http://www.lahey.com/float.htm]{The Perils of Floating
4684Point} for a more complete account of other common surprises.
4685
4686As that says near the end, ``there are no easy answers.'' Still,
4687don't be unduly wary of floating-point! The errors in Python float
4688operations are inherited from the floating-point hardware, and on most
4689machines are on the order of no more than 1 part in 2**53 per
4690operation. That's more than adequate for most tasks, but you do need
4691to keep in mind that it's not decimal arithmetic, and that every float
4692operation can suffer a new rounding error.
4693
4694While pathological cases do exist, for most casual use of
4695floating-point arithmetic you'll see the result you expect in the end
4696if you simply round the display of your final results to the number of
4697decimal digits you expect. \function{str()} usually suffices, and for
4698finer control see the discussion of Pythons's \code{\%} format
4699operator: the \code{\%g}, \code{\%f} and \code{\%e} format codes
4700supply flexible and easy ways to round float results for display.
4701
4702
4703\section{Representation Error
4704 \label{fp-error}}
4705
4706This section explains the ``0.1'' example in detail, and shows how
4707you can perform an exact analysis of cases like this yourself. Basic
4708familiarity with binary floating-point representation is assumed.
4709
4710\dfn{Representation error} refers to that some (most, actually)
4711decimal fractions cannot be represented exactly as binary (base 2)
4712fractions. This is the chief reason why Python (or Perl, C, \Cpp,
4713Java, Fortran, and many others) often won't display the exact decimal
4714number you expect:
4715
4716\begin{verbatim}
4717>>> 0.1
47180.10000000000000001
4719\end{verbatim}
4720
4721Why is that? 1/10 is not exactly representable as a binary fraction.
4722Almost all machines today (November 2000) use IEEE-754 floating point
4723arithmetic, and almost all platforms map Python floats to IEEE-754
4724"double precision". 754 doubles contain 53 bits of precision, so on
4725input the computer strives to convert 0.1 to the closest fraction it can
4726of the form \var{J}/2**\var{N} where \var{J} is an integer containing
4727exactly 53 bits. Rewriting
4728
4729\begin{verbatim}
4730 1 / 10 ~= J / (2**N)
4731\end{verbatim}
4732
4733as
4734
4735\begin{verbatim}
4736J ~= 2**N / 10
4737\end{verbatim}
4738
4739and recalling that \var{J} has exactly 53 bits (is \code{>= 2**52} but
4740\code{< 2**53}), the best value for \var{N} is 56:
4741
4742\begin{verbatim}
4743>>> 2L**52
47444503599627370496L
4745>>> 2L**53
47469007199254740992L
4747>>> 2L**56/10
47487205759403792793L
4749\end{verbatim}
4750
4751That is, 56 is the only value for \var{N} that leaves \var{J} with
4752exactly 53 bits. The best possible value for \var{J} is then that
4753quotient rounded:
4754
4755\begin{verbatim}
4756>>> q, r = divmod(2L**56, 10)
4757>>> r
47586L
4759\end{verbatim}
4760
4761Since the remainder is more than half of 10, the best approximation is
4762obtained by rounding up:
4763
4764\begin{verbatim}
4765>>> q+1
47667205759403792794L
4767\end{verbatim}
4768
4769Therefore the best possible approximation to 1/10 in 754 double
4770precision is that over 2**56, or
4771
4772\begin{verbatim}
47737205759403792794 / 72057594037927936
4774\end{verbatim}
4775
4776Note that since we rounded up, this is actually a little bit larger than
47771/10; if we had not rounded up, the quotient would have been a little
Tim Petersfa9e2732001-06-17 21:57:17 +00004778bit smaller than 1/10. But in no case can it be \emph{exactly} 1/10!
Fred Drake417d6672001-06-08 16:24:58 +00004779
4780So the computer never ``sees'' 1/10: what it sees is the exact
4781fraction given above, the best 754 double approximation it can get:
4782
4783\begin{verbatim}
4784>>> .1 * 2L**56
47857205759403792794.0
4786\end{verbatim}
4787
4788If we multiply that fraction by 10**30, we can see the (truncated)
4789value of its 30 most significant decimal digits:
4790
4791\begin{verbatim}
4792>>> 7205759403792794L * 10L**30 / 2L**56
4793100000000000000005551115123125L
4794\end{verbatim}
4795
4796meaning that the exact number stored in the computer is approximately
4797equal to the decimal value 0.100000000000000005551115123125. Rounding
4798that to 17 significant digits gives the 0.10000000000000001 that Python
4799displays (well, will display on any 754-conforming platform that does
4800best-possible input and output conversions in its C library --- yours may
4801not!).
4802
Fred Draked5df09c2001-06-20 21:37:34 +00004803\chapter{History and License}
4804\input{license}
4805
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004806\end{document}