blob: 13272b999c80b80bc3b72550cbd2e280d764a058 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002
Guido van Rossum02455691997-07-17 16:21:52 +00003% Things to do:
4% Add a section on file I/O
5% Write a chapter entitled ``Some Useful Modules''
6% --regex, math+cmath
7% Should really move the Python startup file info to an appendix
Guido van Rossum02455691997-07-17 16:21:52 +00008
Guido van Rossumdccc2981997-12-30 04:40:25 +00009\title{Python Tutorial}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010
Guido van Rossum16cd7f91994-10-06 10:29:26 +000011\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +000012
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000013\begin{document}
14
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000015\maketitle
16
Fred Drake9f86b661998-07-28 21:55:19 +000017\ifhtml
18\chapter*{Front Matter\label{front}}
19\fi
20
Guido van Rossum16cd7f91994-10-06 10:29:26 +000021\input{copyright}
22
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023\begin{abstract}
24
25\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000026Python is an easy to learn, powerful programming language. It has
27efficient high-level data structures and a simple but effective
28approach to object-oriented programming. Python's elegant syntax and
29dynamic typing, together with its interpreted nature, make it an ideal
30language for scripting and rapid application development in many areas
31on most platforms.
32
33The Python interpreter and the extensive standard library are freely
34available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000035Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000036distributed. The same site also contains distributions of and
37pointers to many free third party Python modules, programs and tools,
38and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000039
Guido van Rossum4410c751991-06-04 20:22:18 +000040The Python interpreter is easily extended with new functions and data
Fred Drakeee84d591999-03-10 17:25:30 +000041types implemented in C or \Cpp{} (or other languages callable from C).
Guido van Rossumdccc2981997-12-30 04:40:25 +000042Python is also suitable as an extension language for customizable
43applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000044
Guido van Rossum6fc178f1991-08-16 09:13:42 +000045This tutorial introduces the reader informally to the basic concepts
46and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000047Python interpreter handy for hands-on experience, but all examples are
48self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000049
Guido van Rossumdccc2981997-12-30 04:40:25 +000050For a description of standard objects and modules, see the
51\emph{Python Library Reference} document. The \emph{Python Reference
52Manual} gives a more formal definition of the language. To write
Fred Drakeee84d591999-03-10 17:25:30 +000053extensions in C or \Cpp{}, read the \emph{Extending and Embedding} and
54\emph{Python/C API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000055Python in depth.
56
57This tutorial does not attempt to be comprehensive and cover every
58single feature, or even every commonly used feature. Instead, it
59introduces many of Python's most noteworthy features, and will give
60you a good idea of the language's flavor and style. After reading it,
61you will be able to read and write Python modules and programs, and
62you will be ready to learn more about the various Python library
63modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000064
65\end{abstract}
66
Fred Drake4d4f9e71998-01-13 22:25:02 +000067\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000068
Guido van Rossum5e0759d1992-08-07 16:06:24 +000069
Fred Drakeb7833d31998-09-11 16:21:55 +000070\chapter{Whetting Your Appetite \label{intro}}
Guido van Rossum3a26dd81996-10-24 22:12:48 +000071
Guido van Rossum6fc178f1991-08-16 09:13:42 +000072If you ever wrote a large shell script, you probably know this
73feeling: you'd love to add yet another feature, but it's already so
74slow, and so big, and so complicated; or the feature involves a system
Fred Drakeee84d591999-03-10 17:25:30 +000075call or other function that is only accessible from C \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000076the problem at hand isn't serious enough to warrant rewriting the
Fred Drakeee84d591999-03-10 17:25:30 +000077script in C; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000078other data types (like sorted lists of file names) that are easy in
Fred Drakeee84d591999-03-10 17:25:30 +000079the shell but lots of work to implement in C, or perhaps you're not
80sufficiently familiar with C.
Guido van Rossum02455691997-07-17 16:21:52 +000081
Fred Drakeee84d591999-03-10 17:25:30 +000082Another situation: perhaps you have to work with several C libraries,
83and the usual C write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000084need to develop software more quickly. Possibly perhaps you've
85written a program that could use an extension language, and you don't
86want to design a language, write and debug an interpreter for it, then
87tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000088
Guido van Rossum6fc178f1991-08-16 09:13:42 +000089In such cases, Python may be just the language for you. Python is
90simple to use, but it is a real programming language, offering much
91more structure and support for large programs than the shell has. On
Fred Drakeee84d591999-03-10 17:25:30 +000092the other hand, it also offers much more error checking than C, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000093being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000094built in, such as flexible arrays and dictionaries that would cost you
Fred Drakeee84d591999-03-10 17:25:30 +000095days to implement efficiently in C. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000096types Python is applicable to a much larger problem domain than
97\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
98in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000099
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000100Python allows you to split up your program in modules that can be
101reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000102standard modules that you can use as the basis of your programs --- or
103as examples to start learning to program in Python. There are also
104built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000105sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000106
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000107Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000108during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000109necessary. The interpreter can be used interactively, which makes it
110easy to experiment with features of the language, to write throw-away
111programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000112It is also a handy desk calculator.
113
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000114Python allows writing very compact and readable programs. Programs
Fred Drakeee84d591999-03-10 17:25:30 +0000115written in Python are typically much shorter than equivalent C
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000116programs, for several reasons:
117\begin{itemize}
118\item
119the high-level data types allow you to express complex operations in a
120single statement;
121\item
122statement grouping is done by indentation instead of begin/end
123brackets;
124\item
125no variable or argument declarations are necessary.
126\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000127
Fred Drakeee84d591999-03-10 17:25:30 +0000128Python is \emph{extensible}: if you know how to program in C it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000129to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000130perform critical operations at maximum speed, or to link Python
131programs to libraries that may only be available in binary form (such
132as a vendor-specific graphics library). Once you are really hooked,
Fred Drakeee84d591999-03-10 17:25:30 +0000133you can link the Python interpreter into an application written in C
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000134and use it as an extension or command language for that application.
135
Guido van Rossum02455691997-07-17 16:21:52 +0000136By the way, the language is named after the BBC show ``Monty Python's
137Flying Circus'' and has nothing to do with nasty reptiles. Making
138references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000139it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000140
Fred Drakeb7833d31998-09-11 16:21:55 +0000141\section{Where From Here \label{where}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000142
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000143Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000144in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000145using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000146
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000147In the next chapter, the mechanics of using the interpreter are
148explained. This is rather mundane information, but essential for
149trying out the examples shown later.
150
Guido van Rossum4410c751991-06-04 20:22:18 +0000151The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000152language and system though examples, beginning with simple
153expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000154and finally touching upon advanced concepts like exceptions
155and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000156
Fred Drakeb7833d31998-09-11 16:21:55 +0000157\chapter{Using the Python Interpreter \label{using}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000158
Fred Drakeb7833d31998-09-11 16:21:55 +0000159\section{Invoking the Interpreter \label{invoking}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000160
Fred Drakeeee08cd1997-12-04 15:43:15 +0000161The Python interpreter is usually installed as \file{/usr/local/bin/python}
162on those machines where it is available; putting \file{/usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000163your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000164typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000165
Fred Drake8842e861998-02-13 07:16:30 +0000166\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000167python
Fred Drake8842e861998-02-13 07:16:30 +0000168\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000169
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000170to the shell. Since the choice of the directory where the interpreter
171lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000172your local Python guru or system administrator. (E.g.,
173\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000174
Guido van Rossuma8a1b9b1998-06-22 14:28:39 +0000175Typing an EOF character (Control-D on \UNIX{}, Control-Z on DOS
Guido van Rossum02455691997-07-17 16:21:52 +0000176or Windows) at the primary prompt causes the interpreter to exit with
177a zero exit status. If that doesn't work, you can exit the
Fred Drake8842e861998-02-13 07:16:30 +0000178interpreter by typing the following commands: \samp{import sys;
Guido van Rossum02455691997-07-17 16:21:52 +0000179sys.exit()}.
180
181The interpreter's line-editing features usually aren't very
Fred Drake3f205921998-01-13 18:56:38 +0000182sophisticated. On \UNIX{}, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000183enabled support for the GNU readline library, which adds more
184elaborate interactive editing and history features. Perhaps the
185quickest check to see whether command line editing is supported is
186typing Control-P to the first Python prompt you get. If it beeps, you
187have command line editing; see Appendix A for an introduction to the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000188keys. If nothing appears to happen, or if \code{\^P} is echoed,
Guido van Rossum02455691997-07-17 16:21:52 +0000189command line editing isn't available; you'll only be able to use
190backspace to remove characters from the current line.
191
Fred Drake6dc2aae1996-12-13 21:56:03 +0000192The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000193with standard input connected to a tty device, it reads and executes
194commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000195a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000196that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000197
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000198A third way of starting the interpreter is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000199\samp{python -c command [arg] ...}, which
200executes the statement(s) in \code{command}, analogous to the shell's
201\code{-c} option. Since Python statements often contain spaces or other
202characters that are special to the shell, it is best to quote
203\code{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000204
Fred Drakeeee08cd1997-12-04 15:43:15 +0000205Note that there is a difference between \samp{python file} and
206\samp{python <file}. In the latter case, input requests from the
207program, such as calls to \code{input()} and \code{raw_input()}, are
208satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000209until the end by the parser before the program starts executing, the
210program will encounter EOF immediately. In the former case (which is
211usually what you want) they are satisfied from whatever file or device
212is connected to standard input of the Python interpreter.
213
Guido van Rossumb2c65561993-05-12 08:53:36 +0000214When a script file is used, it is sometimes useful to be able to run
215the script and enter interactive mode afterwards. This can be done by
Fred Drakeeee08cd1997-12-04 15:43:15 +0000216passing \code{-i} before the script. (This does not work if the script
Guido van Rossumb2c65561993-05-12 08:53:36 +0000217is read from standard input, for the same reason as explained in the
218previous paragraph.)
219
Fred Drakeb7833d31998-09-11 16:21:55 +0000220\subsection{Argument Passing \label{argPassing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000221
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000222When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000223arguments thereafter are passed to the script in the variable
224\code{sys.argv}, which is a list of strings. Its length is at least
225one; when no script and no arguments are given, \code{sys.argv[0]} is
226an empty string. When the script name is given as \code{'-'} (meaning
227standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c
228command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options
229found after \code{-c command} are not consumed by the Python
230interpreter's option processing but left in \code{sys.argv} for the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000231command to handle.
232
Fred Drakeb7833d31998-09-11 16:21:55 +0000233\subsection{Interactive Mode \label{interactive}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000234
Guido van Rossumdd010801991-06-07 14:31:11 +0000235When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000236\emph{interactive mode}. In this mode it prompts for the next command
237with the \emph{primary prompt}, usually three greater-than signs
Fred Drake8842e861998-02-13 07:16:30 +0000238(\samp{>>> }); for continuation lines it prompts with the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000239\emph{secondary prompt},
Fred Drake8842e861998-02-13 07:16:30 +0000240by default three dots (\samp{... }).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000241
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000242The interpreter prints a welcome message stating its version number
243and a copyright notice before printing the first prompt, e.g.:
244
Fred Drake8842e861998-02-13 07:16:30 +0000245\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000246python
Fred Drakeee84d591999-03-10 17:25:30 +0000247Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Fred Drakeeee08cd1997-12-04 15:43:15 +0000248Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000249>>>
Fred Drake8842e861998-02-13 07:16:30 +0000250\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000251
Fred Drakeb7833d31998-09-11 16:21:55 +0000252\section{The Interpreter and Its Environment \label{interp}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000253
Fred Drakeb7833d31998-09-11 16:21:55 +0000254\subsection{Error Handling \label{error}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000255
256When an error occurs, the interpreter prints an error
257message and a stack trace. In interactive mode, it then returns to
258the primary prompt; when input came from a file, it exits with a
259nonzero exit status after printing
Fred Drakeeee08cd1997-12-04 15:43:15 +0000260the stack trace. (Exceptions handled by an \code{except} clause in a
261\code{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000262unconditionally fatal and cause an exit with a nonzero exit; this
263applies to internal inconsistencies and some cases of running out of
264memory. All error messages are written to the standard error stream;
265normal output from the executed commands is written to standard
266output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000267
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000268Typing the interrupt character (usually Control-C or DEL) to the
269primary or secondary prompt cancels the input and returns to the
Fred Drake93aa0f21999-04-05 21:39:17 +0000270primary prompt.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000271 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000272}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000273Typing an interrupt while a command is executing raises the
274\code{KeyboardInterrupt} exception, which may be handled by a
275\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000276
Fred Drakeb7833d31998-09-11 16:21:55 +0000277\subsection{Executable Python Scripts \label{scripts}}
Guido van Rossum4410c751991-06-04 20:22:18 +0000278
Fred Drake6dc2aae1996-12-13 21:56:03 +0000279On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000280executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000281
Fred Drake8842e861998-02-13 07:16:30 +0000282\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000283#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000284\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000285
Fred Drake391564f1998-04-01 23:11:56 +0000286(assuming that the interpreter is on the user's \envvar{PATH}) at the
287beginning of the script and giving the file an executable mode. The
288\samp{\#!} must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000289
Fred Drakeb7833d31998-09-11 16:21:55 +0000290\subsection{The Interactive Startup File \label{startup}}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000291
Fred Drake8842e861998-02-13 07:16:30 +0000292% XXX This should probably be dumped in an appendix, since most people
293% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000294
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000295When you use Python interactively, it is frequently handy to have some
296standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000297can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000298\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drakeeee08cd1997-12-04 15:43:15 +0000299commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000300shells.
301
302This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000303commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000304explicit source of commands (which otherwise behaves like an
305interactive session). It is executed in the same name space where
306interactive commands are executed, so that objects that it defines or
307imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000308You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000309this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000310
311If you want to read an additional start-up file from the current
Fred Drake72389881998-04-13 01:31:10 +0000312directory, you can program this in the global start-up file,
Fred Drakeee84d591999-03-10 17:25:30 +0000313e.g.\ \samp{execfile('.pythonrc.py')}\indexii{.pythonrc.py}{file}. If
Fred Drake72389881998-04-13 01:31:10 +0000314you want to use the startup file in a script, you must do this
315explicitly in the script:
Fred Drake8842e861998-02-13 07:16:30 +0000316
317\begin{verbatim}
318import os
Fred Drakeee84d591999-03-10 17:25:30 +0000319if os.environ.get('PYTHONSTARTUP') \
320 and os.path.isfile(os.environ['PYTHONSTARTUP']):
Fred Drake72389881998-04-13 01:31:10 +0000321 execfile(os.environ['PYTHONSTARTUP'])
Fred Drake8842e861998-02-13 07:16:30 +0000322\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000323
Fred Drake72389881998-04-13 01:31:10 +0000324
Fred Drakeb7833d31998-09-11 16:21:55 +0000325\chapter{An Informal Introduction to Python \label{informal}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000326
327In the following examples, input and output are distinguished by the
Fred Drake8842e861998-02-13 07:16:30 +0000328presence or absence of prompts (\samp{>>> } and \samp{... }): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000329the example, you must type everything after the prompt, when the
330prompt appears; lines that do not begin with a prompt are output from
331the interpreter.%
Guido van Rossum02455691997-07-17 16:21:52 +0000332%\footnote{
333% I'd prefer to use different fonts to distinguish input
334% from output, but the amount of LaTeX hacking that would require
335% is currently beyond my ability.
336%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000337Note that a secondary prompt on a line by itself in an example means
338you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000339
Fred Drakeb7833d31998-09-11 16:21:55 +0000340\section{Using Python as a Calculator \label{calculator}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000341
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000342Let's try some simple Python commands. Start the interpreter and wait
Fred Drake8842e861998-02-13 07:16:30 +0000343for the primary prompt, \samp{>>> }. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000344
Fred Drakeb7833d31998-09-11 16:21:55 +0000345\subsection{Numbers \label{numbers}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000346
347The interpreter acts as a simple calculator: you can type an
348expression at it and it will write the value. Expression syntax is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000349straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/}
Fred Drakeee84d591999-03-10 17:25:30 +0000350work just like in most other languages (e.g., Pascal or C); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000351can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000352
Fred Drake8842e861998-02-13 07:16:30 +0000353\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000354>>> 2+2
3554
Guido van Rossum6938f061994-08-01 12:22:53 +0000356>>> # This is a comment
357... 2+2
3584
359>>> 2+2 # and a comment on the same line as code
3604
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000361>>> (50-5*6)/4
3625
Guido van Rossum6938f061994-08-01 12:22:53 +0000363>>> # Integer division returns the floor:
364... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003652
Guido van Rossum6938f061994-08-01 12:22:53 +0000366>>> 7/-3
367-3
Fred Drake8842e861998-02-13 07:16:30 +0000368\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000369
Fred Drakeee84d591999-03-10 17:25:30 +0000370Like in C, the equal sign (\character{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000371variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000372
Fred Drake8842e861998-02-13 07:16:30 +0000373\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000374>>> width = 20
375>>> height = 5*9
376>>> width * height
377900
Fred Drake8842e861998-02-13 07:16:30 +0000378\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000379%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000380A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000381
Fred Drake8842e861998-02-13 07:16:30 +0000382\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000383>>> x = y = z = 0 # Zero x, y and z
384>>> x
3850
386>>> y
3870
388>>> z
3890
Fred Drake8842e861998-02-13 07:16:30 +0000390\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000391%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000392There is full support for floating point; operators with mixed type
393operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000394
Fred Drake8842e861998-02-13 07:16:30 +0000395\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000396>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003973.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000398>>> 7.0 / 2
3993.5
Fred Drake8842e861998-02-13 07:16:30 +0000400\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000401%
402Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000403a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
404real component are written as \samp{(\var{real}+\var{imag}j)}, or can
405be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000406
Fred Drake8842e861998-02-13 07:16:30 +0000407\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000408>>> 1j * 1J
409(-1+0j)
410>>> 1j * complex(0,1)
411(-1+0j)
412>>> 3+1j*3
413(3+3j)
414>>> (3+1j)*3
415(9+3j)
416>>> (1+2j)/(1+1j)
417(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000418\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000419%
420Complex numbers are always represented as two floating point numbers,
421the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000422number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000423
Fred Drake8842e861998-02-13 07:16:30 +0000424\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000425>>> a=1.5+0.5j
426>>> a.real
4271.5
428>>> a.imag
4290.5
Fred Drake8842e861998-02-13 07:16:30 +0000430\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000431%
432The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000433(\function{float()}, \function{int()} and \function{long()}) don't
434work for complex numbers --- there is no one correct way to convert a
435complex number to a real number. Use \code{abs(\var{z})} to get its
436magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000437
Fred Drake8842e861998-02-13 07:16:30 +0000438\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000439>>> a=1.5+0.5j
440>>> float(a)
441Traceback (innermost last):
442 File "<stdin>", line 1, in ?
443TypeError: can't convert complex to float; use e.g. abs(z)
444>>> a.real
4451.5
446>>> abs(a)
4471.58113883008
Fred Drake8842e861998-02-13 07:16:30 +0000448\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000449%
450In interactive mode, the last printed expression is assigned to the
451variable \code{_}. This means that when you are using Python as a
452desk calculator, it is somewhat easier to continue calculations, for
453example:
454
455\begin{verbatim}
456>>> tax = 17.5 / 100
457>>> price = 3.50
458>>> price * tax
4590.6125
460>>> price + _
4614.1125
462>>> round(_, 2)
4634.11
464\end{verbatim}
465
466This variable should be treated as read-only by the user. Don't
467explicitly assign a value to it --- you would create an independent
468local variable with the same name masking the built-in variable with
469its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000470
Fred Drakeb7833d31998-09-11 16:21:55 +0000471\subsection{Strings \label{strings}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000472
Guido van Rossum02455691997-07-17 16:21:52 +0000473Besides numbers, Python can also manipulate strings, which can be
474expressed in several ways. They can be enclosed in single quotes or
475double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000476
Fred Drake8842e861998-02-13 07:16:30 +0000477\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000478>>> 'spam eggs'
479'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000480>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000481"doesn't"
482>>> "doesn't"
483"doesn't"
484>>> '"Yes," he said.'
485'"Yes," he said.'
486>>> "\"Yes,\" he said."
487'"Yes," he said.'
488>>> '"Isn\'t," she said.'
489'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000490\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000491
Fred Drake8842e861998-02-13 07:16:30 +0000492String literals can span multiple lines in several ways. Newlines can
493be escaped with backslashes, e.g.:
Guido van Rossum02455691997-07-17 16:21:52 +0000494
495\begin{verbatim}
496hello = "This is a rather long string containing\n\
497several lines of text just as you would do in C.\n\
498 Note that whitespace at the beginning of the line is\
499 significant.\n"
500print hello
501\end{verbatim}
502
503which would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000504
Guido van Rossum02455691997-07-17 16:21:52 +0000505\begin{verbatim}
506This is a rather long string containing
507several lines of text just as you would do in C.
508 Note that whitespace at the beginning of the line is significant.
509\end{verbatim}
510
511Or, strings can be surrounded in a pair of matching triple-quotes:
512\code{"""} or \code {'''}. End of lines do not need to be escaped
513when using triple-quotes, but they will be included in the string.
514
515\begin{verbatim}
516print """
517Usage: thingy [OPTIONS]
518 -h Display this usage message
519 -H hostname Hostname to connect to
520"""
521\end{verbatim}
522
523produces the following output:
524
Fred Drake8842e861998-02-13 07:16:30 +0000525\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000526Usage: thingy [OPTIONS]
527 -h Display this usage message
528 -H hostname Hostname to connect to
Fred Drake8842e861998-02-13 07:16:30 +0000529\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000530
Guido van Rossum02455691997-07-17 16:21:52 +0000531The interpreter prints the result of string operations in the same way
532as they are typed for input: inside quotes, and with quotes and other
533funny characters escaped by backslashes, to show the precise
534value. The string is enclosed in double quotes if the string contains
535a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000536quotes. (The \keyword{print} statement, described later, can be used
537to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000538
Fred Drakeeee08cd1997-12-04 15:43:15 +0000539Strings can be concatenated (glued together) with the \code{+}
540operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000541
Fred Drake8842e861998-02-13 07:16:30 +0000542\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000543>>> word = 'Help' + 'A'
544>>> word
545'HelpA'
546>>> '<' + word*5 + '>'
547'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000548\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000549
Guido van Rossum02455691997-07-17 16:21:52 +0000550Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000551the first line above could also have been written \samp{word = 'Help'
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000552'A'}; this only works with two literals, not with arbitrary string
553expressions:
554
555\begin{verbatim}
556>>> 'str' 'ing' # <- This is ok
557'string'
558>>> string.strip('str') + 'ing' # <- This is ok
559'string'
560>>> string.strip('str') 'ing' # <- This is invalid
561 File "<stdin>", line 1
562 string.strip('str') 'ing'
563 ^
564SyntaxError: invalid syntax
565\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000566
Fred Drakeee84d591999-03-10 17:25:30 +0000567Strings can be subscripted (indexed); like in C, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000568of a string has subscript (index) 0. There is no separate character
569type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000570substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000571separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000572
Fred Drake8842e861998-02-13 07:16:30 +0000573\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000574>>> word[4]
575'A'
576>>> word[0:2]
577'He'
578>>> word[2:4]
579'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000580\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000581
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000582Slice indices have useful defaults; an omitted first index defaults to
583zero, an omitted second index defaults to the size of the string being
584sliced.
585
Fred Drake8842e861998-02-13 07:16:30 +0000586\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000587>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000588'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000589>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000590'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000591\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000592
Fred Drakeeee08cd1997-12-04 15:43:15 +0000593Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
594equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000595
Fred Drake8842e861998-02-13 07:16:30 +0000596\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000597>>> word[:2] + word[2:]
598'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000599>>> word[:3] + word[3:]
600'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000601\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000602
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000603Degenerate slice indices are handled gracefully: an index that is too
604large is replaced by the string size, an upper bound smaller than the
605lower bound returns an empty string.
606
Fred Drake8842e861998-02-13 07:16:30 +0000607\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000608>>> word[1:100]
609'elpA'
610>>> word[10:]
611''
612>>> word[2:1]
613''
Fred Drake8842e861998-02-13 07:16:30 +0000614\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000615
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000616Indices may be negative numbers, to start counting from the right.
617For example:
618
Fred Drake8842e861998-02-13 07:16:30 +0000619\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000620>>> word[-1] # The last character
621'A'
622>>> word[-2] # The last-but-one character
623'p'
624>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000625'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000626>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000627'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000628\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000629
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000630But note that -0 is really the same as 0, so it does not count from
631the right!
632
Fred Drake8842e861998-02-13 07:16:30 +0000633\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000634>>> word[-0] # (since -0 equals 0)
635'H'
Fred Drake8842e861998-02-13 07:16:30 +0000636\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000637
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000638Out-of-range negative slice indices are truncated, but don't try this
639for single-element (non-slice) indices:
640
Fred Drake8842e861998-02-13 07:16:30 +0000641\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000642>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000643'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000644>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000645Traceback (innermost last):
646 File "<stdin>", line 1
647IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000648\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000649
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000650The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000651pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000652character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000653string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000654
Fred Drake8842e861998-02-13 07:16:30 +0000655\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000656 +---+---+---+---+---+
657 | H | e | l | p | A |
658 +---+---+---+---+---+
659 0 1 2 3 4 5
660-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000661\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000662
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000663The first row of numbers gives the position of the indices 0...5 in
664the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000665The slice from \var{i} to \var{j} consists of all characters between
666the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000667
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000668For nonnegative indices, the length of a slice is the difference of
669the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000670\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000671
Fred Drake8842e861998-02-13 07:16:30 +0000672The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000673
Fred Drake8842e861998-02-13 07:16:30 +0000674\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000675>>> s = 'supercalifragilisticexpialidocious'
676>>> len(s)
67734
Fred Drake8842e861998-02-13 07:16:30 +0000678\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000679
Fred Drakeb7833d31998-09-11 16:21:55 +0000680\subsection{Lists \label{lists}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000681
Fred Drakeeee08cd1997-12-04 15:43:15 +0000682Python knows a number of \emph{compound} data types, used to group
683together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000684can be written as a list of comma-separated values (items) between
685square brackets. List items need not all have the same type.
686
Fred Drake8842e861998-02-13 07:16:30 +0000687\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000688>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000689>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000690['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000691\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000692
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000693Like string indices, list indices start at 0, and lists can be sliced,
694concatenated and so on:
695
Fred Drake8842e861998-02-13 07:16:30 +0000696\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000697>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000698'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000699>>> a[3]
7001234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000701>>> a[-2]
702100
703>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000704['eggs', 100]
705>>> a[:2] + ['bacon', 2*2]
706['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000707>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000708['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000709\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000710
Fred Drakeeee08cd1997-12-04 15:43:15 +0000711Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000712individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000713
Fred Drake8842e861998-02-13 07:16:30 +0000714\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000715>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000716['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000717>>> a[2] = a[2] + 23
718>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000719['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000720\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000721
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000722Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000723of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000724
Fred Drake8842e861998-02-13 07:16:30 +0000725\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000726>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000727... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000728>>> a
729[1, 12, 123, 1234]
730>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000731... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000732>>> a
733[123, 1234]
734>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000735... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000736>>> a
737[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000738>>> a[:0] = a # Insert (a copy of) itself at the beginning
739>>> a
740[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000741\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000742
Fred Drake8842e861998-02-13 07:16:30 +0000743The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000744
Fred Drake8842e861998-02-13 07:16:30 +0000745\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000746>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007478
Fred Drake8842e861998-02-13 07:16:30 +0000748\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000749
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000750It is possible to nest lists (create lists containing other lists),
751for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000752
Fred Drake8842e861998-02-13 07:16:30 +0000753\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000754>>> q = [2, 3]
755>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000756>>> len(p)
7573
758>>> p[1]
759[2, 3]
760>>> p[1][0]
7612
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000762>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000763>>> p
764[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000765>>> q
766[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000767\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000768
Fred Drakeeee08cd1997-12-04 15:43:15 +0000769Note that in the last example, \code{p[1]} and \code{q} really refer to
770the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000771
Fred Drakeb7833d31998-09-11 16:21:55 +0000772\section{First Steps Towards Programming \label{firstSteps}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000773
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000774Of course, we can use Python for more complicated tasks than adding
775two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000776subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000777
Fred Drake8842e861998-02-13 07:16:30 +0000778\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000779>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000780... # the sum of two elements defines the next
781... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000782>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000783... print b
784... a, b = b, a+b
785...
7861
7871
7882
7893
7905
7918
Fred Drake8842e861998-02-13 07:16:30 +0000792\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000793
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000794This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000795
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000796\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000797
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000798\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000799The first line contains a \emph{multiple assignment}: the variables
800\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000801last line this is used again, demonstrating that the expressions on
802the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000803assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000804
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000805\item
Fred Drake8842e861998-02-13 07:16:30 +0000806The \keyword{while} loop executes as long as the condition (here:
Fred Drakeee84d591999-03-10 17:25:30 +0000807\code{b < 10}) remains true. In Python, like in C, any non-zero
Fred Drake8842e861998-02-13 07:16:30 +0000808integer value is true; zero is false. The condition may also be a
809string or list value, in fact any sequence; anything with a non-zero
810length is true, empty sequences are false. The test used in the
811example is a simple comparison. The standard comparison operators are
Fred Drakeee84d591999-03-10 17:25:30 +0000812written the same as in C: \code{<}, \code{>}, \code{==}, \code{<=},
Fred Drake8842e861998-02-13 07:16:30 +0000813\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000814
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000815\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000816The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000817way of grouping statements. Python does not (yet!) provide an
818intelligent input line editing facility, so you have to type a tab or
819space(s) for each indented line. In practice you will prepare more
820complicated input for Python with a text editor; most text editors have
821an auto-indent facility. When a compound statement is entered
822interactively, it must be followed by a blank line to indicate
823completion (since the parser cannot guess when you have typed the last
824line).
825
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000826\item
Fred Drake8842e861998-02-13 07:16:30 +0000827The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000828given. It differs from just writing the expression you want to write
829(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000830multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000831and a space is inserted between items, so you can format things nicely,
832like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000833
Fred Drake8842e861998-02-13 07:16:30 +0000834\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000835>>> i = 256*256
836>>> print 'The value of i is', i
837The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000838\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000839
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000840A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000841
Fred Drake8842e861998-02-13 07:16:30 +0000842\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000843>>> a, b = 0, 1
844>>> while b < 1000:
845... print b,
846... a, b = b, a+b
847...
8481 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000849\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000850
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000851Note that the interpreter inserts a newline before it prints the next
852prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000853
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000854\end{itemize}
855
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000856
Fred Drakeb7833d31998-09-11 16:21:55 +0000857\chapter{More Control Flow Tools \label{moreControl}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000858
Fred Drake8842e861998-02-13 07:16:30 +0000859Besides the \keyword{while} statement just introduced, Python knows
860the usual control flow statements known from other languages, with
861some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000862
Fred Drakeb7833d31998-09-11 16:21:55 +0000863\section{\keyword{if} Statements \label{if}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000864
Fred Drake8842e861998-02-13 07:16:30 +0000865Perhaps the most well-known statement type is the \keyword{if}
866statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000867
Fred Drake8842e861998-02-13 07:16:30 +0000868\begin{verbatim}
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000869>>> # [Code which sets 'x' to a value...]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000870>>> if x < 0:
871... x = 0
872... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000873... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000874... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000875... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000876... print 'Single'
877... else:
878... print 'More'
879...
Fred Drake8842e861998-02-13 07:16:30 +0000880\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000881
Fred Drake8842e861998-02-13 07:16:30 +0000882There can be zero or more \keyword{elif} parts, and the \keyword{else}
883part is optional. The keyword `\keyword{elif}' is short for `else
884if', and is useful to avoid excessive indentation. An
885\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif}
886\ldots\ sequence is a substitute for the \emph{switch} or
887% ^^^^
888% Weird spacings happen here if the wrapping of the source text
889% gets changed in the wrong way.
890\emph{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000891
Fred Drakeb7833d31998-09-11 16:21:55 +0000892
893\section{\keyword{for} Statements \label{for}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000894
Fred Drakef790b161998-11-30 20:37:24 +0000895The \keyword{for}\stindex{for} statement in Python differs a bit from
Fred Drakeee84d591999-03-10 17:25:30 +0000896what you may be used to in C or Pascal. Rather than always
Fred Drakef790b161998-11-30 20:37:24 +0000897iterating over an arithmetic progression of numbers (like in Pascal),
898or giving the user the ability to define both the iteration step and
Fred Drakeee84d591999-03-10 17:25:30 +0000899halting condition (as C), Python's \keyword{for}\stindex{for}
Fred Drakef790b161998-11-30 20:37:24 +0000900statement iterates over the items of any sequence (e.g., a list or a
901string), in the order that they appear in the sequence. For example
902(no pun intended):
903% One suggestion was to give a real C example here, but that may only
904% serve to confuse non-C programmers.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000905
Fred Drake8842e861998-02-13 07:16:30 +0000906\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000907>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000908... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000909>>> for x in a:
910... print x, len(x)
911...
912cat 3
913window 6
914defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000915\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000916
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000917It is not safe to modify the sequence being iterated over in the loop
918(this can only happen for mutable sequence types, i.e., lists). If
919you need to modify the list you are iterating over, e.g., duplicate
920selected items, you must iterate over a copy. The slice notation
921makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000922
Fred Drake8842e861998-02-13 07:16:30 +0000923\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000924>>> for x in a[:]: # make a slice copy of the entire list
925... if len(x) > 6: a.insert(0, x)
926...
927>>> a
928['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000929\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000930
Fred Drakeb7833d31998-09-11 16:21:55 +0000931
932\section{The \function{range()} Function \label{range}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000933
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000934If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000935function \function{range()} comes in handy. It generates lists
936containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000937
Fred Drake8842e861998-02-13 07:16:30 +0000938\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000939>>> range(10)
940[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000941\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000942
Fred Drake8842e861998-02-13 07:16:30 +0000943The given end point is never part of the generated list;
944\code{range(10)} generates a list of 10 values, exactly the legal
945indices for items of a sequence of length 10. It is possible to let
946the range start at another number, or to specify a different increment
947(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000948
Fred Drake8842e861998-02-13 07:16:30 +0000949\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000950>>> range(5, 10)
951[5, 6, 7, 8, 9]
952>>> range(0, 10, 3)
953[0, 3, 6, 9]
954>>> range(-10, -100, -30)
955[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000956\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000957
Fred Drake8842e861998-02-13 07:16:30 +0000958To iterate over the indices of a sequence, combine \function{range()}
959and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000960
Fred Drake8842e861998-02-13 07:16:30 +0000961\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000962>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000963>>> for i in range(len(a)):
964... print i, a[i]
965...
9660 Mary
9671 had
9682 a
9693 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009704 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000971\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000972
Fred Drake391564f1998-04-01 23:11:56 +0000973\section{\keyword{break} and \keyword{continue} Statements, and
Fred Drakeb7833d31998-09-11 16:21:55 +0000974 \keyword{else} Clauses on Loops
975 \label{break}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000976
Fred Drakeee84d591999-03-10 17:25:30 +0000977The \keyword{break} statement, like in C, breaks out of the smallest
Fred Drake8842e861998-02-13 07:16:30 +0000978enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000979
Fred Drakeee84d591999-03-10 17:25:30 +0000980The \keyword{continue} statement, also borrowed from C, continues
Fred Drake8842e861998-02-13 07:16:30 +0000981with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000982
Fred Drake8842e861998-02-13 07:16:30 +0000983Loop statements may have an \code{else} clause; it is executed when
984the loop terminates through exhaustion of the list (with
985\keyword{for}) or when the condition becomes false (with
986\keyword{while}), but not when the loop is terminated by a
987\keyword{break} statement. This is exemplified by the following loop,
988which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000989
Fred Drake8842e861998-02-13 07:16:30 +0000990\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000991>>> for n in range(2, 10):
992... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000993... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000994... print n, 'equals', x, '*', n/x
995... break
996... else:
997... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000998...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00009992 is a prime number
10003 is a prime number
10014 equals 2 * 2
10025 is a prime number
10036 equals 2 * 3
10047 is a prime number
10058 equals 2 * 4
10069 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +00001007\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001008
Fred Drakeb7833d31998-09-11 16:21:55 +00001009\section{\keyword{pass} Statements \label{pass}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001010
Fred Drake8842e861998-02-13 07:16:30 +00001011The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001012It can be used when a statement is required syntactically but the
1013program requires no action.
1014For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001015
Fred Drake8842e861998-02-13 07:16:30 +00001016\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001017>>> while 1:
1018... pass # Busy-wait for keyboard interrupt
1019...
Fred Drake8842e861998-02-13 07:16:30 +00001020\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001021
Fred Drakeb7833d31998-09-11 16:21:55 +00001022\section{Defining Functions \label{functions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001023
1024We can create a function that writes the Fibonacci series to an
1025arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001026
Fred Drake8842e861998-02-13 07:16:30 +00001027\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001028>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001029... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001030... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001031... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001032... print b,
1033... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001034...
1035>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001036... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010371 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001038\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001039
Fred Drake8842e861998-02-13 07:16:30 +00001040The keyword \keyword{def} introduces a function \emph{definition}. It
1041must be followed by the function name and the parenthesized list of
1042formal parameters. The statements that form the body of the function
1043start at the next line, indented by a tab stop. The first statement
1044of the function body can optionally be a string literal; this string
1045literal is the function's documentation string, or \dfn{docstring}.
1046There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001047documentation, or to let the user interactively browse through code;
1048it's good practice to include docstrings in code that you write, so
1049try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001050
Fred Drakeeee08cd1997-12-04 15:43:15 +00001051The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001052for the local variables of the function. More precisely, all variable
1053assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001054whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001055in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001056Thus, global variables cannot be directly assigned a value within a
1057function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001058they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001059
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001060The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001061the local symbol table of the called function when it is called; thus,
Fred Drake93aa0f21999-04-05 21:39:17 +00001062arguments are passed using \emph{call by value}.\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001063 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001064 description, since if a mutable object is passed, the caller
1065 will see any changes the callee makes to it (e.g., items
1066 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001067}
1068When a function calls another function, a new local symbol table is
1069created for that call.
1070
Fred Drake8842e861998-02-13 07:16:30 +00001071A function definition introduces the function name in the current
1072symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001073has a type that is recognized by the interpreter as a user-defined
1074function. This value can be assigned to another name which can then
1075also be used as a function. This serves as a general renaming
1076mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001077
Fred Drake8842e861998-02-13 07:16:30 +00001078\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001079>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001080<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001081>>> f = fib
1082>>> f(100)
10831 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001084\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001085
Fred Drakeeee08cd1997-12-04 15:43:15 +00001086You might object that \code{fib} is not a function but a procedure. In
Fred Drakeee84d591999-03-10 17:25:30 +00001087Python, like in C, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001088value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001089albeit a rather boring one. This value is called \code{None} (it's a
1090built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001091the interpreter if it would be the only value written. You can see it
1092if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001093
Fred Drake8842e861998-02-13 07:16:30 +00001094\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001095>>> print fib(0)
1096None
Fred Drake8842e861998-02-13 07:16:30 +00001097\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001098
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001099It is simple to write a function that returns a list of the numbers of
1100the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001101
Fred Drake8842e861998-02-13 07:16:30 +00001102\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001103>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001104... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001105... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001106... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001107... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001108... result.append(b) # see below
1109... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001110... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001111...
1112>>> f100 = fib2(100) # call it
1113>>> f100 # write the result
1114[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001115\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001116%
Guido van Rossum4410c751991-06-04 20:22:18 +00001117This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001118
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001119\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001120
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001121\item
Fred Drake8842e861998-02-13 07:16:30 +00001122The \keyword{return} statement returns with a value from a function.
1123\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001124the middle of a procedure (falling off the end also returns from a
1125procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001126
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001127\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001128The statement \code{result.append(b)} calls a \emph{method} of the list
1129object \code{result}. A method is a function that `belongs' to an
1130object and is named \code{obj.methodname}, where \code{obj} is some
1131object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001132of a method that is defined by the object's type. Different types
1133define different methods. Methods of different types may have the
1134same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001135own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001136in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001137The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001138list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001139example it is equivalent to \samp{result = result + [b]}, but more
1140efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001141
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001142\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001143
Fred Drakeb7833d31998-09-11 16:21:55 +00001144\section{More on Defining Functions \label{defining}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001145
Guido van Rossum02455691997-07-17 16:21:52 +00001146It is also possible to define functions with a variable number of
1147arguments. There are three forms, which can be combined.
1148
Fred Drakeb7833d31998-09-11 16:21:55 +00001149\subsection{Default Argument Values \label{defaultArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001150
1151The most useful form is to specify a default value for one or more
1152arguments. This creates a function that can be called with fewer
1153arguments than it is defined, e.g.
1154
1155\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001156def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1157 while 1:
1158 ok = raw_input(prompt)
1159 if ok in ('y', 'ye', 'yes'): return 1
1160 if ok in ('n', 'no', 'nop', 'nope'): return 0
1161 retries = retries - 1
1162 if retries < 0: raise IOError, 'refusenik user'
1163 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001164\end{verbatim}
1165
1166This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001167\code{ask_ok('Do you really want to quit?')} or like this:
1168\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001169
1170The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001171in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001172
1173\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001174i = 5
1175def f(arg = i): print arg
1176i = 6
1177f()
Guido van Rossum02455691997-07-17 16:21:52 +00001178\end{verbatim}
1179
Fred Drakeeee08cd1997-12-04 15:43:15 +00001180will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001181
Guido van Rossumaee5e261998-08-07 17:45:09 +00001182\strong{Important warning:} The default value is evaluated only once.
1183This makes a difference when the default is a mutable object such as a
1184list or dictionary. For example, the following function accumulates
1185the arguments passed to it on subsequent calls:
1186
1187\begin{verbatim}
1188def f(a, l = []):
1189 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001190 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001191print f(1)
1192print f(2)
1193print f(3)
1194\end{verbatim}
1195
1196This will print
1197
1198\begin{verbatim}
1199[1]
1200[1, 2]
1201[1, 2, 3]
1202\end{verbatim}
1203
1204If you don't want the default to be shared between subsequent calls,
1205you can write the function like this instead:
1206
1207\begin{verbatim}
1208def f(a, l = None):
1209 if l is None:
1210 l = []
1211 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001212 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001213\end{verbatim}
1214
Fred Drakeb7833d31998-09-11 16:21:55 +00001215\subsection{Keyword Arguments \label{keywordArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001216
1217Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001218keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001219instance, the following function:
1220
1221\begin{verbatim}
1222def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1223 print "-- This parrot wouldn't", action,
1224 print "if you put", voltage, "Volts through it."
1225 print "-- Lovely plumage, the", type
1226 print "-- It's", state, "!"
1227\end{verbatim}
1228
1229could be called in any of the following ways:
1230
1231\begin{verbatim}
1232parrot(1000)
1233parrot(action = 'VOOOOOM', voltage = 1000000)
1234parrot('a thousand', state = 'pushing up the daisies')
1235parrot('a million', 'bereft of life', 'jump')
1236\end{verbatim}
1237
1238but the following calls would all be invalid:
1239
1240\begin{verbatim}
1241parrot() # required argument missing
1242parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1243parrot(110, voltage=220) # duplicate value for argument
1244parrot(actor='John Cleese') # unknown keyword
1245\end{verbatim}
1246
1247In general, an argument list must have any positional arguments
1248followed by any keyword arguments, where the keywords must be chosen
1249from the formal parameter names. It's not important whether a formal
1250parameter has a default value or not. No argument must receive a
1251value more than once --- formal parameter names corresponding to
1252positional arguments cannot be used as keywords in the same calls.
1253
1254When a final formal parameter of the form \code{**\var{name}} is
1255present, it receives a dictionary containing all keyword arguments
1256whose keyword doesn't correspond to a formal parameter. This may be
1257combined with a formal parameter of the form \code{*\var{name}}
1258(described in the next subsection) which receives a tuple containing
1259the positional arguments beyond the formal parameter list.
1260(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1261example, if we define a function like this:
1262
1263\begin{verbatim}
1264def cheeseshop(kind, *arguments, **keywords):
1265 print "-- Do you have any", kind, '?'
1266 print "-- I'm sorry, we're all out of", kind
1267 for arg in arguments: print arg
1268 print '-'*40
1269 for kw in keywords.keys(): print kw, ':', keywords[kw]
1270\end{verbatim}
1271
1272It could be called like this:
1273
1274\begin{verbatim}
1275cheeseshop('Limburger', "It's very runny, sir.",
1276 "It's really very, VERY runny, sir.",
1277 client='John Cleese',
1278 shopkeeper='Michael Palin',
1279 sketch='Cheese Shop Sketch')
1280\end{verbatim}
1281
1282and of course it would print:
1283
1284\begin{verbatim}
1285-- Do you have any Limburger ?
1286-- I'm sorry, we're all out of Limburger
1287It's very runny, sir.
1288It's really very, VERY runny, sir.
1289----------------------------------------
1290client : John Cleese
1291shopkeeper : Michael Palin
1292sketch : Cheese Shop Sketch
1293\end{verbatim}
1294
Fred Drakeb7833d31998-09-11 16:21:55 +00001295\subsection{Arbitrary Argument Lists \label{arbitraryArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001296
1297Finally, the least frequently used option is to specify that a
1298function can be called with an arbitrary number of arguments. These
1299arguments will be wrapped up in a tuple. Before the variable number
1300of arguments, zero or more normal arguments may occur.
1301
1302\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001303def fprintf(file, format, *args):
1304 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001305\end{verbatim}
1306
Fred Drakea594baf1998-04-03 05:16:31 +00001307
Fred Drakeb7833d31998-09-11 16:21:55 +00001308\subsection{Lambda Forms \label{lambda}}
Fred Drakea594baf1998-04-03 05:16:31 +00001309
1310By popular demand, a few features commonly found in functional
1311programming languages and Lisp have been added to Python. With the
1312\keyword{lambda} keyword, small anonymous functions can be created.
1313Here's a function that returns the sum of its two arguments:
1314\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1315objects are required. They are syntactically restricted to a single
1316expression. Semantically, they are just syntactic sugar for a normal
1317function definition. Like nested function definitions, lambda forms
1318cannot reference variables from the containing scope, but this can be
1319overcome through the judicious use of default argument values, e.g.
1320
1321\begin{verbatim}
1322def make_incrementor(n):
1323 return lambda x, incr=n: x+incr
1324\end{verbatim}
1325
Fred Drakeb7833d31998-09-11 16:21:55 +00001326\subsection{Documentation Strings \label{docstrings}}
Fred Drakea594baf1998-04-03 05:16:31 +00001327
1328There are emerging conventions about the content and formatting of
1329documentation strings.
1330
1331The first line should always be a short, concise summary of the
1332object's purpose. For brevity, it should not explicitly state the
1333object's name or type, since these are available by other means
1334(except if the name happens to be a verb describing a function's
1335operation). This line should begin with a capital letter and end with
1336a period.
1337
1338If there are more lines in the documentation string, the second line
1339should be blank, visually separating the summary from the rest of the
Fred Drake4b1a07a1999-03-12 18:21:32 +00001340description. The following lines should be one or more paragraphs
1341describing the object's calling conventions, its side effects, etc.
Fred Drakea594baf1998-04-03 05:16:31 +00001342
1343The Python parser does not strip indentation from multi-line string
1344literals in Python, so tools that process documentation have to strip
1345indentation. This is done using the following convention. The first
1346non-blank line \emph{after} the first line of the string determines the
1347amount of indentation for the entire documentation string. (We can't
1348use the first line since it is generally adjacent to the string's
1349opening quotes so its indentation is not apparent in the string
1350literal.) Whitespace ``equivalent'' to this indentation is then
1351stripped from the start of all lines of the string. Lines that are
1352indented less should not occur, but if they occur all their leading
1353whitespace should be stripped. Equivalence of whitespace should be
1354tested after expansion of tabs (to 8 spaces, normally).
1355
1356
1357
Fred Drakeb7833d31998-09-11 16:21:55 +00001358\chapter{Data Structures \label{structures}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001359
1360This chapter describes some things you've learned about already in
1361more detail, and adds some new things as well.
1362
Fred Drakeb7833d31998-09-11 16:21:55 +00001363\section{More on Lists \label{moreLists}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001364
1365The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001366of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001367
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001368\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001369
Fred Drakeeee08cd1997-12-04 15:43:15 +00001370\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001371Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001372the element before which to insert, so \code{a.insert(0, x)} inserts at
1373the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1374\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001375
Fred Drakeeee08cd1997-12-04 15:43:15 +00001376\item[\code{append(x)}]
1377Equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001378
Fred Drakeeee08cd1997-12-04 15:43:15 +00001379\item[\code{index(x)}]
1380Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001381It is an error if there is no such item.
1382
Fred Drakeeee08cd1997-12-04 15:43:15 +00001383\item[\code{remove(x)}]
1384Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001385It is an error if there is no such item.
1386
Fred Drakeeee08cd1997-12-04 15:43:15 +00001387\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001388Sort the items of the list, in place.
1389
Fred Drakeeee08cd1997-12-04 15:43:15 +00001390\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001391Reverse the elements of the list, in place.
1392
Fred Drakeeee08cd1997-12-04 15:43:15 +00001393\item[\code{count(x)}]
1394Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001395
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001396\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001397
1398An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001399
Fred Drake8842e861998-02-13 07:16:30 +00001400\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001401>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001402>>> print a.count(333), a.count(66.6), a.count('x')
14032 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001404>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001405>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001406>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001407[66.6, 333, -1, 333, 1, 1234.5, 333]
1408>>> a.index(333)
14091
1410>>> a.remove(333)
1411>>> a
1412[66.6, -1, 333, 1, 1234.5, 333]
1413>>> a.reverse()
1414>>> a
1415[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001416>>> a.sort()
1417>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001418[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001419\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001420
Fred Drakeb7833d31998-09-11 16:21:55 +00001421\subsection{Functional Programming Tools \label{functional}}
Guido van Rossum02455691997-07-17 16:21:52 +00001422
1423There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001424lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001425
Fred Drake8842e861998-02-13 07:16:30 +00001426\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1427the same type, if possible) consisting of those items from the
1428sequence for which \code{\var{function}(\var{item})} is true. For
1429example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001430
1431\begin{verbatim}
Fred Drakeee84d591999-03-10 17:25:30 +00001432>>> def f(x): return x % 2 != 0 and x % 3 != 0
Fred Drake8842e861998-02-13 07:16:30 +00001433...
1434>>> filter(f, range(2, 25))
1435[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001436\end{verbatim}
1437
Fred Drake8842e861998-02-13 07:16:30 +00001438\samp{map(\var{function}, \var{sequence})} calls
1439\code{\var{function}(\var{item})} for each of the sequence's items and
1440returns a list of the return values. For example, to compute some
1441cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001442
1443\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001444>>> def cube(x): return x*x*x
1445...
1446>>> map(cube, range(1, 11))
1447[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001448\end{verbatim}
1449
1450More than one sequence may be passed; the function must then have as
1451many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001452corresponding item from each sequence (or \code{None} if some sequence
1453is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001454a function returning its argument(s) is substituted.
1455
1456Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001457\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1458turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001459
1460\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001461>>> seq = range(8)
1462>>> def square(x): return x*x
1463...
1464>>> map(None, seq, map(square, seq))
1465[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001466\end{verbatim}
1467
Fred Drake8842e861998-02-13 07:16:30 +00001468\samp{reduce(\var{func}, \var{sequence})} returns a single value
1469constructed by calling the binary function \var{func} on the first two
1470items of the sequence, then on the result and the next item, and so
1471on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001472
1473\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001474>>> def add(x,y): return x+y
1475...
1476>>> reduce(add, range(1, 11))
147755
Guido van Rossum02455691997-07-17 16:21:52 +00001478\end{verbatim}
1479
1480If there's only one item in the sequence, its value is returned; if
1481the sequence is empty, an exception is raised.
1482
1483A third argument can be passed to indicate the starting value. In this
1484case the starting value is returned for an empty sequence, and the
1485function is first applied to the starting value and the first sequence
1486item, then to the result and the next item, and so on. For example,
1487
1488\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001489>>> def sum(seq):
1490... def add(x,y): return x+y
1491... return reduce(add, seq, 0)
1492...
1493>>> sum(range(1, 11))
149455
1495>>> sum([])
14960
Guido van Rossum02455691997-07-17 16:21:52 +00001497\end{verbatim}
1498
Fred Drakeb7833d31998-09-11 16:21:55 +00001499\section{The \keyword{del} statement \label{del}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001500
1501There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001502of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001503remove slices from a list (which we did earlier by assignment of an
1504empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001505
Fred Drake8842e861998-02-13 07:16:30 +00001506\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001507>>> a
1508[-1, 1, 66.6, 333, 333, 1234.5]
1509>>> del a[0]
1510>>> a
1511[1, 66.6, 333, 333, 1234.5]
1512>>> del a[2:4]
1513>>> a
1514[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001515\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001516
1517\keyword{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001518
Fred Drake8842e861998-02-13 07:16:30 +00001519\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001520>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001521\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001522
Fred Drakeeee08cd1997-12-04 15:43:15 +00001523Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001524another value is assigned to it). We'll find other uses for
1525\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001526
Fred Drakeb7833d31998-09-11 16:21:55 +00001527\section{Tuples and Sequences \label{tuples}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001528
1529We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001530indexing and slicing operations. They are two examples of
1531\emph{sequence} data types. Since Python is an evolving language,
1532other sequence data types may be added. There is also another
1533standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001534
1535A tuple consists of a number of values separated by commas, for
1536instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001537
Fred Drake8842e861998-02-13 07:16:30 +00001538\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001539>>> t = 12345, 54321, 'hello!'
1540>>> t[0]
154112345
1542>>> t
1543(12345, 54321, 'hello!')
1544>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001545... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001546>>> u
1547((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001548\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001549
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001550As you see, on output tuples are alway enclosed in parentheses, so
1551that nested tuples are interpreted correctly; they may be input with
1552or without surrounding parentheses, although often parentheses are
1553necessary anyway (if the tuple is part of a larger expression).
1554
1555Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1556from a database, etc. Tuples, like strings, are immutable: it is not
1557possible to assign to the individual items of a tuple (you can
1558simulate much of the same effect with slicing and concatenation,
1559though).
1560
1561A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001562items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001563tuples are constructed by an empty pair of parentheses; a tuple with
1564one item is constructed by following a value with a comma
1565(it is not sufficient to enclose a single value in parentheses).
1566Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001567
Fred Drake8842e861998-02-13 07:16:30 +00001568\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001569>>> empty = ()
1570>>> singleton = 'hello', # <-- note trailing comma
1571>>> len(empty)
15720
1573>>> len(singleton)
15741
1575>>> singleton
1576('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001577\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001578
Fred Drakeeee08cd1997-12-04 15:43:15 +00001579The statement \code{t = 12345, 54321, 'hello!'} is an example of
1580\emph{tuple packing}: the values \code{12345}, \code{54321} and
1581\code{'hello!'} are packed together in a tuple. The reverse operation
1582is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001583
Fred Drake8842e861998-02-13 07:16:30 +00001584\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001585>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001586\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001587
Fred Drakeeee08cd1997-12-04 15:43:15 +00001588This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001589unpacking requires that the list of variables on the left has the same
1590number of elements as the length of the tuple. Note that multiple
1591assignment is really just a combination of tuple packing and tuple
1592unpacking!
1593
Guido van Rossumaee5e261998-08-07 17:45:09 +00001594% XXX This is no longer necessary!
Fred Drakeeee08cd1997-12-04 15:43:15 +00001595Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001596unpacking}. This is supported by enclosing the list of variables in
1597square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001598
Fred Drake8842e861998-02-13 07:16:30 +00001599\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001600>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001601>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001602\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001603
Guido van Rossumaee5e261998-08-07 17:45:09 +00001604% XXX Add a bit on the difference between tuples and lists.
1605% XXX Also explain that a tuple can *contain* a mutable object!
1606
Fred Drakeb7833d31998-09-11 16:21:55 +00001607\section{Dictionaries \label{dictionaries}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001608
Fred Drakeeee08cd1997-12-04 15:43:15 +00001609Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001610Dictionaries are sometimes found in other languages as ``associative
1611memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001612indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001613which can be any non-mutable type; strings and numbers can always be
1614keys. Tuples can be used as keys if they contain only strings,
1615numbers, or tuples. You can't use lists as keys, since lists can be
1616modified in place using their \code{append()} method.
1617
Guido van Rossum6938f061994-08-01 12:22:53 +00001618It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001619\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001620(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001621A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001622Placing a comma-separated list of key:value pairs within the
1623braces adds initial key:value pairs to the dictionary; this is also the
1624way dictionaries are written on output.
1625
1626The main operations on a dictionary are storing a value with some key
1627and extracting the value given the key. It is also possible to delete
1628a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001629with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001630If you store using a key that is already in use, the old value
1631associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001632value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001633
Fred Drakeeee08cd1997-12-04 15:43:15 +00001634The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001635keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001636just apply the \code{sort()} method to the list of keys). To check
1637whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001638method of the dictionary.
1639
1640Here is a small example using a dictionary:
1641
Fred Drake8842e861998-02-13 07:16:30 +00001642\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001643>>> tel = {'jack': 4098, 'sape': 4139}
1644>>> tel['guido'] = 4127
1645>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001646{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001647>>> tel['jack']
16484098
1649>>> del tel['sape']
1650>>> tel['irv'] = 4127
1651>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001652{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001653>>> tel.keys()
1654['guido', 'irv', 'jack']
1655>>> tel.has_key('guido')
16561
Fred Drake8842e861998-02-13 07:16:30 +00001657\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001658
Fred Drakeb7833d31998-09-11 16:21:55 +00001659\section{More on Conditions \label{conditions}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001660
Fred Drakeeee08cd1997-12-04 15:43:15 +00001661The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001662contain other operators besides comparisons.
1663
Fred Drakeeee08cd1997-12-04 15:43:15 +00001664The comparison operators \code{in} and \code{not in} check whether a value
1665occurs (does not occur) in a sequence. The operators \code{is} and
1666\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001667only matters for mutable objects like lists. All comparison operators
1668have the same priority, which is lower than that of all numerical
1669operators.
1670
Fred Drakeeee08cd1997-12-04 15:43:15 +00001671Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a}
1672is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001673
Fred Drakeeee08cd1997-12-04 15:43:15 +00001674Comparisons may be combined by the Boolean operators \code{and} and
1675\code{or}, and the outcome of a comparison (or of any other Boolean
1676expression) may be negated with \code{not}. These all have lower
1677priorities than comparison operators again; between them, \code{not} has
1678the highest priority, and \code{or} the lowest, so that
1679\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 +00001680course, parentheses can be used to express the desired composition.
1681
Fred Drakeeee08cd1997-12-04 15:43:15 +00001682The Boolean operators \code{and} and \code{or} are so-called
1683\emph{shortcut} operators: their arguments are evaluated from left to
1684right, and evaluation stops as soon as the outcome is determined.
1685E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1686and B and C} does not evaluate the expression C. In general, the
1687return value of a shortcut operator, when used as a general value and
1688not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001689
1690It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001691expression to a variable. For example,
1692
Fred Drake8842e861998-02-13 07:16:30 +00001693\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001694>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1695>>> non_null = string1 or string2 or string3
1696>>> non_null
1697'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001698\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001699
Fred Drakeee84d591999-03-10 17:25:30 +00001700Note that in Python, unlike C, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001701
Fred Drakeb7833d31998-09-11 16:21:55 +00001702\section{Comparing Sequences and Other Types \label{comparing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001703
1704Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001705sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001706first the first two items are compared, and if they differ this
1707determines the outcome of the comparison; if they are equal, the next
1708two items are compared, and so on, until either sequence is exhausted.
1709If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001710the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001711items of two sequences compare equal, the sequences are considered
1712equal. If one sequence is an initial subsequence of the other, the
1713shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001714strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001715examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001716
Fred Drake8842e861998-02-13 07:16:30 +00001717\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001718(1, 2, 3) < (1, 2, 4)
1719[1, 2, 3] < [1, 2, 4]
1720'ABC' < 'C' < 'Pascal' < 'Python'
1721(1, 2, 3, 4) < (1, 2, 4)
1722(1, 2) < (1, 2, -1)
1723(1, 2, 3) = (1.0, 2.0, 3.0)
1724(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001725\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001726
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001727Note that comparing objects of different types is legal. The outcome
1728is deterministic but arbitrary: the types are ordered by their name.
1729Thus, a list is always smaller than a string, a string is always
1730smaller than a tuple, etc. Mixed numeric types are compared according
Fred Drake93aa0f21999-04-05 21:39:17 +00001731to their numeric value, so 0 equals 0.0, etc.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001732 The rules for comparing objects of different types should
1733 not be relied upon; they may change in a future version of
1734 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001735}
1736
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001737
Fred Drakeb7833d31998-09-11 16:21:55 +00001738\chapter{Modules \label{modules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001739
Guido van Rossum4410c751991-06-04 20:22:18 +00001740If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001741definitions you have made (functions and variables) are lost.
1742Therefore, if you want to write a somewhat longer program, you are
1743better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001744and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001745\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001746into several files for easier maintenance. You may also want to use a
1747handy function that you've written in several programs without copying
1748its definition into each program.
1749
Guido van Rossum4410c751991-06-04 20:22:18 +00001750To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001751them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001752Such a file is called a \emph{module}; definitions from a module can be
1753\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001754collection of variables that you have access to in a script
1755executed at the top level
1756and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001757
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001758A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001759file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001760a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001761the global variable \code{__name__}. For instance, use your favorite text
1762editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001763with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001764
Fred Drake8842e861998-02-13 07:16:30 +00001765\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001766# Fibonacci numbers module
1767
1768def fib(n): # write Fibonacci series up to n
1769 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001770 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001771 print b,
1772 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001773
1774def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001775 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001776 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001777 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001778 result.append(b)
1779 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001780 return result
Fred Drake8842e861998-02-13 07:16:30 +00001781\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001782
Guido van Rossum4410c751991-06-04 20:22:18 +00001783Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001784following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001785
Fred Drake8842e861998-02-13 07:16:30 +00001786\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001787>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001788\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001789
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001790This does not enter the names of the functions defined in
Fred Drakeeee08cd1997-12-04 15:43:15 +00001791\code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001792directly in the current symbol table; it only enters the module name
Fred Drakeeee08cd1997-12-04 15:43:15 +00001793\code{fibo}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001794there.
1795Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001796
Fred Drake8842e861998-02-13 07:16:30 +00001797\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001798>>> fibo.fib(1000)
17991 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1800>>> fibo.fib2(100)
1801[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001802>>> fibo.__name__
1803'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001804\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001805%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001806If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001807
Fred Drake8842e861998-02-13 07:16:30 +00001808\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001809>>> fib = fibo.fib
1810>>> fib(500)
18111 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001812\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001813
Guido van Rossum02455691997-07-17 16:21:52 +00001814
Fred Drakeb7833d31998-09-11 16:21:55 +00001815\section{More on Modules \label{moreModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001816
1817A module can contain executable statements as well as function
1818definitions.
1819These statements are intended to initialize the module.
1820They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001821\emph{first}
Fred Drake93aa0f21999-04-05 21:39:17 +00001822time the module is imported somewhere.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001823 In fact function definitions are also `statements' that are
1824 `executed'; the execution enters the function name in the
1825 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001826}
1827
1828Each module has its own private symbol table, which is used as the
1829global symbol table by all functions defined in the module.
1830Thus, the author of a module can use global variables in the module
1831without worrying about accidental clashes with a user's global
1832variables.
1833On the other hand, if you know what you are doing you can touch a
1834module's global variables with the same notation used to refer to its
1835functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001836\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001837
1838Modules can import other modules.
1839It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001840\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001841statements at the beginning of a module (or script, for that matter).
1842The imported module names are placed in the importing module's global
1843symbol table.
1844
1845There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001846\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001847statement that imports names from a module directly into the importing
1848module's symbol table.
1849For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001850
Fred Drake8842e861998-02-13 07:16:30 +00001851\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001852>>> from fibo import fib, fib2
1853>>> fib(500)
18541 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001855\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001856
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001857This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001858in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001859defined).
1860
1861There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001862
Fred Drake8842e861998-02-13 07:16:30 +00001863\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001864>>> from fibo import *
1865>>> fib(500)
18661 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001867\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001868
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001869This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001870(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001871
Fred Drakeb7833d31998-09-11 16:21:55 +00001872\subsection{The Module Search Path \label{searchPath}}
Guido van Rossum02455691997-07-17 16:21:52 +00001873
Guido van Rossumaee5e261998-08-07 17:45:09 +00001874% XXX Need to document that a lone .pyc/.pyo is acceptable too!
1875
Fred Drake391564f1998-04-01 23:11:56 +00001876\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00001877When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001878for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001879and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00001880the environment variable \envvar{PYTHONPATH}. This has the same syntax as
1881the shell variable \envvar{PATH}, i.e., a list of
1882directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001883is not found there, the search continues in an installation-dependent
Fred Drake391564f1998-04-01 23:11:56 +00001884default path; on \UNIX{}, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001885
1886Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001887variable \code{sys.path} which is initialized from the directory
1888containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00001889\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001890Python programs that know what they're doing to modify or replace the
1891module search path. See the section on Standard Modules later.
1892
1893\subsection{``Compiled'' Python files}
1894
1895As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001896use a lot of standard modules, if a file called \file{spam.pyc} exists
1897in the directory where \file{spam.py} is found, this is assumed to
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001898contain an already-``byte-compiled'' version of the module \module{spam}.
Fred Drake8842e861998-02-13 07:16:30 +00001899The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001900\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1901ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001902
Fred Drakeeee08cd1997-12-04 15:43:15 +00001903Normally, you don't need to do anything to create the \file{spam.pyc} file.
1904Whenever \file{spam.py} is successfully compiled, an attempt is made to
1905write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001906this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001907completely, the resulting \file{spam.pyc} file will be recognized as
1908invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001909file is platform independent, so a Python module directory can be
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001910shared by machines of different architectures.
Guido van Rossum02455691997-07-17 16:21:52 +00001911
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001912Some tips for experts:
1913
1914\begin{itemize}
1915
1916\item
1917When the Python interpreter is invoked with the \code{-O} flag,
1918optimized code is generated and stored in \file{.pyo} files.
1919The optimizer currently doesn't help much; it only removes
1920\keyword{assert} statements and \code{SET_LINENO} instructions.
1921When \code{-O} is used, \emph{all} bytecode is optimized; \code{.pyc}
1922files are ignored and \code{.py} files are compiled to optimized
1923bytecode.
1924
1925\item
Guido van Rossum6b86a421999-01-28 15:07:47 +00001926Passing two \code{-O} flags to the Python interpreter (\code{-OO})
1927will cause the bytecode compiler to perform optimizations that could
1928in some rare cases result in malfunctioning programs. Currently only
1929\code{__doc__} strings are removed from the bytecode, resulting in more
1930compact \file{.pyo} files. Since some programs may rely on having
1931these available, you should only use this option if you know what
1932you're doing.
1933
1934\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001935A program doesn't run any faster when it is read from a
1936\file{.pyc} or \file{.pyo} file than when it is read from a \file{.py}
1937file; the only thing that's faster about \file{.pyc} or \file{.pyo}
1938files is the speed with which they are loaded.
1939
1940\item
Guido van Rossum002f7aa1998-06-28 19:16:38 +00001941When a script is run by giving its name on the command line, the
1942bytecode for the script is never written to a \file{.pyc} or
1943\file{.pyo} file. Thus, the startup time of a script may be reduced
1944by moving most of its code to a module and having a small bootstrap
1945script that imports that module.
1946
1947\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001948It is possible to have a file called \file{spam.pyc} (or
1949\file{spam.pyo} when \code{-O} is used) without a module
1950\file{spam.py} in the same module. This can be used to distribute
1951a library of Python code in a form that is moderately hard to reverse
1952engineer.
1953
1954\item
1955The module \module{compileall}\refstmodindex{compileall} can create
1956\file{.pyc} files (or \file{.pyo} files when \code{-O} is used) for
1957all modules in a directory.
1958
1959\end{itemize}
1960
Guido van Rossum02455691997-07-17 16:21:52 +00001961
Fred Drakeb7833d31998-09-11 16:21:55 +00001962\section{Standard Modules \label{standardModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001963
Guido van Rossum4410c751991-06-04 20:22:18 +00001964Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001965document, the \emph{Python Library Reference} (``Library Reference''
1966hereafter). Some modules are built into the interpreter; these
1967provide access to operations that are not part of the core of the
1968language but are nevertheless built in, either for efficiency or to
1969provide access to operating system primitives such as system calls.
1970The set of such modules is a configuration option; e.g., the
1971\module{amoeba} module is only provided on systems that somehow
1972support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00001973attention: \module{sys}\refstmodindex{sys}, which is built into every
Fred Drakeee84d591999-03-10 17:25:30 +00001974Python interpreter. The variables \code{sys.ps1} and
1975\code{sys.ps2} define the strings used as primary and secondary
1976prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001977
Fred Drake8842e861998-02-13 07:16:30 +00001978\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001979>>> import sys
1980>>> sys.ps1
1981'>>> '
1982>>> sys.ps2
1983'... '
1984>>> sys.ps1 = 'C> '
1985C> print 'Yuck!'
1986Yuck!
1987C>
Fred Drake8842e861998-02-13 07:16:30 +00001988\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001989
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001990These two variables are only defined if the interpreter is in
1991interactive mode.
1992
Fred Drakeee84d591999-03-10 17:25:30 +00001993The variable \code{sys.path} is a list of strings that determine the
1994interpreter's search path for modules. It is initialized to a default
1995path taken from the environment variable \envvar{PYTHONPATH}, or from
1996a built-in default if \envvar{PYTHONPATH} is not set. You can modify
1997it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001998
Fred Drake8842e861998-02-13 07:16:30 +00001999\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002000>>> import sys
2001>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00002002\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002003
Fred Drakeb7833d31998-09-11 16:21:55 +00002004\section{The \function{dir()} Function \label{dir}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002005
Fred Drake8842e861998-02-13 07:16:30 +00002006The built-in function \function{dir()} is used to find out which names
2007a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002008
Fred Drake8842e861998-02-13 07:16:30 +00002009\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002010>>> import fibo, sys
2011>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00002012['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002013>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00002014['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
2015'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
2016'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00002017\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002018
Fred Drake8842e861998-02-13 07:16:30 +00002019Without arguments, \function{dir()} lists the names you have defined
2020currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002021
Fred Drake8842e861998-02-13 07:16:30 +00002022\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002023>>> a = [1, 2, 3, 4, 5]
2024>>> import fibo, sys
2025>>> fib = fibo.fib
2026>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00002027['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00002028\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002029
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002030Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002031
Fred Drake8842e861998-02-13 07:16:30 +00002032\function{dir()} does not list the names of built-in functions and
2033variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00002034standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002035
Fred Drake8842e861998-02-13 07:16:30 +00002036\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00002037>>> import __builtin__
2038>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00002039['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
2040'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2041'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
2042'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
2043'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
2044'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
2045'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
2046'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
2047'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00002048\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002049
Fred Drakeb7833d31998-09-11 16:21:55 +00002050\section{Packages \label{packages}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002051
2052Packages are a way of structuring Python's module namespace
Fred Drakeb7833d31998-09-11 16:21:55 +00002053by using ``dotted module names''. For example, the module name
2054\module{A.B} designates a submodule named \samp{B} in a package named
2055\samp{A}. Just like the use of modules saves the authors of different
2056modules from having to worry about each other's global variable names,
2057the use of dotted module names saves the authors of multi-module
2058packages like NumPy or PIL from having to worry about each other's
2059module names.
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002060
2061Suppose you want to design a collection of modules (a ``package'') for
2062the uniform handling of sound files and sound data. There are many
2063different sound file formats (usually recognized by their extension,
2064e.g. \file{.wav}, \file{.aiff}, \file{.au}), so you may need to create
2065and maintain a growing collection of modules for the conversion
2066between the various file formats. There are also many different
2067operations you might want to perform on sound data (e.g. mixing,
2068adding echo, applying an equalizer function, creating an artificial
2069stereo effect), so in addition you will be writing a never-ending
2070stream of modules to perform these operations. Here's a possible
2071structure for your package (expressed in terms of a hierarchical
2072filesystem):
2073
2074\begin{verbatim}
2075Sound/ Top-level package
2076 __init__.py Initialize the sound package
2077 Formats/ Subpackage for file format conversions
2078 __init__.py
2079 wavread.py
2080 wavwrite.py
2081 aiffread.py
2082 aiffwrite.py
2083 auread.py
2084 auwrite.py
2085 ...
2086 Effects/ Subpackage for sound effects
2087 __init__.py
2088 echo.py
2089 surround.py
2090 reverse.py
2091 ...
2092 Filters/ Subpackage for filters
2093 __init__.py
2094 equalizer.py
2095 vocoder.py
2096 karaoke.py
2097 ...
2098\end{verbatim}
2099The \file{__init__.py} files are required to make Python treat the
2100directories as containing packages; this is done to prevent
2101directories with a common name, such as \samp{string}, from
2102unintentionally hiding valid modules that occur later on the module
2103search path. In the simplest case, \file{__init__.py} can just be an
2104empty file, but it can also execute initialization code for the
2105package or set the \code{__all__} variable, described later.
2106
2107Users of the package can import individual modules from the
2108package, for example:
2109
2110\begin{verbatim}
2111import Sound.Effects.echo
2112\end{verbatim}
2113This loads the submodule \module{Sound.Effects.echo}. It must be referenced
2114with its full name, e.g.
2115
2116\begin{verbatim}
2117Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
2118\end{verbatim}
2119An alternative way of importing the submodule is:
2120
2121\begin{verbatim}
2122from Sound.Effects import echo
2123\end{verbatim}
2124This also loads the submodule \module{echo}, and makes it available without
2125its package prefix, so it can be used as follows:
2126
2127\begin{verbatim}
2128echo.echofilter(input, output, delay=0.7, atten=4)
2129\end{verbatim}
2130
2131Yet another variation is to import the desired function or variable directly:
2132
2133\begin{verbatim}
2134from Sound.Effects.echo import echofilter
2135\end{verbatim}
2136
2137Again, this loads the submodule \module{echo}, but this makes its function
2138echofilter directly available:
2139
2140\begin{verbatim}
2141echofilter(input, output, delay=0.7, atten=4)
2142\end{verbatim}
2143
2144Note that when using \code{from \var{package} import \var{item}}, the
2145item can be either a submodule (or subpackage) of the package, or some
2146other name defined in the package, like a function, class or
2147variable. The \code{import} statement first tests whether the item is
2148defined in the package; if not, it assumes it is a module and attempts
2149to load it. If it fails to find it, \exception{ImportError} is raised.
2150
2151Contrarily, when using syntax like \code{import
2152\var{item.subitem.subsubitem}}, each item except for the last must be
2153a package; the last item can be a module or a package but can't be a
2154class or function or variable defined in the previous item.
2155
Fred Drakeb7833d31998-09-11 16:21:55 +00002156\subsection{Importing * From a Package \label{pkg-import-star}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002157%The \code{__all__} Attribute
2158
2159Now what happens when the user writes \code{from Sound.Effects import
2160*}? Ideally, one would hope that this somehow goes out to the
2161filesystem, finds which submodules are present in the package, and
2162imports them all. Unfortunately, this operation does not work very
2163well on Mac and Windows platforms, where the filesystem does not
2164always have accurate information about the case of a filename! On
2165these platforms, there is no guaranteed way to know whether a file
2166\file{ECHO.PY} should be imported as a module \module{echo},
2167\module{Echo} or \module{ECHO}. (For example, Windows 95 has the
2168annoying practice of showing all file names with a capitalized first
2169letter.) The DOS 8+3 filename restriction adds another interesting
2170problem for long module names.
2171
2172The only solution is for the package author to provide an explicit
2173index of the package. The import statement uses the following
2174convention: if a package's \file{__init__.py} code defines a list named
2175\code{__all__}, it is taken to be the list of module names that should be imported
2176when \code{from \var{package} import *} is
2177encountered. It is up to the package author to keep this list
2178up-to-date when a new version of the package is released. Package
2179authors may also decide not to support it, if they don't see a use for
2180importing * from their package. For example, the file
2181\code{Sounds/Effects/__init__.py} could contain the following code:
2182
2183\begin{verbatim}
2184__all__ = ["echo", "surround", "reverse"]
2185\end{verbatim}
2186
2187This would mean that \code{from Sound.Effects import *} would
2188import the three named submodules of the \module{Sound} package.
2189
2190If \code{__all__} is not defined, the statement \code{from Sound.Effects
2191import *} does \emph{not} import all submodules from the package
2192\module{Sound.Effects} into the current namespace; it only ensures that the
2193package \module{Sound.Effects} has been imported (possibly running its
2194initialization code, \file{__init__.py}) and then imports whatever names are
2195defined in the package. This includes any names defined (and
2196submodules explicitly loaded) by \file{__init__.py}. It also includes any
2197submodules of the package that were explicitly loaded by previous
2198import statements, e.g.
2199
2200\begin{verbatim}
2201import Sound.Effects.echo
2202import Sound.Effects.surround
2203from Sound.Effects import *
2204\end{verbatim}
2205
2206
2207In this example, the echo and surround modules are imported in the
2208current namespace because they are defined in the \module{Sound.Effects}
2209package when the \code{from...import} statement is executed. (This also
2210works when \code{__all__} is defined.)
2211
2212Note that in general the practicing of importing * from a module or
2213package is frowned upon, since it often causes poorly readable code.
2214However, it is okay to use it to save typing in interactive sessions,
2215and certain modules are designed to export only names that follow
2216certain patterns.
2217
2218Remember, there is nothing wrong with using \code{from Package
2219import specific_submodule}! In fact, this is the
2220recommended notation unless the importing module needs to use
2221submodules with the same name from different packages.
2222
2223
2224\subsection{Intra-package References}
2225
2226The submodules often need to refer to each other. For example, the
2227\module{surround} module might use the \module{echo} module. In fact, such references
2228are so common that the \code{import} statement first looks in the
2229containing package before looking in the standard module search path.
2230Thus, the surround module can simply use \code{import echo} or
2231\code{from echo import echofilter}. If the imported module is not
2232found in the current package (the package of which the current module
2233is a submodule), the \code{import} statement looks for a top-level module
2234with the given name.
2235
2236When packages are structured into subpackages (as with the \module{Sound}
2237package in the example), there's no shortcut to refer to submodules of
2238sibling packages - the full name of the subpackage must be used. For
2239example, if the module \module{Sound.Filters.vocoder} needs to use the \module{echo}
2240module in the \module{Sound.Effects} package, it can use \code{from
2241Sound.Effects import echo}.
2242
2243%(One could design a notation to refer to parent packages, similar to
2244%the use of ".." to refer to the parent directory in Unix and Windows
2245%filesystems. In fact, the \module{ni} module, which was the
2246%ancestor of this package system, supported this using \code{__} for
2247%the package containing the current module,
2248%\code{__.__} for the parent package, and so on. This feature was dropped
2249%because of its awkwardness; since most packages will have a relative
2250%shallow substructure, this is no big loss.)
2251
2252
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002253
Fred Drakeb7833d31998-09-11 16:21:55 +00002254\chapter{Input and Output \label{io}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002255
Guido van Rossum02455691997-07-17 16:21:52 +00002256There are several ways to present the output of a program; data can be
2257printed in a human-readable form, or written to a file for future use.
2258This chapter will discuss some of the possibilities.
2259
Fred Drakeb7833d31998-09-11 16:21:55 +00002260
2261\section{Fancier Output Formatting \label{formatting}}
2262
Fred Drakeeee08cd1997-12-04 15:43:15 +00002263So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00002264statements} and the \keyword{print} statement. (A third way is using
2265the \method{write()} method of file objects; the standard output file
2266can be referenced as \code{sys.stdout}. See the Library Reference for
2267more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002268
2269Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00002270simply printing space-separated values. There are two ways to format
2271your output; the first way is to do all the string handling yourself;
2272using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00002273lay-out you can imagine. The standard module
2274\module{string}\refstmodindex{string} contains some useful operations
2275for padding strings to a given column width;
Guido van Rossum02455691997-07-17 16:21:52 +00002276these will be discussed shortly. The second way is to use the
2277\code{\%} operator with a string as the left argument. \code{\%}
Fred Drakeee84d591999-03-10 17:25:30 +00002278interprets the left argument as a C \cfunction{sprintf()}-style
Fred Drake8842e861998-02-13 07:16:30 +00002279format string to be applied to the right argument, and returns the
2280string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002281
2282One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00002283Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00002284the \function{repr()} function, or just write the value between
2285reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002286
Fred Drake8842e861998-02-13 07:16:30 +00002287\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002288>>> x = 10 * 3.14
2289>>> y = 200*200
2290>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2291>>> print s
2292The value of x is 31.4, and y is 40000...
2293>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00002294... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00002295>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002296>>> ps
2297'[31.4, 40000]'
2298>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00002299... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002300>>> hellos = `hello`
2301>>> print hellos
2302'hello, world\012'
2303>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002304... `x, y, ('spam', 'eggs')`
2305"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00002306\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002307
Guido van Rossum6938f061994-08-01 12:22:53 +00002308Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002309
Fred Drake8842e861998-02-13 07:16:30 +00002310\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002311>>> import string
2312>>> for x in range(1, 11):
2313... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
2314... # Note trailing comma on previous line
2315... print string.rjust(`x*x*x`, 4)
2316...
2317 1 1 1
2318 2 4 8
2319 3 9 27
2320 4 16 64
2321 5 25 125
2322 6 36 216
2323 7 49 343
2324 8 64 512
2325 9 81 729
232610 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002327>>> for x in range(1,11):
2328... print '%2d %3d %4d' % (x, x*x, x*x*x)
2329...
2330 1 1 1
2331 2 4 8
2332 3 9 27
2333 4 16 64
2334 5 25 125
2335 6 36 216
2336 7 49 343
2337 8 64 512
2338 9 81 729
233910 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002340\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002341
Fred Drake8842e861998-02-13 07:16:30 +00002342(Note that one space between each column was added by the way
2343\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002344
Fred Drake8842e861998-02-13 07:16:30 +00002345This example demonstrates the function \function{string.rjust()},
2346which right-justifies a string in a field of a given width by padding
2347it with spaces on the left. There are similar functions
2348\function{string.ljust()} and \function{string.center()}. These
2349functions do not write anything, they just return a new string. If
2350the input string is too long, they don't truncate it, but return it
2351unchanged; this will mess up your column lay-out but that's usually
2352better than the alternative, which would be lying about a value. (If
2353you really want truncation you can always add a slice operation, as in
2354\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002355
Fred Drake8842e861998-02-13 07:16:30 +00002356There is another function, \function{string.zfill()}, which pads a
2357numeric string on the left with zeros. It understands about plus and
2358minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002359
Fred Drake8842e861998-02-13 07:16:30 +00002360\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002361>>> string.zfill('12', 5)
2362'00012'
2363>>> string.zfill('-3.14', 7)
2364'-003.14'
2365>>> string.zfill('3.14159265359', 5)
2366'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002367\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002368%
2369Using the \code{\%} operator looks like this:
2370
2371\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002372>>> import math
2373>>> print 'The value of PI is approximately %5.3f.' % math.pi
2374The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002375\end{verbatim}
2376
2377If there is more than one format in the string you pass a tuple as
2378right operand, e.g.
2379
2380\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002381>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2382>>> for name, phone in table.items():
2383... print '%-10s ==> %10d' % (name, phone)
2384...
2385Jack ==> 4098
2386Dcab ==> 8637678
2387Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002388\end{verbatim}
2389
Fred Drakeee84d591999-03-10 17:25:30 +00002390Most formats work exactly as in C and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002391type; however, if you don't you get an exception, not a core dump.
Fred Drakedb70d061998-11-17 21:59:04 +00002392The \code{\%s} format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002393not a string object, it is converted to string using the
2394\function{str()} built-in function. Using \code{*} to pass the width
2395or precision in as a separate (integer) argument is supported. The
Fred Drakeee84d591999-03-10 17:25:30 +00002396C formats \code{\%n} and \code{\%p} are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002397
2398If you have a really long format string that you don't want to split
2399up, it would be nice if you could reference the variables to be
2400formatted by name instead of by position. This can be done by using
Fred Drakeee84d591999-03-10 17:25:30 +00002401an extension of C formats using the form \code{\%(name)format}, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002402
2403\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002404>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2405>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2406Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002407\end{verbatim}
2408
2409This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002410\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002411local variables.
2412
Fred Drakeb7833d31998-09-11 16:21:55 +00002413\section{Reading and Writing Files \label{files}}
Fred Drake6c2176e1998-02-26 21:47:54 +00002414
Guido van Rossum02455691997-07-17 16:21:52 +00002415% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002416\function{open()}\bifuncindex{open} returns a file
2417object\obindex{file}, and is most commonly used with two arguments:
2418\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002419
Fred Drake8842e861998-02-13 07:16:30 +00002420\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002421>>> f=open('/tmp/workfile', 'w')
2422>>> print f
2423<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002424\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002425
Guido van Rossum02455691997-07-17 16:21:52 +00002426The first argument is a string containing the filename. The second
2427argument is another string containing a few characters describing the
2428way in which the file will be used. \var{mode} can be \code{'r'} when
2429the file will only be read, \code{'w'} for only writing (an existing
2430file with the same name will be erased), and \code{'a'} opens the file
2431for appending; any data written to the file is automatically added to
2432the end. \code{'r+'} opens the file for both reading and writing.
2433The \var{mode} argument is optional; \code{'r'} will be assumed if
2434it's omitted.
2435
Fred Drake391564f1998-04-01 23:11:56 +00002436On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00002437mode opens the file in binary mode, so there are also modes like
2438\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2439distinction between text and binary files; the end-of-line characters
2440in text files are automatically altered slightly when data is read or
2441written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002442\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2443\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00002444writing such files. (Note that the precise semantics of text mode on
Fred Drakeee84d591999-03-10 17:25:30 +00002445the Macintosh depends on the underlying C library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00002446
Fred Drakeb7833d31998-09-11 16:21:55 +00002447\subsection{Methods of File Objects \label{fileMethods}}
Guido van Rossum02455691997-07-17 16:21:52 +00002448
2449The rest of the examples in this section will assume that a file
2450object called \code{f} has already been created.
2451
2452To read a file's contents, call \code{f.read(\var{size})}, which reads
2453some quantity of data and returns it as a string. \var{size} is an
2454optional numeric argument. When \var{size} is omitted or negative,
2455the entire contents of the file will be read and returned; it's your
2456problem if the file is twice as large as your machine's memory.
2457Otherwise, at most \var{size} bytes are read and returned. If the end
2458of the file has been reached, \code{f.read()} will return an empty
2459string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002460\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002461>>> f.read()
2462'This is the entire file.\012'
2463>>> f.read()
2464''
Fred Drake8842e861998-02-13 07:16:30 +00002465\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002466
Guido van Rossum02455691997-07-17 16:21:52 +00002467\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002468character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002469omitted on the last line of the file if the file doesn't end in a
2470newline. This makes the return value unambiguous; if
2471\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002472been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002473string containing only a single newline.
2474
Fred Drake8842e861998-02-13 07:16:30 +00002475\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002476>>> f.readline()
2477'This is the first line of the file.\012'
2478>>> f.readline()
2479'Second line of the file\012'
2480>>> f.readline()
2481''
Fred Drake8842e861998-02-13 07:16:30 +00002482\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002483
Fred Drakeeee08cd1997-12-04 15:43:15 +00002484\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002485a list containing all the lines of data in the file.
2486
Fred Drake8842e861998-02-13 07:16:30 +00002487\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002488>>> f.readlines()
2489['This is the first line of the file.\012', 'Second line of the file\012']
Fred Drake8842e861998-02-13 07:16:30 +00002490\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002491
Guido van Rossum02455691997-07-17 16:21:52 +00002492\code{f.write(\var{string})} writes the contents of \var{string} to
2493the file, returning \code{None}.
2494
Fred Drake8842e861998-02-13 07:16:30 +00002495\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002496>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002497\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002498
Guido van Rossum02455691997-07-17 16:21:52 +00002499\code{f.tell()} returns an integer giving the file object's current
2500position in the file, measured in bytes from the beginning of the
2501file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002502\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002503computed from adding \var{offset} to a reference point; the reference
2504point is selected by the \var{from_what} argument. A \var{from_what}
2505value of 0 measures from the beginning of the file, 1 uses the current
2506file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002507\var{from_what} can be omitted and defaults to 0, using the beginning
2508of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002509
Fred Drake8842e861998-02-13 07:16:30 +00002510\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002511>>> f=open('/tmp/workfile', 'r+')
2512>>> f.write('0123456789abcdef')
2513>>> f.seek(5) # Go to the 5th byte in the file
2514>>> f.read(1)
2515'5'
2516>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2517>>> f.read(1)
2518'd'
Fred Drake8842e861998-02-13 07:16:30 +00002519\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002520
Guido van Rossum02455691997-07-17 16:21:52 +00002521When you're done with a file, call \code{f.close()} to close it and
2522free up any system resources taken up by the open file. After calling
2523\code{f.close()}, attempts to use the file object will automatically fail.
2524
Fred Drake8842e861998-02-13 07:16:30 +00002525\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002526>>> f.close()
2527>>> f.read()
2528Traceback (innermost last):
2529 File "<stdin>", line 1, in ?
2530ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002531\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002532
Fred Drake8842e861998-02-13 07:16:30 +00002533File objects have some additional methods, such as \method{isatty()}
2534and \method{truncate()} which are less frequently used; consult the
2535Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002536
Fred Drakeb7833d31998-09-11 16:21:55 +00002537\subsection{The \module{pickle} Module \label{pickle}}
Fred Drake391564f1998-04-01 23:11:56 +00002538\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00002539
2540Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002541bit more effort, since the \method{read()} method only returns
2542strings, which will have to be passed to a function like
2543\function{string.atoi()}, which takes a string like \code{'123'} and
2544returns its numeric value 123. However, when you want to save more
2545complex data types like lists, dictionaries, or class instances,
2546things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002547
2548Rather than have users be constantly writing and debugging code to
2549save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002550\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002551any Python object (even some forms of Python code!), and convert it to
2552a string representation; this process is called \dfn{pickling}.
2553Reconstructing the object from the string representation is called
2554\dfn{unpickling}. Between pickling and unpickling, the string
2555representing the object may have been stored in a file or data, or
2556sent over a network connection to some distant machine.
2557
2558If you have an object \code{x}, and a file object \code{f} that's been
2559opened for writing, the simplest way to pickle the object takes only
2560one line of code:
2561
Fred Drake8842e861998-02-13 07:16:30 +00002562\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002563pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002564\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002565
Fred Drake8842e861998-02-13 07:16:30 +00002566To unpickle the object again, if \code{f} is a file object which has
2567been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002568
Fred Drake8842e861998-02-13 07:16:30 +00002569\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002570x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002571\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002572
Guido van Rossum02455691997-07-17 16:21:52 +00002573(There are other variants of this, used when pickling many objects or
2574when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002575complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002576
Fred Drake8842e861998-02-13 07:16:30 +00002577\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002578stored and reused by other programs or by a future invocation of the
2579same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002580object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002581write Python extensions take care to ensure that new data types such
Fred Drake72389881998-04-13 01:31:10 +00002582as matrices can be properly pickled and unpickled.
Guido van Rossum02455691997-07-17 16:21:52 +00002583
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002584
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002585
Fred Drakeb7833d31998-09-11 16:21:55 +00002586\chapter{Errors and Exceptions \label{errors}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002587
2588Until now error messages haven't been more than mentioned, but if you
2589have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002590(at least) two distinguishable kinds of errors: \emph{syntax errors}
2591and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002592
Fred Drakeb7833d31998-09-11 16:21:55 +00002593\section{Syntax Errors \label{syntaxErrors}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002594
2595Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002596kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002597
Fred Drake8842e861998-02-13 07:16:30 +00002598\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002599>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002600 File "<stdin>", line 1
2601 while 1 print 'Hello world'
2602 ^
2603SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002604\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002605
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002606The parser repeats the offending line and displays a little `arrow'
2607pointing at the earliest point in the line where the error was detected.
2608The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002609\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002610the arrow: in the example, the error is detected at the keyword
Fred Drake391564f1998-04-01 23:11:56 +00002611\keyword{print}, since a colon (\character{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002612File name and line number are printed so you know where to look in case
2613the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002614
Fred Drakeb7833d31998-09-11 16:21:55 +00002615\section{Exceptions \label{exceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002616
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002617Even if a statement or expression is syntactically correct, it may
2618cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002619Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002620not unconditionally fatal: you will soon learn how to handle them in
2621Python programs. Most exceptions are not handled by programs,
2622however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002623
Fred Drake8842e861998-02-13 07:16:30 +00002624\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002625>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002626Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002627 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002628ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002629>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002630Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002631 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002632NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002633>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002634Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002635 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002636TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002637\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002638
Guido van Rossumb2c65561993-05-12 08:53:36 +00002639The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002640Exceptions come in different types, and the type is printed as part of
2641the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002642\exception{ZeroDivisionError},
2643\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002644and
Fred Drake8842e861998-02-13 07:16:30 +00002645\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002646The string printed as the exception type is the name of the built-in
2647name for the exception that occurred. This is true for all built-in
2648exceptions, but need not be true for user-defined exceptions (although
2649it is a useful convention).
2650Standard exception names are built-in identifiers (not reserved
2651keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002652
Guido van Rossumb2c65561993-05-12 08:53:36 +00002653The rest of the line is a detail whose interpretation depends on the
2654exception type; its meaning is dependent on the exception type.
2655
2656The preceding part of the error message shows the context where the
2657exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002658In general it contains a stack backtrace listing source lines; however,
2659it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002660
Fred Drake8842e861998-02-13 07:16:30 +00002661The Library Reference lists the built-in exceptions and their
2662meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002663
Fred Drakeb7833d31998-09-11 16:21:55 +00002664\section{Handling Exceptions \label{handling}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002665
2666It is possible to write programs that handle selected exceptions.
2667Look at the following example, which prints a table of inverses of
2668some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002669
Fred Drake8842e861998-02-13 07:16:30 +00002670\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002671>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002672>>> for x in numbers:
2673... print x,
2674... try:
2675... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002676... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002677... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002678...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000026790.3333 3.00030003
26802.5 0.4
26810 *** has no inverse ***
268210 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002683\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002684
Fred Drake8842e861998-02-13 07:16:30 +00002685The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002686\begin{itemize}
2687\item
Fred Drake8842e861998-02-13 07:16:30 +00002688First, the \emph{try clause}
2689(the statement(s) between the \keyword{try} and \keyword{except}
2690keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002691\item
2692If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002693\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002694is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002695\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002696If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002697the rest of the clause is skipped. Then if its type matches the
2698exception named after the \keyword{except} keyword, the rest of the
2699try clause is skipped, the except clause is executed, and then
2700execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002701\item
2702If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002703except clause, it is passed on to outer \keyword{try} statements; if
2704no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002705and execution stops with a message as shown above.
2706\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002707A \keyword{try} statement may have more than one except clause, to
2708specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002709At most one handler will be executed.
2710Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002711clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002712An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002713e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002714
Fred Drake8842e861998-02-13 07:16:30 +00002715\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002716... except (RuntimeError, TypeError, NameError):
2717... pass
Fred Drake8842e861998-02-13 07:16:30 +00002718\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002719
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002720The last except clause may omit the exception name(s), to serve as a
2721wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002722Use this with extreme caution, since it is easy to mask a real
2723programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002724
Fred Drake8842e861998-02-13 07:16:30 +00002725The \keyword{try} \ldots\ \keyword{except} statement has an optional
2726\emph{else clause}, which must follow all except clauses. It is
2727useful to place code that must be executed if the try clause does not
2728raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002729
2730\begin{verbatim}
Guido van Rossuma4289a71998-07-07 20:18:06 +00002731for arg in sys.argv[1:]:
Fred Drake8842e861998-02-13 07:16:30 +00002732 try:
2733 f = open(arg, 'r')
2734 except IOError:
2735 print 'cannot open', arg
2736 else:
2737 print arg, 'has', len(f.readlines()), 'lines'
2738 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002739\end{verbatim}
2740
2741
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002742When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002743the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002744The presence and type of the argument depend on the exception type.
2745For exception types which have an argument, the except clause may
2746specify a variable after the exception name (or list) to receive the
2747argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002748
Fred Drake8842e861998-02-13 07:16:30 +00002749\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002750>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002751... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002752... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002753... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002754...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002755name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002756\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002757
Guido van Rossumb2c65561993-05-12 08:53:36 +00002758If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002759(`detail') of the message for unhandled exceptions.
2760
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002761Exception handlers don't just handle exceptions if they occur
2762immediately in the try clause, but also if they occur inside functions
2763that are called (even indirectly) in the try clause.
2764For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002765
Fred Drake8842e861998-02-13 07:16:30 +00002766\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002767>>> def this_fails():
2768... x = 1/0
2769...
2770>>> try:
2771... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002772... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002773... print 'Handling run-time error:', detail
2774...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002775Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002776\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002777
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002778
Fred Drakeb7833d31998-09-11 16:21:55 +00002779\section{Raising Exceptions \label{raising}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002780
Fred Drake8842e861998-02-13 07:16:30 +00002781The \keyword{raise} statement allows the programmer to force a
2782specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002783For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002784
Fred Drake8842e861998-02-13 07:16:30 +00002785\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002786>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002787Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002788 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002789NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002790\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002791
Fred Drake8842e861998-02-13 07:16:30 +00002792The first argument to \keyword{raise} names the exception to be
2793raised. The optional second argument specifies the exception's
2794argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002795
Guido van Rossum02455691997-07-17 16:21:52 +00002796
Fred Drakeb7833d31998-09-11 16:21:55 +00002797\section{User-defined Exceptions \label{userExceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002798
2799Programs may name their own exceptions by assigning a string to a
2800variable.
2801For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002802
Fred Drake8842e861998-02-13 07:16:30 +00002803\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002804>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002805>>> try:
2806... raise my_exc, 2*2
2807... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002808... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002809...
Guido van Rossum6938f061994-08-01 12:22:53 +00002810My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002811>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002812Traceback (innermost last):
2813 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002814my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002815\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002816
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002817Many standard modules use this to report errors that may occur in
2818functions they define.
2819
Guido van Rossum02455691997-07-17 16:21:52 +00002820
Fred Drakeb7833d31998-09-11 16:21:55 +00002821\section{Defining Clean-up Actions \label{cleanup}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002822
Fred Drake8842e861998-02-13 07:16:30 +00002823The \keyword{try} statement has another optional clause which is
2824intended to define clean-up actions that must be executed under all
2825circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002826
Fred Drake8842e861998-02-13 07:16:30 +00002827\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002828>>> try:
2829... raise KeyboardInterrupt
2830... finally:
2831... print 'Goodbye, world!'
2832...
2833Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002834Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002835 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002836KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002837\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002838
Fred Drake8842e861998-02-13 07:16:30 +00002839A \emph{finally clause} is executed whether or not an exception has
2840occurred in the try clause. When an exception has occurred, it is
2841re-raised after the finally clause is executed. The finally clause is
2842also executed ``on the way out'' when the \keyword{try} statement is
2843left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002844
Fred Drake8842e861998-02-13 07:16:30 +00002845A \keyword{try} statement must either have one or more except clauses
2846or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002847
Fred Drakeb7833d31998-09-11 16:21:55 +00002848\chapter{Classes \label{classes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002849
2850Python's class mechanism adds classes to the language with a minimum
2851of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002852found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002853do not put an absolute barrier between definition and user, but rather
2854rely on the politeness of the user not to ``break into the
2855definition.'' The most important features of classes are retained
2856with full power, however: the class inheritance mechanism allows
2857multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00002858base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002859same name. Objects can contain an arbitrary amount of private data.
2860
Guido van Rossum16d6e711994-08-08 12:30:22 +00002861In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002862\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002863no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002864shorthands for referencing the object's members from its methods: the
2865method function is declared with an explicit first argument
2866representing the object, which is provided implicitly by the call. As
2867in Smalltalk, classes themselves are objects, albeit in the wider
2868sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002869provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002870or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002871extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002872built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00002873subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002874
Fred Drakeb7833d31998-09-11 16:21:55 +00002875\section{A Word About Terminology \label{terminology}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002876
Fred Drake391564f1998-04-01 23:11:56 +00002877Lacking universally accepted terminology to talk about classes, I will
2878make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002879terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002880Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002881
2882I also have to warn you that there's a terminological pitfall for
2883object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002884necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2885unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00002886built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00002887exotic types like files aren't. However, \emph{all} Python types
2888share a little bit of common semantics that is best described by using
2889the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002890
2891Objects have individuality, and multiple names (in multiple scopes)
2892can be bound to the same object. This is known as aliasing in other
2893languages. This is usually not appreciated on a first glance at
2894Python, and can be safely ignored when dealing with immutable basic
2895types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002896(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002897objects such as lists, dictionaries, and most types representing
2898entities outside the program (files, windows, etc.). This is usually
2899used to the benefit of the program, since aliases behave like pointers
2900in some respects. For example, passing an object is cheap since only
2901a pointer is passed by the implementation; and if a function modifies
2902an object passed as an argument, the caller will see the change --- this
2903obviates the need for two different argument passing mechanisms as in
2904Pascal.
2905
2906
Fred Drakeb7833d31998-09-11 16:21:55 +00002907\section{Python Scopes and Name Spaces \label{scopes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002908
2909Before introducing classes, I first have to tell you something about
2910Python's scope rules. Class definitions play some neat tricks with
2911name spaces, and you need to know how scopes and name spaces work to
2912fully understand what's going on. Incidentally, knowledge about this
2913subject is useful for any advanced Python programmer.
2914
2915Let's begin with some definitions.
2916
Fred Drakeeee08cd1997-12-04 15:43:15 +00002917A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002918spaces are currently implemented as Python dictionaries, but that's
2919normally not noticeable in any way (except for performance), and it
2920may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002921built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002922names); the global names in a module; and the local names in a
2923function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002924also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002925spaces is that there is absolutely no relation between names in
2926different name spaces; for instance, two different modules may both
2927define a function ``maximize'' without confusion --- users of the
2928modules must prefix it with the module name.
2929
Fred Drakeeee08cd1997-12-04 15:43:15 +00002930By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002931dot --- for example, in the expression \code{z.real}, \code{real} is
2932an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002933names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002934\code{modname.funcname}, \code{modname} is a module object and
2935\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002936be a straightforward mapping between the module's attributes and the
Fred Drake93aa0f21999-04-05 21:39:17 +00002937global names defined in the module: they share the same name
2938space!\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002939 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002940 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002941 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002942 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002943 Obviously, using this violates the abstraction of name space
2944 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002945 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002946}
2947
2948Attributes may be read-only or writable. In the latter case,
2949assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002950you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drake391564f1998-04-01 23:11:56 +00002951also be deleted with the \keyword{del} statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002952\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002953
2954Name spaces are created at different moments and have different
2955lifetimes. The name space containing the built-in names is created
2956when the Python interpreter starts up, and is never deleted. The
2957global name space for a module is created when the module definition
2958is read in; normally, module name spaces also last until the
2959interpreter quits. The statements executed by the top-level
2960invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002961interactively, are considered part of a module called
2962\module{__main__}, so they have their own global name space. (The
2963built-in names actually also live in a module; this is called
2964\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002965
2966The local name space for a function is created when the function is
2967called, and deleted when the function returns or raises an exception
2968that is not handled within the function. (Actually, forgetting would
2969be a better way to describe what actually happens.) Of course,
2970recursive invocations each have their own local name space.
2971
Fred Drakeeee08cd1997-12-04 15:43:15 +00002972A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002973is directly accessible. ``Directly accessible'' here means that an
2974unqualified reference to a name attempts to find the name in the name
2975space.
2976
2977Although scopes are determined statically, they are used dynamically.
2978At any time during execution, exactly three nested scopes are in use
2979(i.e., exactly three name spaces are directly accessible): the
2980innermost scope, which is searched first, contains the local names,
2981the middle scope, searched next, contains the current module's global
2982names, and the outermost scope (searched last) is the name space
2983containing built-in names.
2984
2985Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00002986current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002987the same name space as the global scope: the module's name space.
2988Class definitions place yet another name space in the local scope.
2989
2990It is important to realize that scopes are determined textually: the
2991global scope of a function defined in a module is that module's name
2992space, no matter from where or by what alias the function is called.
2993On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00002994run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002995static name resolution, at ``compile'' time, so don't rely on dynamic
2996name resolution! (In fact, local variables are already determined
2997statically.)
2998
2999A special quirk of Python is that assignments always go into the
3000innermost scope. Assignments do not copy data --- they just
3001bind names to objects. The same is true for deletions: the statement
Fred Drake391564f1998-04-01 23:11:56 +00003002\samp{del x} removes the binding of \code{x} from the name space
3003referenced by the local scope. In fact, all operations that introduce
3004new names use the local scope: in particular, import statements and
3005function definitions bind the module or function name in the local
3006scope. (The \keyword{global} statement can be used to indicate that
3007particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003008
3009
Fred Drakeb7833d31998-09-11 16:21:55 +00003010\section{A First Look at Classes \label{firstClasses}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003011
3012Classes introduce a little bit of new syntax, three new object types,
3013and some new semantics.
3014
3015
Fred Drakeb7833d31998-09-11 16:21:55 +00003016\subsection{Class Definition Syntax \label{classDefinition}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003017
3018The simplest form of class definition looks like this:
3019
3020\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003021class ClassName:
3022 <statement-1>
3023 .
3024 .
3025 .
3026 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003027\end{verbatim}
3028
Fred Drake8842e861998-02-13 07:16:30 +00003029Class definitions, like function definitions (\keyword{def}
3030statements) must be executed before they have any effect. (You could
3031conceivably place a class definition in a branch of an \keyword{if}
3032statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003033
3034In practice, the statements inside a class definition will usually be
3035function definitions, but other statements are allowed, and sometimes
3036useful --- we'll come back to this later. The function definitions
3037inside a class normally have a peculiar form of argument list,
3038dictated by the calling conventions for methods --- again, this is
3039explained later.
3040
3041When a class definition is entered, a new name space is created, and
3042used as the local scope --- thus, all assignments to local variables
3043go into this new name space. In particular, function definitions bind
3044the name of the new function here.
3045
Fred Drakeeee08cd1997-12-04 15:43:15 +00003046When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003047object} is created. This is basically a wrapper around the contents
3048of the name space created by the class definition; we'll learn more
3049about class objects in the next section. The original local scope
3050(the one in effect just before the class definitions was entered) is
Fred Drakea594baf1998-04-03 05:16:31 +00003051reinstated, and the class object is bound here to the class name given
3052in the class definition header (\class{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003053
3054
Fred Drakeb7833d31998-09-11 16:21:55 +00003055\subsection{Class Objects \label{classObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003056
3057Class objects support two kinds of operations: attribute references
3058and instantiation.
3059
Fred Drakeeee08cd1997-12-04 15:43:15 +00003060\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00003061attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003062names are all the names that were in the class's name space when the
3063class object was created. So, if the class definition looked like
3064this:
3065
3066\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003067class MyClass:
3068 "A simple example class"
3069 i = 12345
3070 def f(x):
3071 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003072\end{verbatim}
3073
Fred Drake8842e861998-02-13 07:16:30 +00003074then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003075references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00003076Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00003077of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00003078attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00003079the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003080
Fred Drakeeee08cd1997-12-04 15:43:15 +00003081Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003082the class object is a parameterless function that returns a new
3083instance of the class. For example, (assuming the above class):
3084
3085\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003086x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003087\end{verbatim}
3088
Fred Drakeeee08cd1997-12-04 15:43:15 +00003089creates a new \emph{instance} of the class and assigns this object to
3090the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003091
3092
Fred Drakeb7833d31998-09-11 16:21:55 +00003093\subsection{Instance Objects \label{instanceObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003094
3095Now what can we do with instance objects? The only operations
3096understood by instance objects are attribute references. There are
3097two kinds of valid attribute names.
3098
Fred Drakeeee08cd1997-12-04 15:43:15 +00003099The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00003100``instance variables'' in Smalltalk, and to ``data members'' in
3101\Cpp{}. Data attributes need not be declared; like local variables,
3102they spring into existence when they are first assigned to. For
3103example, if \code{x} is the instance of \class{MyClass} created above,
3104the following piece of code will print the value \code{16}, without
3105leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003106
3107\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003108x.counter = 1
3109while x.counter < 10:
3110 x.counter = x.counter * 2
3111print x.counter
3112del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003113\end{verbatim}
3114
3115The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00003116are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003117object. (In Python, the term method is not unique to class instances:
3118other object types can have methods as well, e.g., list objects have
3119methods called append, insert, remove, sort, and so on. However,
3120below, we'll use the term method exclusively to mean methods of class
3121instance objects, unless explicitly stated otherwise.)
3122
3123Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00003124definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003125objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00003126example, \code{x.f} is a valid method reference, since
3127\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00003128\code{MyClass.i} is not. But \code{x.f} is not the same thing as
3129\code{MyClass.f} --- it is a \emph{method object}, not a function
Fred Drakea594baf1998-04-03 05:16:31 +00003130object.%
3131\obindex{method}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003132
3133
Fred Drakeb7833d31998-09-11 16:21:55 +00003134\subsection{Method Objects \label{methodObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003135
3136Usually, a method is called immediately, e.g.:
3137
3138\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003139x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003140\end{verbatim}
3141
Fred Drake8842e861998-02-13 07:16:30 +00003142In our example, this will return the string \code{'hello world'}.
Fred Drakeee84d591999-03-10 17:25:30 +00003143However, it is not necessary to call a method right away:
3144\code{x.f} is a method object, and can be stored away and called at a
3145later time. For example:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003146
3147\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003148xf = x.f
3149while 1:
3150 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003151\end{verbatim}
3152
Fred Drake8842e861998-02-13 07:16:30 +00003153will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003154
3155What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00003156that \code{x.f()} was called without an argument above, even though
3157the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003158happened to the argument? Surely Python raises an exception when a
3159function that requires an argument is called without any --- even if
3160the argument isn't actually used...
3161
3162Actually, you may have guessed the answer: the special thing about
3163methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00003164function. In our example, the call \code{x.f()} is exactly equivalent
3165to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00003166\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003167with an argument list that is created by inserting the method's object
3168before the first argument.
3169
3170If you still don't understand how methods work, a look at the
3171implementation can perhaps clarify matters. When an instance
3172attribute is referenced that isn't a data attribute, its class is
3173searched. If the name denotes a valid class attribute that is a
3174function object, a method object is created by packing (pointers to)
3175the instance object and the function object just found together in an
3176abstract object: this is the method object. When the method object is
3177called with an argument list, it is unpacked again, a new argument
3178list is constructed from the instance object and the original argument
3179list, and the function object is called with this new argument list.
3180
3181
Fred Drakeb7833d31998-09-11 16:21:55 +00003182\section{Random Remarks \label{remarks}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003183
3184[These should perhaps be placed more carefully...]
3185
3186
3187Data attributes override method attributes with the same name; to
3188avoid accidental name conflicts, which may cause hard-to-find bugs in
3189large programs, it is wise to use some kind of convention that
3190minimizes the chance of conflicts, e.g., capitalize method names,
3191prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00003192an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003193
3194
3195Data attributes may be referenced by methods as well as by ordinary
3196users (``clients'') of an object. In other words, classes are not
3197usable to implement pure abstract data types. In fact, nothing in
3198Python makes it possible to enforce data hiding --- it is all based
3199upon convention. (On the other hand, the Python implementation,
Fred Drakeee84d591999-03-10 17:25:30 +00003200written in C, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003201access to an object if necessary; this can be used by extensions to
Fred Drakeee84d591999-03-10 17:25:30 +00003202Python written in C.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003203
3204
3205Clients should use data attributes with care --- clients may mess up
3206invariants maintained by the methods by stamping on their data
3207attributes. Note that clients may add data attributes of their own to
3208an instance object without affecting the validity of the methods, as
3209long as name conflicts are avoided --- again, a naming convention can
3210save a lot of headaches here.
3211
3212
3213There is no shorthand for referencing data attributes (or other
3214methods!) from within methods. I find that this actually increases
3215the readability of methods: there is no chance of confusing local
3216variables and instance variables when glancing through a method.
3217
3218
3219Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00003220\code{self}. This is nothing more than a convention: the name
3221\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003222however, that by not following the convention your code may be less
3223readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00003224a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003225convention.)
3226
3227
3228Any function object that is a class attribute defines a method for
3229instances of that class. It is not necessary that the function
3230definition is textually enclosed in the class definition: assigning a
3231function object to a local variable in the class is also ok. For
3232example:
3233
3234\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003235# Function defined outside the class
3236def f1(self, x, y):
3237 return min(x, x+y)
3238
3239class C:
3240 f = f1
3241 def g(self):
3242 return 'hello world'
3243 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003244\end{verbatim}
3245
Fred Drake8842e861998-02-13 07:16:30 +00003246Now \code{f}, \code{g} and \code{h} are all attributes of class
3247\class{C} that refer to function objects, and consequently they are all
3248methods of instances of \class{C} --- \code{h} being exactly equivalent
3249to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003250the reader of a program.
3251
3252
3253Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00003254\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003255
3256\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003257class Bag:
3258 def empty(self):
3259 self.data = []
3260 def add(self, x):
3261 self.data.append(x)
3262 def addtwice(self, x):
3263 self.add(x)
3264 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003265\end{verbatim}
3266
3267
3268The instantiation operation (``calling'' a class object) creates an
3269empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00003270state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00003271\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003272
Guido van Rossum6938f061994-08-01 12:22:53 +00003273\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003274 def __init__(self):
3275 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00003276\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003277
Fred Drake8842e861998-02-13 07:16:30 +00003278When a class defines an \method{__init__()} method, class
3279instantiation automatically invokes \method{__init__()} for the
3280newly-created class instance. So in the \class{Bag} example, a new
3281and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003282
Guido van Rossum6938f061994-08-01 12:22:53 +00003283\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003284x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00003285\end{verbatim}
3286
Fred Drake8842e861998-02-13 07:16:30 +00003287Of course, the \method{__init__()} method may have arguments for
3288greater flexibility. In that case, arguments given to the class
3289instantiation operator are passed on to \method{__init__()}. For
3290example,
Guido van Rossum6938f061994-08-01 12:22:53 +00003291
Fred Drake8842e861998-02-13 07:16:30 +00003292\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00003293>>> class Complex:
3294... def __init__(self, realpart, imagpart):
3295... self.r = realpart
3296... self.i = imagpart
3297...
3298>>> x = Complex(3.0,-4.5)
3299>>> x.r, x.i
3300(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00003301\end{verbatim}
3302
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003303Methods may reference global names in the same way as ordinary
3304functions. The global scope associated with a method is the module
3305containing the class definition. (The class itself is never used as a
3306global scope!) While one rarely encounters a good reason for using
3307global data in a method, there are many legitimate uses of the global
3308scope: for one thing, functions and modules imported into the global
3309scope can be used by methods, as well as functions and classes defined
3310in it. Usually, the class containing the method is itself defined in
3311this global scope, and in the next section we'll find some good
3312reasons why a method would want to reference its own class!
3313
3314
Fred Drakeb7833d31998-09-11 16:21:55 +00003315\section{Inheritance \label{inheritance}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003316
3317Of course, a language feature would not be worthy of the name ``class''
3318without supporting inheritance. The syntax for a derived class
3319definition looks as follows:
3320
3321\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003322class DerivedClassName(BaseClassName):
3323 <statement-1>
3324 .
3325 .
3326 .
3327 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003328\end{verbatim}
3329
Fred Drake8842e861998-02-13 07:16:30 +00003330The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003331the derived class definition. Instead of a base class name, an
3332expression is also allowed. This is useful when the base class is
3333defined in another module, e.g.,
3334
3335\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003336class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003337\end{verbatim}
3338
3339Execution of a derived class definition proceeds the same as for a
3340base class. When the class object is constructed, the base class is
3341remembered. This is used for resolving attribute references: if a
3342requested attribute is not found in the class, it is searched in the
3343base class. This rule is applied recursively if the base class itself
3344is derived from some other class.
3345
3346There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00003347\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003348references are resolved as follows: the corresponding class attribute
3349is searched, descending down the chain of base classes if necessary,
3350and the method reference is valid if this yields a function object.
3351
3352Derived classes may override methods of their base classes. Because
3353methods have no special privileges when calling other methods of the
3354same object, a method of a base class that calls another method
3355defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003356a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003357in Python are ``virtual functions''.)
3358
3359An overriding method in a derived class may in fact want to extend
3360rather than simply replace the base class method of the same name.
3361There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003362call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003363occasionally useful to clients as well. (Note that this only works if
3364the base class is defined or imported directly in the global scope.)
3365
3366
Fred Drakeb7833d31998-09-11 16:21:55 +00003367\subsection{Multiple Inheritance \label{multiple}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003368
Guido van Rossum6938f061994-08-01 12:22:53 +00003369Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003370class definition with multiple base classes looks as follows:
3371
3372\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003373class DerivedClassName(Base1, Base2, Base3):
3374 <statement-1>
3375 .
3376 .
3377 .
3378 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003379\end{verbatim}
3380
3381The only rule necessary to explain the semantics is the resolution
3382rule used for class attribute references. This is depth-first,
3383left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003384\class{DerivedClassName}, it is searched in \class{Base1}, then
3385(recursively) in the base classes of \class{Base1}, and only if it is
3386not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003387
Fred Drake8842e861998-02-13 07:16:30 +00003388(To some people breadth first --- searching \class{Base2} and
3389\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003390natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003391attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003392one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003393a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003394rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003395\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003396
3397It is clear that indiscriminate use of multiple inheritance is a
3398maintenance nightmare, given the reliance in Python on conventions to
3399avoid accidental name conflicts. A well-known problem with multiple
3400inheritance is a class derived from two classes that happen to have a
3401common base class. While it is easy enough to figure out what happens
3402in this case (the instance will have a single copy of ``instance
3403variables'' or data attributes used by the common base class), it is
3404not clear that these semantics are in any way useful.
3405
3406
Fred Drakeb7833d31998-09-11 16:21:55 +00003407\section{Private Variables \label{private}}
Guido van Rossum02455691997-07-17 16:21:52 +00003408
Fred Drakea594baf1998-04-03 05:16:31 +00003409There is limited support for class-private
Guido van Rossum02455691997-07-17 16:21:52 +00003410identifiers. Any identifier of the form \code{__spam} (at least two
3411leading underscores, at most one trailing underscore) is now textually
3412replaced with \code{_classname__spam}, where \code{classname} is the
3413current class name with leading underscore(s) stripped. This mangling
3414is done without regard of the syntactic position of the identifier, so
3415it can be used to define class-private instance and class variables,
3416methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003417private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003418may occur when the mangled name would be longer than 255 characters.
3419Outside classes, or when the class name consists of only underscores,
3420no mangling occurs.
3421
3422Name mangling is intended to give classes an easy way to define
3423``private'' instance variables and methods, without having to worry
3424about instance variables defined by derived classes, or mucking with
3425instance variables by code outside the class. Note that the mangling
3426rules are designed mostly to avoid accidents; it still is possible for
3427a determined soul to access or modify a variable that is considered
3428private. This can even be useful, e.g. for the debugger, and that's
3429one reason why this loophole is not closed. (Buglet: derivation of a
3430class with the same name as the base class makes use of private
3431variables of the base class possible.)
3432
3433Notice that code passed to \code{exec}, \code{eval()} or
3434\code{evalfile()} does not consider the classname of the invoking
3435class to be the current class; this is similar to the effect of the
3436\code{global} statement, the effect of which is likewise restricted to
3437code that is byte-compiled together. The same restriction applies to
3438\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3439when referencing \code{__dict__} directly.
3440
3441Here's an example of a class that implements its own
3442\code{__getattr__} and \code{__setattr__} methods and stores all
3443attributes in a private variable, in a way that works in Python 1.4 as
3444well as in previous versions:
3445
3446\begin{verbatim}
3447class VirtualAttributes:
3448 __vdict = None
3449 __vdict_name = locals().keys()[0]
3450
3451 def __init__(self):
3452 self.__dict__[self.__vdict_name] = {}
3453
3454 def __getattr__(self, name):
3455 return self.__vdict[name]
3456
3457 def __setattr__(self, name, value):
3458 self.__vdict[name] = value
3459\end{verbatim}
3460
Fred Drakeaf8a0151998-01-14 14:51:31 +00003461%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003462%potential problems, refrain from using identifiers starting with
3463%double underscore except for predefined uses like \code{__init__}. To
3464%use private names while maintaining future compatibility: refrain from
3465%using the same private name in classes related via subclassing; avoid
3466%explicit (manual) mangling/unmangling; and assume that at some point
3467%in the future, leading double underscore will revert to being just a
3468%naming convention. Discussion on extensive compile-time declarations
3469%are currently underway, and it is impossible to predict what solution
3470%will eventually be chosen for private names. Double leading
3471%underscore is still a candidate, of course --- just not the only one.
3472%It is placed in the distribution in the belief that it is useful, and
3473%so that widespread experience with its use can be gained. It will not
3474%be removed without providing a better solution and a migration path.
3475
Fred Drakeb7833d31998-09-11 16:21:55 +00003476\section{Odds and Ends \label{odds}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003477
3478Sometimes it is useful to have a data type similar to the Pascal
Fred Drakeee84d591999-03-10 17:25:30 +00003479``record'' or C ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003480items. An empty class definition will do nicely, e.g.:
3481
3482\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003483class Employee:
3484 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003485
Fred Drake8842e861998-02-13 07:16:30 +00003486john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003487
Fred Drake8842e861998-02-13 07:16:30 +00003488# Fill the fields of the record
3489john.name = 'John Doe'
3490john.dept = 'computer lab'
3491john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003492\end{verbatim}
3493
3494
3495A piece of Python code that expects a particular abstract data type
3496can often be passed a class that emulates the methods of that data
3497type instead. For instance, if you have a function that formats some
3498data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003499\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00003500buffer instead, and pass it as an argument.% (Unfortunately, this
3501%technique has its limitations: a class can't define operations that
3502%are accessed by special syntax such as sequence subscripting or
3503%arithmetic operators, and assigning such a ``pseudo-file'' to
3504%\code{sys.stdin} will not cause the interpreter to read further input
3505%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003506
3507
Fred Drake8842e861998-02-13 07:16:30 +00003508Instance method objects have attributes, too: \code{m.im_self} is the
3509object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003510function object corresponding to the method.
3511
Fred Drakeb7833d31998-09-11 16:21:55 +00003512\subsection{Exceptions Can Be Classes \label{exceptionClasses}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003513
3514User-defined exceptions are no longer limited to being string objects
3515--- they can be identified by classes as well. Using this mechanism it
3516is possible to create extensible hierarchies of exceptions.
3517
3518There are two new valid (semantic) forms for the raise statement:
3519
3520\begin{verbatim}
3521raise Class, instance
3522
3523raise instance
3524\end{verbatim}
3525
Fred Drake8842e861998-02-13 07:16:30 +00003526In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003527or of a class derived from it. The second form is a shorthand for
3528
3529\begin{verbatim}
3530raise instance.__class__, instance
3531\end{verbatim}
3532
3533An except clause may list classes as well as string objects. A class
3534in an except clause is compatible with an exception if it is the same
3535class or a base class thereof (but not the other way around --- an
3536except clause listing a derived class is not compatible with a base
3537class). For example, the following code will print B, C, D in that
3538order:
3539
3540\begin{verbatim}
3541class B:
3542 pass
3543class C(B):
3544 pass
3545class D(C):
3546 pass
3547
3548for c in [B, C, D]:
3549 try:
3550 raise c()
3551 except D:
3552 print "D"
3553 except C:
3554 print "C"
3555 except B:
3556 print "B"
3557\end{verbatim}
3558
Fred Drakeee84d591999-03-10 17:25:30 +00003559Note that if the except clauses were reversed (with
3560\samp{except B} first), it would have printed B, B, B --- the first
3561matching except clause is triggered.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003562
3563When an error message is printed for an unhandled exception which is a
3564class, the class name is printed, then a colon and a space, and
3565finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003566\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003567
Guido van Rossum194e57c1995-02-15 15:51:38 +00003568
Fred Drakeb7833d31998-09-11 16:21:55 +00003569\chapter{What Now? \label{whatNow}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003570
Guido van Rossum02455691997-07-17 16:21:52 +00003571Hopefully reading this tutorial has reinforced your interest in using
3572Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003573
Guido van Rossum02455691997-07-17 16:21:52 +00003574You should read, or at least page through, the Library Reference,
3575which gives complete (though terse) reference material about types,
3576functions, and modules that can save you a lot of time when writing
3577Python programs. The standard Python distribution includes a
Fred Drakeee84d591999-03-10 17:25:30 +00003578\emph{lot} of code in both C and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003579\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3580numbers, parse command-line options, write CGI programs, compress
3581data, and a lot more; skimming through the Library Reference will give
3582you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003583
Fred Drakeca6567f1998-01-22 20:44:18 +00003584The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003585code, documentation, and pointers to Python-related pages around the
Fred Drake391564f1998-04-01 23:11:56 +00003586Web. This web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00003587world, such as Europe, Japan, and Australia; a mirror may be faster
3588than the main site, depending on your geographical location. A more
Fred Drakeca6567f1998-01-22 20:44:18 +00003589informal site is \url{http://starship.skyport.net}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003590bunch of Python-related personal home pages; many people have
3591downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003592
Guido van Rossum02455691997-07-17 16:21:52 +00003593For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00003594newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
3595list at \email{python-list@cwi.nl}. The newsgroup and mailing list
3596are gatewayed, so messages posted to one will automatically be
3597forwarded to the other. There are around 35--45 postings a day,
3598% Postings figure based on average of last six months activity as
3599% reported by www.findmail.com; Oct. '97 - Mar. '98: 7480 msgs / 182
3600% days = 41.1 msgs / day.
3601asking (and answering) questions, suggesting new features, and
3602announcing new modules. Before posting, be sure to check the list of
3603Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003604\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3605\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003606answers many of the questions that come up again and again, and may
3607already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003608
Guido van Rossum02455691997-07-17 16:21:52 +00003609You can support the Python community by joining the Python Software
3610Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003611organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003612information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003613
Guido van Rossum194e57c1995-02-15 15:51:38 +00003614
Fred Drakea594baf1998-04-03 05:16:31 +00003615\appendix
Guido van Rossum194e57c1995-02-15 15:51:38 +00003616
Fred Drakeb7833d31998-09-11 16:21:55 +00003617\chapter{Interactive Input Editing and History Substitution
3618 \label{interacting}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003619
Guido van Rossum02455691997-07-17 16:21:52 +00003620Some versions of the Python interpreter support editing of the current
3621input line and history substitution, similar to facilities found in
3622the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003623\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003624editing. This library has its own documentation which I won't
Fred Drakecc09e8d1998-12-28 21:21:36 +00003625duplicate here; however, the basics are easily explained. The
3626interactive editing and history described here are optionally
3627available in the \UNIX{} and CygWin versions of the interpreter.
3628
3629This chapter does \emph{not} document the editing facilities of Mark
3630Hammond's PythonWin package or the Tk-based environment, IDLE,
3631distributed with Python. The command line history recall which
3632operates within DOS boxes on NT and some other DOS and Windows flavors
3633is yet another beast.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003634
Fred Drakeb7833d31998-09-11 16:21:55 +00003635\section{Line Editing \label{lineEditing}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003636
Guido van Rossum02455691997-07-17 16:21:52 +00003637If supported, input line editing is active whenever the interpreter
3638prints a primary or secondary prompt. The current line can be edited
3639using the conventional Emacs control characters. The most important
3640of these are: C-A (Control-A) moves the cursor to the beginning of the
3641line, C-E to the end, C-B moves it one position to the left, C-F to
3642the right. Backspace erases the character to the left of the cursor,
3643C-D the character to its right. C-K kills (erases) the rest of the
3644line to the right of the cursor, C-Y yanks back the last killed
3645string. C-underscore undoes the last change you made; it can be
3646repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003647
Fred Drakeb7833d31998-09-11 16:21:55 +00003648\section{History Substitution \label{history}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003649
Guido van Rossum02455691997-07-17 16:21:52 +00003650History substitution works as follows. All non-empty input lines
3651issued are saved in a history buffer, and when a new prompt is given
3652you are positioned on a new line at the bottom of this buffer. C-P
3653moves one line up (back) in the history buffer, C-N moves one down.
3654Any line in the history buffer can be edited; an asterisk appears in
3655front of the prompt to mark a line as modified. Pressing the Return
3656key passes the current line to the interpreter. C-R starts an
3657incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003658
Fred Drakeb7833d31998-09-11 16:21:55 +00003659\section{Key Bindings \label{keyBindings}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003660
Guido van Rossum02455691997-07-17 16:21:52 +00003661The key bindings and some other parameters of the Readline library can
3662be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003663\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003664
Fred Drake8842e861998-02-13 07:16:30 +00003665\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003666key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003667\end{verbatim}
3668
Guido van Rossum02455691997-07-17 16:21:52 +00003669or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003670
Fred Drake8842e861998-02-13 07:16:30 +00003671\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003672"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003673\end{verbatim}
3674
Guido van Rossum02455691997-07-17 16:21:52 +00003675and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003676
Fred Drake8842e861998-02-13 07:16:30 +00003677\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003678set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003679\end{verbatim}
3680
Guido van Rossum02455691997-07-17 16:21:52 +00003681For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003682
Fred Drake8842e861998-02-13 07:16:30 +00003683\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003684# I prefer vi-style editing:
3685set editing-mode vi
3686# Edit using a single line:
3687set horizontal-scroll-mode On
3688# Rebind some keys:
3689Meta-h: backward-kill-word
3690"\C-u": universal-argument
3691"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003692\end{verbatim}
3693
Guido van Rossum02455691997-07-17 16:21:52 +00003694Note that the default binding for TAB in Python is to insert a TAB
3695instead of Readline's default filename completion function. If you
3696insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003697
Fred Drake8842e861998-02-13 07:16:30 +00003698\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003699TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003700\end{verbatim}
3701
Fred Drakeeee08cd1997-12-04 15:43:15 +00003702in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003703indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003704
Fred Drake72389881998-04-13 01:31:10 +00003705Automatic completion of variable and module names is optionally
3706available. To enable it in the interpreter's interactive mode, add
Fred Drakeee84d591999-03-10 17:25:30 +00003707the following to your \file{\$HOME/.pythonrc.py} file:% $ <- bow to font-lock
3708\indexii{.pythonrc.py}{file}
3709\refstmodindex{rlcompleter}
Fred Drake72389881998-04-13 01:31:10 +00003710\refbimodindex{readline}
3711
3712\begin{verbatim}
3713import rlcompleter, readline
3714readline.parse_and_bind('tab: complete')
3715\end{verbatim}
3716
3717This binds the TAB key to the completion function, so hitting the TAB
3718key twice suggests completions; it looks at Python statement names,
3719the current local variables, and the available module names. For
3720dotted expressions such as \code{string.a}, it will evaluate the the
3721expression up to the final \character{.} and then suggest completions
3722from the attributes of the resulting object. Note that this may
3723execute application-defined code if an object with a
3724\method{__getattr__()} method is part of the expression.
3725
3726
Fred Drakeb7833d31998-09-11 16:21:55 +00003727\section{Commentary \label{commentary}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003728
Guido van Rossum02455691997-07-17 16:21:52 +00003729This facility is an enormous step forward compared to previous
3730versions of the interpreter; however, some wishes are left: It would
3731be nice if the proper indentation were suggested on continuation lines
3732(the parser knows if an indent token is required next). The
3733completion mechanism might use the interpreter's symbol table. A
3734command to check (or even suggest) matching parentheses, quotes etc.
3735would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003736
Fred Drake8842e861998-02-13 07:16:30 +00003737% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003738
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003739\end{document}