blob: dc59074ec771a5bc7d1565a085f04b659d0b8a7b [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002
Guido van Rossum02455691997-07-17 16:21:52 +00003% Things to do:
4% Add a section on file I/O
5% Write a chapter entitled ``Some Useful Modules''
6% --regex, math+cmath
7% Should really move the Python startup file info to an appendix
Guido van Rossum02455691997-07-17 16:21:52 +00008
Guido van Rossumdccc2981997-12-30 04:40:25 +00009\title{Python Tutorial}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010
Guido van Rossum16cd7f91994-10-06 10:29:26 +000011\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +000012
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000013\begin{document}
14
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000015\maketitle
16
Fred Drake9f86b661998-07-28 21:55:19 +000017\ifhtml
18\chapter*{Front Matter\label{front}}
19\fi
20
Guido van Rossum16cd7f91994-10-06 10:29:26 +000021\input{copyright}
22
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023\begin{abstract}
24
25\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000026Python is an easy to learn, powerful programming language. It has
27efficient high-level data structures and a simple but effective
28approach to object-oriented programming. Python's elegant syntax and
29dynamic typing, together with its interpreted nature, make it an ideal
30language for scripting and rapid application development in many areas
31on most platforms.
32
33The Python interpreter and the extensive standard library are freely
34available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000035Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000036distributed. The same site also contains distributions of and
37pointers to many free third party Python modules, programs and tools,
38and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000039
Guido van Rossum4410c751991-06-04 20:22:18 +000040The Python interpreter is easily extended with new functions and data
Fred Drake3f205921998-01-13 18:56:38 +000041types implemented in \C{} or \Cpp{} (or other languages callable from \C{}).
Guido van Rossumdccc2981997-12-30 04:40:25 +000042Python is also suitable as an extension language for customizable
43applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000044
Guido van Rossum6fc178f1991-08-16 09:13:42 +000045This tutorial introduces the reader informally to the basic concepts
46and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000047Python interpreter handy for hands-on experience, but all examples are
48self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000049
Guido van Rossumdccc2981997-12-30 04:40:25 +000050For a description of standard objects and modules, see the
51\emph{Python Library Reference} document. The \emph{Python Reference
52Manual} gives a more formal definition of the language. To write
Fred Drake3f205921998-01-13 18:56:38 +000053extensions in \C{} or \Cpp{}, read the \emph{Extending and Embedding} and
54\emph{Python/\C{} API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000055Python in depth.
56
57This tutorial does not attempt to be comprehensive and cover every
58single feature, or even every commonly used feature. Instead, it
59introduces many of Python's most noteworthy features, and will give
60you a good idea of the language's flavor and style. After reading it,
61you will be able to read and write Python modules and programs, and
62you will be ready to learn more about the various Python library
63modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000064
65\end{abstract}
66
Fred Drake4d4f9e71998-01-13 22:25:02 +000067\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000068
Guido van Rossum5e0759d1992-08-07 16:06:24 +000069
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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drake3f205921998-01-13 18:56:38 +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 Drakeeee08cd1997-12-04 15:43:15 +0000247Python 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5
248Copyright 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
270primary prompt.%
271\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000272 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000273}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000274Typing an interrupt while a command is executing raises the
275\code{KeyboardInterrupt} exception, which may be handled by a
276\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000277
Fred Drakeb7833d31998-09-11 16:21:55 +0000278\subsection{Executable Python Scripts \label{scripts}}
Guido van Rossum4410c751991-06-04 20:22:18 +0000279
Fred Drake6dc2aae1996-12-13 21:56:03 +0000280On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000281executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000282
Fred Drake8842e861998-02-13 07:16:30 +0000283\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000284#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000285\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000286
Fred Drake391564f1998-04-01 23:11:56 +0000287(assuming that the interpreter is on the user's \envvar{PATH}) at the
288beginning of the script and giving the file an executable mode. The
289\samp{\#!} must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000290
Fred Drakeb7833d31998-09-11 16:21:55 +0000291\subsection{The Interactive Startup File \label{startup}}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000292
Fred Drake8842e861998-02-13 07:16:30 +0000293% XXX This should probably be dumped in an appendix, since most people
294% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000295
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000296When you use Python interactively, it is frequently handy to have some
297standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000298can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000299\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drakeeee08cd1997-12-04 15:43:15 +0000300commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000301shells.
302
303This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000304commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000305explicit source of commands (which otherwise behaves like an
306interactive session). It is executed in the same name space where
307interactive commands are executed, so that objects that it defines or
308imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000309You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000310this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000311
312If you want to read an additional start-up file from the current
Fred Drake72389881998-04-13 01:31:10 +0000313directory, you can program this in the global start-up file,
314e.g.\ \samp{execfile('.pythonrc')}\indexii{.pythonrc.py}{file}. If
315you want to use the startup file in a script, you must do this
316explicitly in the script:
Fred Drake8842e861998-02-13 07:16:30 +0000317
318\begin{verbatim}
319import os
Fred Drake72389881998-04-13 01:31:10 +0000320if os.path.isfile(os.environ['PYTHONSTARTUP']):
321 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 Drake3f205921998-01-13 18:56:38 +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 Drake391564f1998-04-01 23:11:56 +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 Rossum02455691997-07-17 16:21:52 +0000552'A'}; this only works with two literals, not with arbitrary string expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000553
Fred Drake3f205921998-01-13 18:56:38 +0000554Strings can be subscripted (indexed); like in \C{}, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000555of a string has subscript (index) 0. There is no separate character
556type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000557substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000558separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000559
Fred Drake8842e861998-02-13 07:16:30 +0000560\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000561>>> word[4]
562'A'
563>>> word[0:2]
564'He'
565>>> word[2:4]
566'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000567\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000568
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000569Slice indices have useful defaults; an omitted first index defaults to
570zero, an omitted second index defaults to the size of the string being
571sliced.
572
Fred Drake8842e861998-02-13 07:16:30 +0000573\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000574>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000575'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000576>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000577'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000578\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000579
Fred Drakeeee08cd1997-12-04 15:43:15 +0000580Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
581equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000582
Fred Drake8842e861998-02-13 07:16:30 +0000583\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000584>>> word[:2] + word[2:]
585'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000586>>> word[:3] + word[3:]
587'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000588\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000589
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000590Degenerate slice indices are handled gracefully: an index that is too
591large is replaced by the string size, an upper bound smaller than the
592lower bound returns an empty string.
593
Fred Drake8842e861998-02-13 07:16:30 +0000594\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000595>>> word[1:100]
596'elpA'
597>>> word[10:]
598''
599>>> word[2:1]
600''
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 +0000603Indices may be negative numbers, to start counting from the right.
604For example:
605
Fred Drake8842e861998-02-13 07:16:30 +0000606\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000607>>> word[-1] # The last character
608'A'
609>>> word[-2] # The last-but-one character
610'p'
611>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000612'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000613>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000614'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000615\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000616
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000617But note that -0 is really the same as 0, so it does not count from
618the right!
619
Fred Drake8842e861998-02-13 07:16:30 +0000620\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000621>>> word[-0] # (since -0 equals 0)
622'H'
Fred Drake8842e861998-02-13 07:16:30 +0000623\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000624
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000625Out-of-range negative slice indices are truncated, but don't try this
626for single-element (non-slice) indices:
627
Fred Drake8842e861998-02-13 07:16:30 +0000628\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000629>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000630'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000631>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000632Traceback (innermost last):
633 File "<stdin>", line 1
634IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000635\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000636
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000637The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000638pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000639character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000640string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000641
Fred Drake8842e861998-02-13 07:16:30 +0000642\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000643 +---+---+---+---+---+
644 | H | e | l | p | A |
645 +---+---+---+---+---+
646 0 1 2 3 4 5
647-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000648\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000649
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000650The first row of numbers gives the position of the indices 0...5 in
651the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000652The slice from \var{i} to \var{j} consists of all characters between
653the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000654
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000655For nonnegative indices, the length of a slice is the difference of
656the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000657\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000658
Fred Drake8842e861998-02-13 07:16:30 +0000659The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000660
Fred Drake8842e861998-02-13 07:16:30 +0000661\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000662>>> s = 'supercalifragilisticexpialidocious'
663>>> len(s)
66434
Fred Drake8842e861998-02-13 07:16:30 +0000665\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000666
Fred Drakeb7833d31998-09-11 16:21:55 +0000667\subsection{Lists \label{lists}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000668
Fred Drakeeee08cd1997-12-04 15:43:15 +0000669Python knows a number of \emph{compound} data types, used to group
670together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000671can be written as a list of comma-separated values (items) between
672square brackets. List items need not all have the same type.
673
Fred Drake8842e861998-02-13 07:16:30 +0000674\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000675>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000676>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000677['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000678\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000679
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000680Like string indices, list indices start at 0, and lists can be sliced,
681concatenated and so on:
682
Fred Drake8842e861998-02-13 07:16:30 +0000683\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000684>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000685'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000686>>> a[3]
6871234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000688>>> a[-2]
689100
690>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000691['eggs', 100]
692>>> a[:2] + ['bacon', 2*2]
693['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000694>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000695['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000696\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000697
Fred Drakeeee08cd1997-12-04 15:43:15 +0000698Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000699individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000700
Fred Drake8842e861998-02-13 07:16:30 +0000701\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000702>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000703['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000704>>> a[2] = a[2] + 23
705>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000706['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000707\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000708
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000709Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000710of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000711
Fred Drake8842e861998-02-13 07:16:30 +0000712\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000713>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000714... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000715>>> a
716[1, 12, 123, 1234]
717>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000718... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000719>>> a
720[123, 1234]
721>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000722... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000723>>> a
724[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000725>>> a[:0] = a # Insert (a copy of) itself at the beginning
726>>> a
727[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000728\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000729
Fred Drake8842e861998-02-13 07:16:30 +0000730The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000731
Fred Drake8842e861998-02-13 07:16:30 +0000732\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000733>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007348
Fred Drake8842e861998-02-13 07:16:30 +0000735\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000736
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000737It is possible to nest lists (create lists containing other lists),
738for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000739
Fred Drake8842e861998-02-13 07:16:30 +0000740\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000741>>> q = [2, 3]
742>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000743>>> len(p)
7443
745>>> p[1]
746[2, 3]
747>>> p[1][0]
7482
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000749>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000750>>> p
751[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000752>>> q
753[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000754\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000755
Fred Drakeeee08cd1997-12-04 15:43:15 +0000756Note that in the last example, \code{p[1]} and \code{q} really refer to
757the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000758
Fred Drakeb7833d31998-09-11 16:21:55 +0000759\section{First Steps Towards Programming \label{firstSteps}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000760
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000761Of course, we can use Python for more complicated tasks than adding
762two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000763subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000764
Fred Drake8842e861998-02-13 07:16:30 +0000765\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000766>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000767... # the sum of two elements defines the next
768... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000769>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000770... print b
771... a, b = b, a+b
772...
7731
7741
7752
7763
7775
7788
Fred Drake8842e861998-02-13 07:16:30 +0000779\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000780
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000781This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000782
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000783\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000784
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000785\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000786The first line contains a \emph{multiple assignment}: the variables
787\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000788last line this is used again, demonstrating that the expressions on
789the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000790assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000791
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000792\item
Fred Drake8842e861998-02-13 07:16:30 +0000793The \keyword{while} loop executes as long as the condition (here:
794\code{b < 10}) remains true. In Python, like in \C{}, any non-zero
795integer value is true; zero is false. The condition may also be a
796string or list value, in fact any sequence; anything with a non-zero
797length is true, empty sequences are false. The test used in the
798example is a simple comparison. The standard comparison operators are
799written the same as in \C{}: \code{<}, \code{>}, \code{==}, \code{<=},
800\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000801
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000802\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000803The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000804way of grouping statements. Python does not (yet!) provide an
805intelligent input line editing facility, so you have to type a tab or
806space(s) for each indented line. In practice you will prepare more
807complicated input for Python with a text editor; most text editors have
808an auto-indent facility. When a compound statement is entered
809interactively, it must be followed by a blank line to indicate
810completion (since the parser cannot guess when you have typed the last
811line).
812
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000813\item
Fred Drake8842e861998-02-13 07:16:30 +0000814The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000815given. It differs from just writing the expression you want to write
816(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000817multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000818and a space is inserted between items, so you can format things nicely,
819like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000820
Fred Drake8842e861998-02-13 07:16:30 +0000821\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000822>>> i = 256*256
823>>> print 'The value of i is', i
824The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000825\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000826
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000827A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000828
Fred Drake8842e861998-02-13 07:16:30 +0000829\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000830>>> a, b = 0, 1
831>>> while b < 1000:
832... print b,
833... a, b = b, a+b
834...
8351 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000836\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000837
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000838Note that the interpreter inserts a newline before it prints the next
839prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000840
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000841\end{itemize}
842
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000843
Fred Drakeb7833d31998-09-11 16:21:55 +0000844\chapter{More Control Flow Tools \label{moreControl}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000845
Fred Drake8842e861998-02-13 07:16:30 +0000846Besides the \keyword{while} statement just introduced, Python knows
847the usual control flow statements known from other languages, with
848some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000849
Fred Drakeb7833d31998-09-11 16:21:55 +0000850\section{\keyword{if} Statements \label{if}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000851
Fred Drake8842e861998-02-13 07:16:30 +0000852Perhaps the most well-known statement type is the \keyword{if}
853statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000854
Fred Drake8842e861998-02-13 07:16:30 +0000855\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000856>>> if x < 0:
857... x = 0
858... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000859... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000860... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000861... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000862... print 'Single'
863... else:
864... print 'More'
865...
Fred Drake8842e861998-02-13 07:16:30 +0000866\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000867
Fred Drake8842e861998-02-13 07:16:30 +0000868There can be zero or more \keyword{elif} parts, and the \keyword{else}
869part is optional. The keyword `\keyword{elif}' is short for `else
870if', and is useful to avoid excessive indentation. An
871\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif}
872\ldots\ sequence is a substitute for the \emph{switch} or
873% ^^^^
874% Weird spacings happen here if the wrapping of the source text
875% gets changed in the wrong way.
876\emph{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000877
Fred Drakeb7833d31998-09-11 16:21:55 +0000878
879\section{\keyword{for} Statements \label{for}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000880
Fred Drakef790b161998-11-30 20:37:24 +0000881The \keyword{for}\stindex{for} statement in Python differs a bit from
882what you may be used to in \C{} or Pascal. Rather than always
883iterating over an arithmetic progression of numbers (like in Pascal),
884or giving the user the ability to define both the iteration step and
885halting condition (as \C{}), Python's \keyword{for}\stindex{for}
886statement iterates over the items of any sequence (e.g., a list or a
887string), in the order that they appear in the sequence. For example
888(no pun intended):
889% One suggestion was to give a real C example here, but that may only
890% serve to confuse non-C programmers.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000891
Fred Drake8842e861998-02-13 07:16:30 +0000892\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000893>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000894... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000895>>> for x in a:
896... print x, len(x)
897...
898cat 3
899window 6
900defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000901\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000902
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000903It is not safe to modify the sequence being iterated over in the loop
904(this can only happen for mutable sequence types, i.e., lists). If
905you need to modify the list you are iterating over, e.g., duplicate
906selected items, you must iterate over a copy. The slice notation
907makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000908
Fred Drake8842e861998-02-13 07:16:30 +0000909\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000910>>> for x in a[:]: # make a slice copy of the entire list
911... if len(x) > 6: a.insert(0, x)
912...
913>>> a
914['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000915\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000916
Fred Drakeb7833d31998-09-11 16:21:55 +0000917
918\section{The \function{range()} Function \label{range}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000919
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000920If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000921function \function{range()} comes in handy. It generates lists
922containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000923
Fred Drake8842e861998-02-13 07:16:30 +0000924\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000925>>> range(10)
926[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000927\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000928
Fred Drake8842e861998-02-13 07:16:30 +0000929The given end point is never part of the generated list;
930\code{range(10)} generates a list of 10 values, exactly the legal
931indices for items of a sequence of length 10. It is possible to let
932the range start at another number, or to specify a different increment
933(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000934
Fred Drake8842e861998-02-13 07:16:30 +0000935\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000936>>> range(5, 10)
937[5, 6, 7, 8, 9]
938>>> range(0, 10, 3)
939[0, 3, 6, 9]
940>>> range(-10, -100, -30)
941[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000942\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000943
Fred Drake8842e861998-02-13 07:16:30 +0000944To iterate over the indices of a sequence, combine \function{range()}
945and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000946
Fred Drake8842e861998-02-13 07:16:30 +0000947\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000948>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000949>>> for i in range(len(a)):
950... print i, a[i]
951...
9520 Mary
9531 had
9542 a
9553 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009564 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000957\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000958
Fred Drake391564f1998-04-01 23:11:56 +0000959\section{\keyword{break} and \keyword{continue} Statements, and
Fred Drakeb7833d31998-09-11 16:21:55 +0000960 \keyword{else} Clauses on Loops
961 \label{break}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000962
Fred Drake8842e861998-02-13 07:16:30 +0000963The \keyword{break} statement, like in \C{}, breaks out of the smallest
964enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000965
Fred Drake8842e861998-02-13 07:16:30 +0000966The \keyword{continue} statement, also borrowed from \C{}, continues
967with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000968
Fred Drake8842e861998-02-13 07:16:30 +0000969Loop statements may have an \code{else} clause; it is executed when
970the loop terminates through exhaustion of the list (with
971\keyword{for}) or when the condition becomes false (with
972\keyword{while}), but not when the loop is terminated by a
973\keyword{break} statement. This is exemplified by the following loop,
974which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000975
Fred Drake8842e861998-02-13 07:16:30 +0000976\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000977>>> for n in range(2, 10):
978... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000979... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000980... print n, 'equals', x, '*', n/x
981... break
982... else:
983... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000984...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00009852 is a prime number
9863 is a prime number
9874 equals 2 * 2
9885 is a prime number
9896 equals 2 * 3
9907 is a prime number
9918 equals 2 * 4
9929 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +0000993\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000994
Fred Drakeb7833d31998-09-11 16:21:55 +0000995\section{\keyword{pass} Statements \label{pass}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000996
Fred Drake8842e861998-02-13 07:16:30 +0000997The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000998It can be used when a statement is required syntactically but the
999program requires no action.
1000For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001001
Fred Drake8842e861998-02-13 07:16:30 +00001002\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001003>>> while 1:
1004... pass # Busy-wait for keyboard interrupt
1005...
Fred Drake8842e861998-02-13 07:16:30 +00001006\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001007
Fred Drakeb7833d31998-09-11 16:21:55 +00001008\section{Defining Functions \label{functions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001009
1010We can create a function that writes the Fibonacci series to an
1011arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001012
Fred Drake8842e861998-02-13 07:16:30 +00001013\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001014>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001015... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001016... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001017... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001018... print b,
1019... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001020...
1021>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001022... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010231 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001024\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001025
Fred Drake8842e861998-02-13 07:16:30 +00001026The keyword \keyword{def} introduces a function \emph{definition}. It
1027must be followed by the function name and the parenthesized list of
1028formal parameters. The statements that form the body of the function
1029start at the next line, indented by a tab stop. The first statement
1030of the function body can optionally be a string literal; this string
1031literal is the function's documentation string, or \dfn{docstring}.
1032There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001033documentation, or to let the user interactively browse through code;
1034it's good practice to include docstrings in code that you write, so
1035try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001036
Fred Drakeeee08cd1997-12-04 15:43:15 +00001037The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001038for the local variables of the function. More precisely, all variable
1039assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001040whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001041in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001042Thus, global variables cannot be directly assigned a value within a
1043function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001044they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001045
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001046The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001047the local symbol table of the called function when it is called; thus,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001048arguments are passed using \emph{call by value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001049\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001050 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001051 description, since if a mutable object is passed, the caller
1052 will see any changes the callee makes to it (e.g., items
1053 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001054}
1055When a function calls another function, a new local symbol table is
1056created for that call.
1057
Fred Drake8842e861998-02-13 07:16:30 +00001058A function definition introduces the function name in the current
1059symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001060has a type that is recognized by the interpreter as a user-defined
1061function. This value can be assigned to another name which can then
1062also be used as a function. This serves as a general renaming
1063mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001064
Fred Drake8842e861998-02-13 07:16:30 +00001065\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001066>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001067<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001068>>> f = fib
1069>>> f(100)
10701 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001071\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001072
Fred Drakeeee08cd1997-12-04 15:43:15 +00001073You might object that \code{fib} is not a function but a procedure. In
Fred Drake3f205921998-01-13 18:56:38 +00001074Python, like in \C{}, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001075value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001076albeit a rather boring one. This value is called \code{None} (it's a
1077built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001078the interpreter if it would be the only value written. You can see it
1079if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001080
Fred Drake8842e861998-02-13 07:16:30 +00001081\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001082>>> print fib(0)
1083None
Fred Drake8842e861998-02-13 07:16:30 +00001084\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001085
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001086It is simple to write a function that returns a list of the numbers of
1087the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001088
Fred Drake8842e861998-02-13 07:16:30 +00001089\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001090>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001091... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001092... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001093... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001094... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001095... result.append(b) # see below
1096... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001097... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001098...
1099>>> f100 = fib2(100) # call it
1100>>> f100 # write the result
1101[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001102\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001103%
Guido van Rossum4410c751991-06-04 20:22:18 +00001104This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001105
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001106\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001107
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001108\item
Fred Drake8842e861998-02-13 07:16:30 +00001109The \keyword{return} statement returns with a value from a function.
1110\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001111the middle of a procedure (falling off the end also returns from a
1112procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001113
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001114\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001115The statement \code{result.append(b)} calls a \emph{method} of the list
1116object \code{result}. A method is a function that `belongs' to an
1117object and is named \code{obj.methodname}, where \code{obj} is some
1118object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001119of a method that is defined by the object's type. Different types
1120define different methods. Methods of different types may have the
1121same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001122own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001123in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001124The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001125list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001126example it is equivalent to \samp{result = result + [b]}, but more
1127efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001128
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001129\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001130
Fred Drakeb7833d31998-09-11 16:21:55 +00001131\section{More on Defining Functions \label{defining}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001132
Guido van Rossum02455691997-07-17 16:21:52 +00001133It is also possible to define functions with a variable number of
1134arguments. There are three forms, which can be combined.
1135
Fred Drakeb7833d31998-09-11 16:21:55 +00001136\subsection{Default Argument Values \label{defaultArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001137
1138The most useful form is to specify a default value for one or more
1139arguments. This creates a function that can be called with fewer
1140arguments than it is defined, e.g.
1141
1142\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001143def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1144 while 1:
1145 ok = raw_input(prompt)
1146 if ok in ('y', 'ye', 'yes'): return 1
1147 if ok in ('n', 'no', 'nop', 'nope'): return 0
1148 retries = retries - 1
1149 if retries < 0: raise IOError, 'refusenik user'
1150 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001151\end{verbatim}
1152
1153This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001154\code{ask_ok('Do you really want to quit?')} or like this:
1155\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001156
1157The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001158in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001159
1160\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001161i = 5
1162def f(arg = i): print arg
1163i = 6
1164f()
Guido van Rossum02455691997-07-17 16:21:52 +00001165\end{verbatim}
1166
Fred Drakeeee08cd1997-12-04 15:43:15 +00001167will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001168
Guido van Rossumaee5e261998-08-07 17:45:09 +00001169\strong{Important warning:} The default value is evaluated only once.
1170This makes a difference when the default is a mutable object such as a
1171list or dictionary. For example, the following function accumulates
1172the arguments passed to it on subsequent calls:
1173
1174\begin{verbatim}
1175def f(a, l = []):
1176 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001177 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001178print f(1)
1179print f(2)
1180print f(3)
1181\end{verbatim}
1182
1183This will print
1184
1185\begin{verbatim}
1186[1]
1187[1, 2]
1188[1, 2, 3]
1189\end{verbatim}
1190
1191If you don't want the default to be shared between subsequent calls,
1192you can write the function like this instead:
1193
1194\begin{verbatim}
1195def f(a, l = None):
1196 if l is None:
1197 l = []
1198 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001199 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001200\end{verbatim}
1201
Fred Drakeb7833d31998-09-11 16:21:55 +00001202\subsection{Keyword Arguments \label{keywordArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001203
1204Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001205keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001206instance, the following function:
1207
1208\begin{verbatim}
1209def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1210 print "-- This parrot wouldn't", action,
1211 print "if you put", voltage, "Volts through it."
1212 print "-- Lovely plumage, the", type
1213 print "-- It's", state, "!"
1214\end{verbatim}
1215
1216could be called in any of the following ways:
1217
1218\begin{verbatim}
1219parrot(1000)
1220parrot(action = 'VOOOOOM', voltage = 1000000)
1221parrot('a thousand', state = 'pushing up the daisies')
1222parrot('a million', 'bereft of life', 'jump')
1223\end{verbatim}
1224
1225but the following calls would all be invalid:
1226
1227\begin{verbatim}
1228parrot() # required argument missing
1229parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1230parrot(110, voltage=220) # duplicate value for argument
1231parrot(actor='John Cleese') # unknown keyword
1232\end{verbatim}
1233
1234In general, an argument list must have any positional arguments
1235followed by any keyword arguments, where the keywords must be chosen
1236from the formal parameter names. It's not important whether a formal
1237parameter has a default value or not. No argument must receive a
1238value more than once --- formal parameter names corresponding to
1239positional arguments cannot be used as keywords in the same calls.
1240
1241When a final formal parameter of the form \code{**\var{name}} is
1242present, it receives a dictionary containing all keyword arguments
1243whose keyword doesn't correspond to a formal parameter. This may be
1244combined with a formal parameter of the form \code{*\var{name}}
1245(described in the next subsection) which receives a tuple containing
1246the positional arguments beyond the formal parameter list.
1247(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1248example, if we define a function like this:
1249
1250\begin{verbatim}
1251def cheeseshop(kind, *arguments, **keywords):
1252 print "-- Do you have any", kind, '?'
1253 print "-- I'm sorry, we're all out of", kind
1254 for arg in arguments: print arg
1255 print '-'*40
1256 for kw in keywords.keys(): print kw, ':', keywords[kw]
1257\end{verbatim}
1258
1259It could be called like this:
1260
1261\begin{verbatim}
1262cheeseshop('Limburger', "It's very runny, sir.",
1263 "It's really very, VERY runny, sir.",
1264 client='John Cleese',
1265 shopkeeper='Michael Palin',
1266 sketch='Cheese Shop Sketch')
1267\end{verbatim}
1268
1269and of course it would print:
1270
1271\begin{verbatim}
1272-- Do you have any Limburger ?
1273-- I'm sorry, we're all out of Limburger
1274It's very runny, sir.
1275It's really very, VERY runny, sir.
1276----------------------------------------
1277client : John Cleese
1278shopkeeper : Michael Palin
1279sketch : Cheese Shop Sketch
1280\end{verbatim}
1281
Fred Drakeb7833d31998-09-11 16:21:55 +00001282\subsection{Arbitrary Argument Lists \label{arbitraryArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001283
1284Finally, the least frequently used option is to specify that a
1285function can be called with an arbitrary number of arguments. These
1286arguments will be wrapped up in a tuple. Before the variable number
1287of arguments, zero or more normal arguments may occur.
1288
1289\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001290def fprintf(file, format, *args):
1291 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001292\end{verbatim}
1293
Fred Drakea594baf1998-04-03 05:16:31 +00001294
Fred Drakeb7833d31998-09-11 16:21:55 +00001295\subsection{Lambda Forms \label{lambda}}
Fred Drakea594baf1998-04-03 05:16:31 +00001296
1297By popular demand, a few features commonly found in functional
1298programming languages and Lisp have been added to Python. With the
1299\keyword{lambda} keyword, small anonymous functions can be created.
1300Here's a function that returns the sum of its two arguments:
1301\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1302objects are required. They are syntactically restricted to a single
1303expression. Semantically, they are just syntactic sugar for a normal
1304function definition. Like nested function definitions, lambda forms
1305cannot reference variables from the containing scope, but this can be
1306overcome through the judicious use of default argument values, e.g.
1307
1308\begin{verbatim}
1309def make_incrementor(n):
1310 return lambda x, incr=n: x+incr
1311\end{verbatim}
1312
Fred Drakeb7833d31998-09-11 16:21:55 +00001313\subsection{Documentation Strings \label{docstrings}}
Fred Drakea594baf1998-04-03 05:16:31 +00001314
1315There are emerging conventions about the content and formatting of
1316documentation strings.
1317
1318The first line should always be a short, concise summary of the
1319object's purpose. For brevity, it should not explicitly state the
1320object's name or type, since these are available by other means
1321(except if the name happens to be a verb describing a function's
1322operation). This line should begin with a capital letter and end with
1323a period.
1324
1325If there are more lines in the documentation string, the second line
1326should be blank, visually separating the summary from the rest of the
1327description. The following lines should be one of more of paragraphs
1328describing the objects calling conventions, its side effects, etc.
1329
1330The Python parser does not strip indentation from multi-line string
1331literals in Python, so tools that process documentation have to strip
1332indentation. This is done using the following convention. The first
1333non-blank line \emph{after} the first line of the string determines the
1334amount of indentation for the entire documentation string. (We can't
1335use the first line since it is generally adjacent to the string's
1336opening quotes so its indentation is not apparent in the string
1337literal.) Whitespace ``equivalent'' to this indentation is then
1338stripped from the start of all lines of the string. Lines that are
1339indented less should not occur, but if they occur all their leading
1340whitespace should be stripped. Equivalence of whitespace should be
1341tested after expansion of tabs (to 8 spaces, normally).
1342
1343
1344
Fred Drakeb7833d31998-09-11 16:21:55 +00001345\chapter{Data Structures \label{structures}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001346
1347This chapter describes some things you've learned about already in
1348more detail, and adds some new things as well.
1349
Fred Drakeb7833d31998-09-11 16:21:55 +00001350\section{More on Lists \label{moreLists}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001351
1352The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001353of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001354
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001355\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001356
Fred Drakeeee08cd1997-12-04 15:43:15 +00001357\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001358Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001359the element before which to insert, so \code{a.insert(0, x)} inserts at
1360the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1361\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001362
Fred Drakeeee08cd1997-12-04 15:43:15 +00001363\item[\code{append(x)}]
1364Equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001365
Fred Drakeeee08cd1997-12-04 15:43:15 +00001366\item[\code{index(x)}]
1367Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001368It is an error if there is no such item.
1369
Fred Drakeeee08cd1997-12-04 15:43:15 +00001370\item[\code{remove(x)}]
1371Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001372It is an error if there is no such item.
1373
Fred Drakeeee08cd1997-12-04 15:43:15 +00001374\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001375Sort the items of the list, in place.
1376
Fred Drakeeee08cd1997-12-04 15:43:15 +00001377\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001378Reverse the elements of the list, in place.
1379
Fred Drakeeee08cd1997-12-04 15:43:15 +00001380\item[\code{count(x)}]
1381Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001382
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001383\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001384
1385An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001386
Fred Drake8842e861998-02-13 07:16:30 +00001387\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001388>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001389>>> print a.count(333), a.count(66.6), a.count('x')
13902 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001391>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001392>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001393>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001394[66.6, 333, -1, 333, 1, 1234.5, 333]
1395>>> a.index(333)
13961
1397>>> a.remove(333)
1398>>> a
1399[66.6, -1, 333, 1, 1234.5, 333]
1400>>> a.reverse()
1401>>> a
1402[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001403>>> a.sort()
1404>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001405[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001406\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001407
Fred Drakeb7833d31998-09-11 16:21:55 +00001408\subsection{Functional Programming Tools \label{functional}}
Guido van Rossum02455691997-07-17 16:21:52 +00001409
1410There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001411lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001412
Fred Drake8842e861998-02-13 07:16:30 +00001413\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1414the same type, if possible) consisting of those items from the
1415sequence for which \code{\var{function}(\var{item})} is true. For
1416example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001417
1418\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001419>>> def f(x): return x%2 != 0 and x%3 != 0
1420...
1421>>> filter(f, range(2, 25))
1422[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001423\end{verbatim}
1424
Fred Drake8842e861998-02-13 07:16:30 +00001425\samp{map(\var{function}, \var{sequence})} calls
1426\code{\var{function}(\var{item})} for each of the sequence's items and
1427returns a list of the return values. For example, to compute some
1428cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001429
1430\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001431>>> def cube(x): return x*x*x
1432...
1433>>> map(cube, range(1, 11))
1434[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001435\end{verbatim}
1436
1437More than one sequence may be passed; the function must then have as
1438many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001439corresponding item from each sequence (or \code{None} if some sequence
1440is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001441a function returning its argument(s) is substituted.
1442
1443Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001444\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1445turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001446
1447\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001448>>> seq = range(8)
1449>>> def square(x): return x*x
1450...
1451>>> map(None, seq, map(square, seq))
1452[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001453\end{verbatim}
1454
Fred Drake8842e861998-02-13 07:16:30 +00001455\samp{reduce(\var{func}, \var{sequence})} returns a single value
1456constructed by calling the binary function \var{func} on the first two
1457items of the sequence, then on the result and the next item, and so
1458on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001459
1460\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001461>>> def add(x,y): return x+y
1462...
1463>>> reduce(add, range(1, 11))
146455
Guido van Rossum02455691997-07-17 16:21:52 +00001465\end{verbatim}
1466
1467If there's only one item in the sequence, its value is returned; if
1468the sequence is empty, an exception is raised.
1469
1470A third argument can be passed to indicate the starting value. In this
1471case the starting value is returned for an empty sequence, and the
1472function is first applied to the starting value and the first sequence
1473item, then to the result and the next item, and so on. For example,
1474
1475\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001476>>> def sum(seq):
1477... def add(x,y): return x+y
1478... return reduce(add, seq, 0)
1479...
1480>>> sum(range(1, 11))
148155
1482>>> sum([])
14830
Guido van Rossum02455691997-07-17 16:21:52 +00001484\end{verbatim}
1485
Fred Drakeb7833d31998-09-11 16:21:55 +00001486\section{The \keyword{del} statement \label{del}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001487
1488There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001489of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001490remove slices from a list (which we did earlier by assignment of an
1491empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001492
Fred Drake8842e861998-02-13 07:16:30 +00001493\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001494>>> a
1495[-1, 1, 66.6, 333, 333, 1234.5]
1496>>> del a[0]
1497>>> a
1498[1, 66.6, 333, 333, 1234.5]
1499>>> del a[2:4]
1500>>> a
1501[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001502\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001503
1504\keyword{del} can also be used to delete entire variables:
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>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001508\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001509
Fred Drakeeee08cd1997-12-04 15:43:15 +00001510Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001511another value is assigned to it). We'll find other uses for
1512\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001513
Fred Drakeb7833d31998-09-11 16:21:55 +00001514\section{Tuples and Sequences \label{tuples}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001515
1516We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001517indexing and slicing operations. They are two examples of
1518\emph{sequence} data types. Since Python is an evolving language,
1519other sequence data types may be added. There is also another
1520standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001521
1522A tuple consists of a number of values separated by commas, for
1523instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001524
Fred Drake8842e861998-02-13 07:16:30 +00001525\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001526>>> t = 12345, 54321, 'hello!'
1527>>> t[0]
152812345
1529>>> t
1530(12345, 54321, 'hello!')
1531>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001532... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001533>>> u
1534((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001535\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001536
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001537As you see, on output tuples are alway enclosed in parentheses, so
1538that nested tuples are interpreted correctly; they may be input with
1539or without surrounding parentheses, although often parentheses are
1540necessary anyway (if the tuple is part of a larger expression).
1541
1542Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1543from a database, etc. Tuples, like strings, are immutable: it is not
1544possible to assign to the individual items of a tuple (you can
1545simulate much of the same effect with slicing and concatenation,
1546though).
1547
1548A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001549items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001550tuples are constructed by an empty pair of parentheses; a tuple with
1551one item is constructed by following a value with a comma
1552(it is not sufficient to enclose a single value in parentheses).
1553Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001554
Fred Drake8842e861998-02-13 07:16:30 +00001555\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001556>>> empty = ()
1557>>> singleton = 'hello', # <-- note trailing comma
1558>>> len(empty)
15590
1560>>> len(singleton)
15611
1562>>> singleton
1563('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001564\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001565
Fred Drakeeee08cd1997-12-04 15:43:15 +00001566The statement \code{t = 12345, 54321, 'hello!'} is an example of
1567\emph{tuple packing}: the values \code{12345}, \code{54321} and
1568\code{'hello!'} are packed together in a tuple. The reverse operation
1569is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001570
Fred Drake8842e861998-02-13 07:16:30 +00001571\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001572>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001573\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001574
Fred Drakeeee08cd1997-12-04 15:43:15 +00001575This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001576unpacking requires that the list of variables on the left has the same
1577number of elements as the length of the tuple. Note that multiple
1578assignment is really just a combination of tuple packing and tuple
1579unpacking!
1580
Guido van Rossumaee5e261998-08-07 17:45:09 +00001581% XXX This is no longer necessary!
Fred Drakeeee08cd1997-12-04 15:43:15 +00001582Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001583unpacking}. This is supported by enclosing the list of variables in
1584square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001585
Fred Drake8842e861998-02-13 07:16:30 +00001586\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001587>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001588>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001589\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001590
Guido van Rossumaee5e261998-08-07 17:45:09 +00001591% XXX Add a bit on the difference between tuples and lists.
1592% XXX Also explain that a tuple can *contain* a mutable object!
1593
Fred Drakeb7833d31998-09-11 16:21:55 +00001594\section{Dictionaries \label{dictionaries}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001595
Fred Drakeeee08cd1997-12-04 15:43:15 +00001596Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001597Dictionaries are sometimes found in other languages as ``associative
1598memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001599indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001600which can be any non-mutable type; strings and numbers can always be
1601keys. Tuples can be used as keys if they contain only strings,
1602numbers, or tuples. You can't use lists as keys, since lists can be
1603modified in place using their \code{append()} method.
1604
Guido van Rossum6938f061994-08-01 12:22:53 +00001605It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001606\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001607(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001608A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001609Placing a comma-separated list of key:value pairs within the
1610braces adds initial key:value pairs to the dictionary; this is also the
1611way dictionaries are written on output.
1612
1613The main operations on a dictionary are storing a value with some key
1614and extracting the value given the key. It is also possible to delete
1615a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001616with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001617If you store using a key that is already in use, the old value
1618associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001619value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001620
Fred Drakeeee08cd1997-12-04 15:43:15 +00001621The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001622keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001623just apply the \code{sort()} method to the list of keys). To check
1624whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001625method of the dictionary.
1626
1627Here is a small example using a dictionary:
1628
Fred Drake8842e861998-02-13 07:16:30 +00001629\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001630>>> tel = {'jack': 4098, 'sape': 4139}
1631>>> tel['guido'] = 4127
1632>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001633{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001634>>> tel['jack']
16354098
1636>>> del tel['sape']
1637>>> tel['irv'] = 4127
1638>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001639{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001640>>> tel.keys()
1641['guido', 'irv', 'jack']
1642>>> tel.has_key('guido')
16431
Fred Drake8842e861998-02-13 07:16:30 +00001644\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001645
Fred Drakeb7833d31998-09-11 16:21:55 +00001646\section{More on Conditions \label{conditions}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001647
Fred Drakeeee08cd1997-12-04 15:43:15 +00001648The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001649contain other operators besides comparisons.
1650
Fred Drakeeee08cd1997-12-04 15:43:15 +00001651The comparison operators \code{in} and \code{not in} check whether a value
1652occurs (does not occur) in a sequence. The operators \code{is} and
1653\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001654only matters for mutable objects like lists. All comparison operators
1655have the same priority, which is lower than that of all numerical
1656operators.
1657
Fred Drakeeee08cd1997-12-04 15:43:15 +00001658Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a}
1659is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001660
Fred Drakeeee08cd1997-12-04 15:43:15 +00001661Comparisons may be combined by the Boolean operators \code{and} and
1662\code{or}, and the outcome of a comparison (or of any other Boolean
1663expression) may be negated with \code{not}. These all have lower
1664priorities than comparison operators again; between them, \code{not} has
1665the highest priority, and \code{or} the lowest, so that
1666\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 +00001667course, parentheses can be used to express the desired composition.
1668
Fred Drakeeee08cd1997-12-04 15:43:15 +00001669The Boolean operators \code{and} and \code{or} are so-called
1670\emph{shortcut} operators: their arguments are evaluated from left to
1671right, and evaluation stops as soon as the outcome is determined.
1672E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1673and B and C} does not evaluate the expression C. In general, the
1674return value of a shortcut operator, when used as a general value and
1675not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001676
1677It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001678expression to a variable. For example,
1679
Fred Drake8842e861998-02-13 07:16:30 +00001680\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001681>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1682>>> non_null = string1 or string2 or string3
1683>>> non_null
1684'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001685\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001686
Fred Drake3f205921998-01-13 18:56:38 +00001687Note that in Python, unlike \C{}, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001688
Fred Drakeb7833d31998-09-11 16:21:55 +00001689\section{Comparing Sequences and Other Types \label{comparing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001690
1691Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001692sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001693first the first two items are compared, and if they differ this
1694determines the outcome of the comparison; if they are equal, the next
1695two items are compared, and so on, until either sequence is exhausted.
1696If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001697the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001698items of two sequences compare equal, the sequences are considered
1699equal. If one sequence is an initial subsequence of the other, the
1700shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001701strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001702examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001703
Fred Drake8842e861998-02-13 07:16:30 +00001704\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001705(1, 2, 3) < (1, 2, 4)
1706[1, 2, 3] < [1, 2, 4]
1707'ABC' < 'C' < 'Pascal' < 'Python'
1708(1, 2, 3, 4) < (1, 2, 4)
1709(1, 2) < (1, 2, -1)
1710(1, 2, 3) = (1.0, 2.0, 3.0)
1711(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001712\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001713
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001714Note that comparing objects of different types is legal. The outcome
1715is deterministic but arbitrary: the types are ordered by their name.
1716Thus, a list is always smaller than a string, a string is always
1717smaller than a tuple, etc. Mixed numeric types are compared according
1718to their numeric value, so 0 equals 0.0, etc.%
1719\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001720 The rules for comparing objects of different types should
1721 not be relied upon; they may change in a future version of
1722 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001723}
1724
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001725
Fred Drakeb7833d31998-09-11 16:21:55 +00001726\chapter{Modules \label{modules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001727
Guido van Rossum4410c751991-06-04 20:22:18 +00001728If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001729definitions you have made (functions and variables) are lost.
1730Therefore, if you want to write a somewhat longer program, you are
1731better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001732and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001733\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001734into several files for easier maintenance. You may also want to use a
1735handy function that you've written in several programs without copying
1736its definition into each program.
1737
Guido van Rossum4410c751991-06-04 20:22:18 +00001738To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001739them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001740Such a file is called a \emph{module}; definitions from a module can be
1741\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001742collection of variables that you have access to in a script
1743executed at the top level
1744and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001745
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001746A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001747file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001748a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001749the global variable \code{__name__}. For instance, use your favorite text
1750editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001751with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001752
Fred Drake8842e861998-02-13 07:16:30 +00001753\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001754# Fibonacci numbers module
1755
1756def fib(n): # write Fibonacci series up to n
1757 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001758 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001759 print b,
1760 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001761
1762def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001763 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001764 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001765 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001766 result.append(b)
1767 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001768 return result
Fred Drake8842e861998-02-13 07:16:30 +00001769\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001770
Guido van Rossum4410c751991-06-04 20:22:18 +00001771Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001772following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001773
Fred Drake8842e861998-02-13 07:16:30 +00001774\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001775>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001776\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001777
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001778This does not enter the names of the functions defined in
Fred Drakeeee08cd1997-12-04 15:43:15 +00001779\code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001780directly in the current symbol table; it only enters the module name
Fred Drakeeee08cd1997-12-04 15:43:15 +00001781\code{fibo}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001782there.
1783Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001784
Fred Drake8842e861998-02-13 07:16:30 +00001785\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001786>>> fibo.fib(1000)
17871 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1788>>> fibo.fib2(100)
1789[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001790>>> fibo.__name__
1791'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001792\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001793%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001794If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001795
Fred Drake8842e861998-02-13 07:16:30 +00001796\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001797>>> fib = fibo.fib
1798>>> fib(500)
17991 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001800\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001801
Guido van Rossum02455691997-07-17 16:21:52 +00001802
Fred Drakeb7833d31998-09-11 16:21:55 +00001803\section{More on Modules \label{moreModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001804
1805A module can contain executable statements as well as function
1806definitions.
1807These statements are intended to initialize the module.
1808They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001809\emph{first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001810time the module is imported somewhere.%
1811\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001812 In fact function definitions are also `statements' that are
1813 `executed'; the execution enters the function name in the
1814 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001815}
1816
1817Each module has its own private symbol table, which is used as the
1818global symbol table by all functions defined in the module.
1819Thus, the author of a module can use global variables in the module
1820without worrying about accidental clashes with a user's global
1821variables.
1822On the other hand, if you know what you are doing you can touch a
1823module's global variables with the same notation used to refer to its
1824functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001825\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001826
1827Modules can import other modules.
1828It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001829\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001830statements at the beginning of a module (or script, for that matter).
1831The imported module names are placed in the importing module's global
1832symbol table.
1833
1834There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001835\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001836statement that imports names from a module directly into the importing
1837module's symbol table.
1838For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001839
Fred Drake8842e861998-02-13 07:16:30 +00001840\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001841>>> from fibo import fib, fib2
1842>>> fib(500)
18431 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001844\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001845
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001846This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001847in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001848defined).
1849
1850There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001851
Fred Drake8842e861998-02-13 07:16:30 +00001852\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001853>>> from fibo import *
1854>>> fib(500)
18551 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001856\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001857
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001858This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001859(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001860
Fred Drakeb7833d31998-09-11 16:21:55 +00001861\subsection{The Module Search Path \label{searchPath}}
Guido van Rossum02455691997-07-17 16:21:52 +00001862
Guido van Rossumaee5e261998-08-07 17:45:09 +00001863% XXX Need to document that a lone .pyc/.pyo is acceptable too!
1864
Fred Drake391564f1998-04-01 23:11:56 +00001865\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00001866When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001867for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001868and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00001869the environment variable \envvar{PYTHONPATH}. This has the same syntax as
1870the shell variable \envvar{PATH}, i.e., a list of
1871directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001872is not found there, the search continues in an installation-dependent
Fred Drake391564f1998-04-01 23:11:56 +00001873default path; on \UNIX{}, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001874
1875Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001876variable \code{sys.path} which is initialized from the directory
1877containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00001878\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001879Python programs that know what they're doing to modify or replace the
1880module search path. See the section on Standard Modules later.
1881
1882\subsection{``Compiled'' Python files}
1883
1884As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001885use a lot of standard modules, if a file called \file{spam.pyc} exists
1886in the directory where \file{spam.py} is found, this is assumed to
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001887contain an already-``byte-compiled'' version of the module \module{spam}.
Fred Drake8842e861998-02-13 07:16:30 +00001888The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001889\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1890ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001891
Fred Drakeeee08cd1997-12-04 15:43:15 +00001892Normally, you don't need to do anything to create the \file{spam.pyc} file.
1893Whenever \file{spam.py} is successfully compiled, an attempt is made to
1894write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001895this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001896completely, the resulting \file{spam.pyc} file will be recognized as
1897invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001898file is platform independent, so a Python module directory can be
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001899shared by machines of different architectures.
Guido van Rossum02455691997-07-17 16:21:52 +00001900
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001901Some tips for experts:
1902
1903\begin{itemize}
1904
1905\item
1906When the Python interpreter is invoked with the \code{-O} flag,
1907optimized code is generated and stored in \file{.pyo} files.
1908The optimizer currently doesn't help much; it only removes
1909\keyword{assert} statements and \code{SET_LINENO} instructions.
1910When \code{-O} is used, \emph{all} bytecode is optimized; \code{.pyc}
1911files are ignored and \code{.py} files are compiled to optimized
1912bytecode.
1913
1914\item
1915A program doesn't run any faster when it is read from a
1916\file{.pyc} or \file{.pyo} file than when it is read from a \file{.py}
1917file; the only thing that's faster about \file{.pyc} or \file{.pyo}
1918files is the speed with which they are loaded.
1919
1920\item
Guido van Rossum002f7aa1998-06-28 19:16:38 +00001921When a script is run by giving its name on the command line, the
1922bytecode for the script is never written to a \file{.pyc} or
1923\file{.pyo} file. Thus, the startup time of a script may be reduced
1924by moving most of its code to a module and having a small bootstrap
1925script that imports that module.
1926
1927\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001928It is possible to have a file called \file{spam.pyc} (or
1929\file{spam.pyo} when \code{-O} is used) without a module
1930\file{spam.py} in the same module. This can be used to distribute
1931a library of Python code in a form that is moderately hard to reverse
1932engineer.
1933
1934\item
1935The module \module{compileall}\refstmodindex{compileall} can create
1936\file{.pyc} files (or \file{.pyo} files when \code{-O} is used) for
1937all modules in a directory.
1938
1939\end{itemize}
1940
Guido van Rossum02455691997-07-17 16:21:52 +00001941
Fred Drakeb7833d31998-09-11 16:21:55 +00001942\section{Standard Modules \label{standardModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001943
Guido van Rossum4410c751991-06-04 20:22:18 +00001944Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001945document, the \emph{Python Library Reference} (``Library Reference''
1946hereafter). Some modules are built into the interpreter; these
1947provide access to operations that are not part of the core of the
1948language but are nevertheless built in, either for efficiency or to
1949provide access to operating system primitives such as system calls.
1950The set of such modules is a configuration option; e.g., the
1951\module{amoeba} module is only provided on systems that somehow
1952support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00001953attention: \module{sys}\refstmodindex{sys}, which is built into every
1954Python interpreter. The variables \code{sys.ps1} and \code{sys.ps2}
1955define the strings used as primary and secondary prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001956
Fred Drake8842e861998-02-13 07:16:30 +00001957\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001958>>> import sys
1959>>> sys.ps1
1960'>>> '
1961>>> sys.ps2
1962'... '
1963>>> sys.ps1 = 'C> '
1964C> print 'Yuck!'
1965Yuck!
1966C>
Fred Drake8842e861998-02-13 07:16:30 +00001967\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001968
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001969These two variables are only defined if the interpreter is in
1970interactive mode.
1971
1972The variable
Fred Drakeeee08cd1997-12-04 15:43:15 +00001973\code{sys.path}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001974is a list of strings that determine the interpreter's search path for
1975modules.
1976It is initialized to a default path taken from the environment variable
Fred Drake391564f1998-04-01 23:11:56 +00001977\envvar{PYTHONPATH}, or from a built-in default if \envvar{PYTHONPATH}
1978is not set. You can modify it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001979
Fred Drake8842e861998-02-13 07:16:30 +00001980\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001981>>> import sys
1982>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00001983\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001984
Fred Drakeb7833d31998-09-11 16:21:55 +00001985\section{The \function{dir()} Function \label{dir}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001986
Fred Drake8842e861998-02-13 07:16:30 +00001987The built-in function \function{dir()} is used to find out which names
1988a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001989
Fred Drake8842e861998-02-13 07:16:30 +00001990\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001991>>> import fibo, sys
1992>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00001993['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001994>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00001995['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
1996'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
1997'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00001998\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001999
Fred Drake8842e861998-02-13 07:16:30 +00002000Without arguments, \function{dir()} lists the names you have defined
2001currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002002
Fred Drake8842e861998-02-13 07:16:30 +00002003\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002004>>> a = [1, 2, 3, 4, 5]
2005>>> import fibo, sys
2006>>> fib = fibo.fib
2007>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00002008['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00002009\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002010
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002011Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002012
Fred Drake8842e861998-02-13 07:16:30 +00002013\function{dir()} does not list the names of built-in functions and
2014variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00002015standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002016
Fred Drake8842e861998-02-13 07:16:30 +00002017\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00002018>>> import __builtin__
2019>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00002020['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
2021'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2022'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
2023'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
2024'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
2025'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
2026'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
2027'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
2028'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00002029\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002030
Fred Drakeb7833d31998-09-11 16:21:55 +00002031\section{Packages \label{packages}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002032
2033Packages are a way of structuring Python's module namespace
Fred Drakeb7833d31998-09-11 16:21:55 +00002034by using ``dotted module names''. For example, the module name
2035\module{A.B} designates a submodule named \samp{B} in a package named
2036\samp{A}. Just like the use of modules saves the authors of different
2037modules from having to worry about each other's global variable names,
2038the use of dotted module names saves the authors of multi-module
2039packages like NumPy or PIL from having to worry about each other's
2040module names.
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002041
2042Suppose you want to design a collection of modules (a ``package'') for
2043the uniform handling of sound files and sound data. There are many
2044different sound file formats (usually recognized by their extension,
2045e.g. \file{.wav}, \file{.aiff}, \file{.au}), so you may need to create
2046and maintain a growing collection of modules for the conversion
2047between the various file formats. There are also many different
2048operations you might want to perform on sound data (e.g. mixing,
2049adding echo, applying an equalizer function, creating an artificial
2050stereo effect), so in addition you will be writing a never-ending
2051stream of modules to perform these operations. Here's a possible
2052structure for your package (expressed in terms of a hierarchical
2053filesystem):
2054
2055\begin{verbatim}
2056Sound/ Top-level package
2057 __init__.py Initialize the sound package
2058 Formats/ Subpackage for file format conversions
2059 __init__.py
2060 wavread.py
2061 wavwrite.py
2062 aiffread.py
2063 aiffwrite.py
2064 auread.py
2065 auwrite.py
2066 ...
2067 Effects/ Subpackage for sound effects
2068 __init__.py
2069 echo.py
2070 surround.py
2071 reverse.py
2072 ...
2073 Filters/ Subpackage for filters
2074 __init__.py
2075 equalizer.py
2076 vocoder.py
2077 karaoke.py
2078 ...
2079\end{verbatim}
2080The \file{__init__.py} files are required to make Python treat the
2081directories as containing packages; this is done to prevent
2082directories with a common name, such as \samp{string}, from
2083unintentionally hiding valid modules that occur later on the module
2084search path. In the simplest case, \file{__init__.py} can just be an
2085empty file, but it can also execute initialization code for the
2086package or set the \code{__all__} variable, described later.
2087
2088Users of the package can import individual modules from the
2089package, for example:
2090
2091\begin{verbatim}
2092import Sound.Effects.echo
2093\end{verbatim}
2094This loads the submodule \module{Sound.Effects.echo}. It must be referenced
2095with its full name, e.g.
2096
2097\begin{verbatim}
2098Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
2099\end{verbatim}
2100An alternative way of importing the submodule is:
2101
2102\begin{verbatim}
2103from Sound.Effects import echo
2104\end{verbatim}
2105This also loads the submodule \module{echo}, and makes it available without
2106its package prefix, so it can be used as follows:
2107
2108\begin{verbatim}
2109echo.echofilter(input, output, delay=0.7, atten=4)
2110\end{verbatim}
2111
2112Yet another variation is to import the desired function or variable directly:
2113
2114\begin{verbatim}
2115from Sound.Effects.echo import echofilter
2116\end{verbatim}
2117
2118Again, this loads the submodule \module{echo}, but this makes its function
2119echofilter directly available:
2120
2121\begin{verbatim}
2122echofilter(input, output, delay=0.7, atten=4)
2123\end{verbatim}
2124
2125Note that when using \code{from \var{package} import \var{item}}, the
2126item can be either a submodule (or subpackage) of the package, or some
2127other name defined in the package, like a function, class or
2128variable. The \code{import} statement first tests whether the item is
2129defined in the package; if not, it assumes it is a module and attempts
2130to load it. If it fails to find it, \exception{ImportError} is raised.
2131
2132Contrarily, when using syntax like \code{import
2133\var{item.subitem.subsubitem}}, each item except for the last must be
2134a package; the last item can be a module or a package but can't be a
2135class or function or variable defined in the previous item.
2136
Fred Drakeb7833d31998-09-11 16:21:55 +00002137\subsection{Importing * From a Package \label{pkg-import-star}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002138%The \code{__all__} Attribute
2139
2140Now what happens when the user writes \code{from Sound.Effects import
2141*}? Ideally, one would hope that this somehow goes out to the
2142filesystem, finds which submodules are present in the package, and
2143imports them all. Unfortunately, this operation does not work very
2144well on Mac and Windows platforms, where the filesystem does not
2145always have accurate information about the case of a filename! On
2146these platforms, there is no guaranteed way to know whether a file
2147\file{ECHO.PY} should be imported as a module \module{echo},
2148\module{Echo} or \module{ECHO}. (For example, Windows 95 has the
2149annoying practice of showing all file names with a capitalized first
2150letter.) The DOS 8+3 filename restriction adds another interesting
2151problem for long module names.
2152
2153The only solution is for the package author to provide an explicit
2154index of the package. The import statement uses the following
2155convention: if a package's \file{__init__.py} code defines a list named
2156\code{__all__}, it is taken to be the list of module names that should be imported
2157when \code{from \var{package} import *} is
2158encountered. It is up to the package author to keep this list
2159up-to-date when a new version of the package is released. Package
2160authors may also decide not to support it, if they don't see a use for
2161importing * from their package. For example, the file
2162\code{Sounds/Effects/__init__.py} could contain the following code:
2163
2164\begin{verbatim}
2165__all__ = ["echo", "surround", "reverse"]
2166\end{verbatim}
2167
2168This would mean that \code{from Sound.Effects import *} would
2169import the three named submodules of the \module{Sound} package.
2170
2171If \code{__all__} is not defined, the statement \code{from Sound.Effects
2172import *} does \emph{not} import all submodules from the package
2173\module{Sound.Effects} into the current namespace; it only ensures that the
2174package \module{Sound.Effects} has been imported (possibly running its
2175initialization code, \file{__init__.py}) and then imports whatever names are
2176defined in the package. This includes any names defined (and
2177submodules explicitly loaded) by \file{__init__.py}. It also includes any
2178submodules of the package that were explicitly loaded by previous
2179import statements, e.g.
2180
2181\begin{verbatim}
2182import Sound.Effects.echo
2183import Sound.Effects.surround
2184from Sound.Effects import *
2185\end{verbatim}
2186
2187
2188In this example, the echo and surround modules are imported in the
2189current namespace because they are defined in the \module{Sound.Effects}
2190package when the \code{from...import} statement is executed. (This also
2191works when \code{__all__} is defined.)
2192
2193Note that in general the practicing of importing * from a module or
2194package is frowned upon, since it often causes poorly readable code.
2195However, it is okay to use it to save typing in interactive sessions,
2196and certain modules are designed to export only names that follow
2197certain patterns.
2198
2199Remember, there is nothing wrong with using \code{from Package
2200import specific_submodule}! In fact, this is the
2201recommended notation unless the importing module needs to use
2202submodules with the same name from different packages.
2203
2204
2205\subsection{Intra-package References}
2206
2207The submodules often need to refer to each other. For example, the
2208\module{surround} module might use the \module{echo} module. In fact, such references
2209are so common that the \code{import} statement first looks in the
2210containing package before looking in the standard module search path.
2211Thus, the surround module can simply use \code{import echo} or
2212\code{from echo import echofilter}. If the imported module is not
2213found in the current package (the package of which the current module
2214is a submodule), the \code{import} statement looks for a top-level module
2215with the given name.
2216
2217When packages are structured into subpackages (as with the \module{Sound}
2218package in the example), there's no shortcut to refer to submodules of
2219sibling packages - the full name of the subpackage must be used. For
2220example, if the module \module{Sound.Filters.vocoder} needs to use the \module{echo}
2221module in the \module{Sound.Effects} package, it can use \code{from
2222Sound.Effects import echo}.
2223
2224%(One could design a notation to refer to parent packages, similar to
2225%the use of ".." to refer to the parent directory in Unix and Windows
2226%filesystems. In fact, the \module{ni} module, which was the
2227%ancestor of this package system, supported this using \code{__} for
2228%the package containing the current module,
2229%\code{__.__} for the parent package, and so on. This feature was dropped
2230%because of its awkwardness; since most packages will have a relative
2231%shallow substructure, this is no big loss.)
2232
2233
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002234
Fred Drakeb7833d31998-09-11 16:21:55 +00002235\chapter{Input and Output \label{io}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002236
Guido van Rossum02455691997-07-17 16:21:52 +00002237There are several ways to present the output of a program; data can be
2238printed in a human-readable form, or written to a file for future use.
2239This chapter will discuss some of the possibilities.
2240
Fred Drakeb7833d31998-09-11 16:21:55 +00002241
2242\section{Fancier Output Formatting \label{formatting}}
2243
Fred Drakeeee08cd1997-12-04 15:43:15 +00002244So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00002245statements} and the \keyword{print} statement. (A third way is using
2246the \method{write()} method of file objects; the standard output file
2247can be referenced as \code{sys.stdout}. See the Library Reference for
2248more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002249
2250Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00002251simply printing space-separated values. There are two ways to format
2252your output; the first way is to do all the string handling yourself;
2253using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00002254lay-out you can imagine. The standard module
2255\module{string}\refstmodindex{string} contains some useful operations
2256for padding strings to a given column width;
Guido van Rossum02455691997-07-17 16:21:52 +00002257these will be discussed shortly. The second way is to use the
2258\code{\%} operator with a string as the left argument. \code{\%}
Fred Drake8842e861998-02-13 07:16:30 +00002259interprets the left argument as a \C{} \cfunction{sprintf()}-style
2260format string to be applied to the right argument, and returns the
2261string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002262
2263One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00002264Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00002265the \function{repr()} function, or just write the value between
2266reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002267
Fred Drake8842e861998-02-13 07:16:30 +00002268\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002269>>> x = 10 * 3.14
2270>>> y = 200*200
2271>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2272>>> print s
2273The value of x is 31.4, and y is 40000...
2274>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00002275... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00002276>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002277>>> ps
2278'[31.4, 40000]'
2279>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00002280... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002281>>> hellos = `hello`
2282>>> print hellos
2283'hello, world\012'
2284>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002285... `x, y, ('spam', 'eggs')`
2286"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00002287\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002288
Guido van Rossum6938f061994-08-01 12:22:53 +00002289Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002290
Fred Drake8842e861998-02-13 07:16:30 +00002291\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002292>>> import string
2293>>> for x in range(1, 11):
2294... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
2295... # Note trailing comma on previous line
2296... print string.rjust(`x*x*x`, 4)
2297...
2298 1 1 1
2299 2 4 8
2300 3 9 27
2301 4 16 64
2302 5 25 125
2303 6 36 216
2304 7 49 343
2305 8 64 512
2306 9 81 729
230710 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002308>>> for x in range(1,11):
2309... print '%2d %3d %4d' % (x, x*x, x*x*x)
2310...
2311 1 1 1
2312 2 4 8
2313 3 9 27
2314 4 16 64
2315 5 25 125
2316 6 36 216
2317 7 49 343
2318 8 64 512
2319 9 81 729
232010 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002321\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002322
Fred Drake8842e861998-02-13 07:16:30 +00002323(Note that one space between each column was added by the way
2324\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002325
Fred Drake8842e861998-02-13 07:16:30 +00002326This example demonstrates the function \function{string.rjust()},
2327which right-justifies a string in a field of a given width by padding
2328it with spaces on the left. There are similar functions
2329\function{string.ljust()} and \function{string.center()}. These
2330functions do not write anything, they just return a new string. If
2331the input string is too long, they don't truncate it, but return it
2332unchanged; this will mess up your column lay-out but that's usually
2333better than the alternative, which would be lying about a value. (If
2334you really want truncation you can always add a slice operation, as in
2335\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002336
Fred Drake8842e861998-02-13 07:16:30 +00002337There is another function, \function{string.zfill()}, which pads a
2338numeric string on the left with zeros. It understands about plus and
2339minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002340
Fred Drake8842e861998-02-13 07:16:30 +00002341\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002342>>> string.zfill('12', 5)
2343'00012'
2344>>> string.zfill('-3.14', 7)
2345'-003.14'
2346>>> string.zfill('3.14159265359', 5)
2347'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002348\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002349%
2350Using the \code{\%} operator looks like this:
2351
2352\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002353>>> import math
2354>>> print 'The value of PI is approximately %5.3f.' % math.pi
2355The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002356\end{verbatim}
2357
2358If there is more than one format in the string you pass a tuple as
2359right operand, e.g.
2360
2361\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002362>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2363>>> for name, phone in table.items():
2364... print '%-10s ==> %10d' % (name, phone)
2365...
2366Jack ==> 4098
2367Dcab ==> 8637678
2368Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002369\end{verbatim}
2370
Fred Drake3f205921998-01-13 18:56:38 +00002371Most formats work exactly as in \C{} and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002372type; however, if you don't you get an exception, not a core dump.
Fred Drakedb70d061998-11-17 21:59:04 +00002373The \code{\%s} format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002374not a string object, it is converted to string using the
2375\function{str()} built-in function. Using \code{*} to pass the width
2376or precision in as a separate (integer) argument is supported. The
Fred Drakedb70d061998-11-17 21:59:04 +00002377\C{} formats \code{\%n} and \code{\%p} are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002378
2379If you have a really long format string that you don't want to split
2380up, it would be nice if you could reference the variables to be
2381formatted by name instead of by position. This can be done by using
Fred Drakedb70d061998-11-17 21:59:04 +00002382an extension of \C{} formats using the form \code{\%(name)format}, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002383
2384\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002385>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2386>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2387Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002388\end{verbatim}
2389
2390This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002391\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002392local variables.
2393
Fred Drakeb7833d31998-09-11 16:21:55 +00002394\section{Reading and Writing Files \label{files}}
Fred Drake6c2176e1998-02-26 21:47:54 +00002395
Guido van Rossum02455691997-07-17 16:21:52 +00002396% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002397\function{open()}\bifuncindex{open} returns a file
2398object\obindex{file}, and is most commonly used with two arguments:
2399\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002400
Fred Drake8842e861998-02-13 07:16:30 +00002401\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002402>>> f=open('/tmp/workfile', 'w')
2403>>> print f
2404<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002405\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002406
Guido van Rossum02455691997-07-17 16:21:52 +00002407The first argument is a string containing the filename. The second
2408argument is another string containing a few characters describing the
2409way in which the file will be used. \var{mode} can be \code{'r'} when
2410the file will only be read, \code{'w'} for only writing (an existing
2411file with the same name will be erased), and \code{'a'} opens the file
2412for appending; any data written to the file is automatically added to
2413the end. \code{'r+'} opens the file for both reading and writing.
2414The \var{mode} argument is optional; \code{'r'} will be assumed if
2415it's omitted.
2416
Fred Drake391564f1998-04-01 23:11:56 +00002417On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00002418mode opens the file in binary mode, so there are also modes like
2419\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2420distinction between text and binary files; the end-of-line characters
2421in text files are automatically altered slightly when data is read or
2422written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002423\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2424\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00002425writing such files. (Note that the precise semantics of text mode on
2426the Macintosh depends on the underlying \C{} library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00002427
Fred Drakeb7833d31998-09-11 16:21:55 +00002428\subsection{Methods of File Objects \label{fileMethods}}
Guido van Rossum02455691997-07-17 16:21:52 +00002429
2430The rest of the examples in this section will assume that a file
2431object called \code{f} has already been created.
2432
2433To read a file's contents, call \code{f.read(\var{size})}, which reads
2434some quantity of data and returns it as a string. \var{size} is an
2435optional numeric argument. When \var{size} is omitted or negative,
2436the entire contents of the file will be read and returned; it's your
2437problem if the file is twice as large as your machine's memory.
2438Otherwise, at most \var{size} bytes are read and returned. If the end
2439of the file has been reached, \code{f.read()} will return an empty
2440string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002441\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002442>>> f.read()
2443'This is the entire file.\012'
2444>>> f.read()
2445''
Fred Drake8842e861998-02-13 07:16:30 +00002446\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002447
Guido van Rossum02455691997-07-17 16:21:52 +00002448\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002449character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002450omitted on the last line of the file if the file doesn't end in a
2451newline. This makes the return value unambiguous; if
2452\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002453been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002454string containing only a single newline.
2455
Fred Drake8842e861998-02-13 07:16:30 +00002456\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002457>>> f.readline()
2458'This is the first line of the file.\012'
2459>>> f.readline()
2460'Second line of the file\012'
2461>>> f.readline()
2462''
Fred Drake8842e861998-02-13 07:16:30 +00002463\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002464
Fred Drakeeee08cd1997-12-04 15:43:15 +00002465\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002466a list containing all the lines of data in the file.
2467
Fred Drake8842e861998-02-13 07:16:30 +00002468\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002469>>> f.readlines()
2470['This is the first line of the file.\012', 'Second line of the file\012']
Fred Drake8842e861998-02-13 07:16:30 +00002471\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002472
Guido van Rossum02455691997-07-17 16:21:52 +00002473\code{f.write(\var{string})} writes the contents of \var{string} to
2474the file, returning \code{None}.
2475
Fred Drake8842e861998-02-13 07:16:30 +00002476\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002477>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002478\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002479
Guido van Rossum02455691997-07-17 16:21:52 +00002480\code{f.tell()} returns an integer giving the file object's current
2481position in the file, measured in bytes from the beginning of the
2482file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002483\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002484computed from adding \var{offset} to a reference point; the reference
2485point is selected by the \var{from_what} argument. A \var{from_what}
2486value of 0 measures from the beginning of the file, 1 uses the current
2487file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002488\var{from_what} can be omitted and defaults to 0, using the beginning
2489of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002490
Fred Drake8842e861998-02-13 07:16:30 +00002491\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002492>>> f=open('/tmp/workfile', 'r+')
2493>>> f.write('0123456789abcdef')
2494>>> f.seek(5) # Go to the 5th byte in the file
2495>>> f.read(1)
2496'5'
2497>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2498>>> f.read(1)
2499'd'
Fred Drake8842e861998-02-13 07:16:30 +00002500\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002501
Guido van Rossum02455691997-07-17 16:21:52 +00002502When you're done with a file, call \code{f.close()} to close it and
2503free up any system resources taken up by the open file. After calling
2504\code{f.close()}, attempts to use the file object will automatically fail.
2505
Fred Drake8842e861998-02-13 07:16:30 +00002506\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002507>>> f.close()
2508>>> f.read()
2509Traceback (innermost last):
2510 File "<stdin>", line 1, in ?
2511ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002512\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002513
Fred Drake8842e861998-02-13 07:16:30 +00002514File objects have some additional methods, such as \method{isatty()}
2515and \method{truncate()} which are less frequently used; consult the
2516Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002517
Fred Drakeb7833d31998-09-11 16:21:55 +00002518\subsection{The \module{pickle} Module \label{pickle}}
Fred Drake391564f1998-04-01 23:11:56 +00002519\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00002520
2521Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002522bit more effort, since the \method{read()} method only returns
2523strings, which will have to be passed to a function like
2524\function{string.atoi()}, which takes a string like \code{'123'} and
2525returns its numeric value 123. However, when you want to save more
2526complex data types like lists, dictionaries, or class instances,
2527things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002528
2529Rather than have users be constantly writing and debugging code to
2530save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002531\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002532any Python object (even some forms of Python code!), and convert it to
2533a string representation; this process is called \dfn{pickling}.
2534Reconstructing the object from the string representation is called
2535\dfn{unpickling}. Between pickling and unpickling, the string
2536representing the object may have been stored in a file or data, or
2537sent over a network connection to some distant machine.
2538
2539If you have an object \code{x}, and a file object \code{f} that's been
2540opened for writing, the simplest way to pickle the object takes only
2541one line of code:
2542
Fred Drake8842e861998-02-13 07:16:30 +00002543\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002544pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002545\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002546
Fred Drake8842e861998-02-13 07:16:30 +00002547To unpickle the object again, if \code{f} is a file object which has
2548been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002549
Fred Drake8842e861998-02-13 07:16:30 +00002550\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002551x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002552\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002553
Guido van Rossum02455691997-07-17 16:21:52 +00002554(There are other variants of this, used when pickling many objects or
2555when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002556complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002557
Fred Drake8842e861998-02-13 07:16:30 +00002558\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002559stored and reused by other programs or by a future invocation of the
2560same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002561object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002562write Python extensions take care to ensure that new data types such
Fred Drake72389881998-04-13 01:31:10 +00002563as matrices can be properly pickled and unpickled.
Guido van Rossum02455691997-07-17 16:21:52 +00002564
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002565
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002566
Fred Drakeb7833d31998-09-11 16:21:55 +00002567\chapter{Errors and Exceptions \label{errors}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002568
2569Until now error messages haven't been more than mentioned, but if you
2570have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002571(at least) two distinguishable kinds of errors: \emph{syntax errors}
2572and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002573
Fred Drakeb7833d31998-09-11 16:21:55 +00002574\section{Syntax Errors \label{syntaxErrors}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002575
2576Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002577kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002578
Fred Drake8842e861998-02-13 07:16:30 +00002579\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002580>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002581 File "<stdin>", line 1
2582 while 1 print 'Hello world'
2583 ^
2584SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002585\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002586
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002587The parser repeats the offending line and displays a little `arrow'
2588pointing at the earliest point in the line where the error was detected.
2589The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002590\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002591the arrow: in the example, the error is detected at the keyword
Fred Drake391564f1998-04-01 23:11:56 +00002592\keyword{print}, since a colon (\character{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002593File name and line number are printed so you know where to look in case
2594the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002595
Fred Drakeb7833d31998-09-11 16:21:55 +00002596\section{Exceptions \label{exceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002597
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002598Even if a statement or expression is syntactically correct, it may
2599cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002600Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002601not unconditionally fatal: you will soon learn how to handle them in
2602Python programs. Most exceptions are not handled by programs,
2603however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002604
Fred Drake8842e861998-02-13 07:16:30 +00002605\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002606>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002607Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002608 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002609ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002610>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002611Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002612 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002613NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002614>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002615Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002616 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002617TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002618\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002619
Guido van Rossumb2c65561993-05-12 08:53:36 +00002620The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002621Exceptions come in different types, and the type is printed as part of
2622the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002623\exception{ZeroDivisionError},
2624\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002625and
Fred Drake8842e861998-02-13 07:16:30 +00002626\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002627The string printed as the exception type is the name of the built-in
2628name for the exception that occurred. This is true for all built-in
2629exceptions, but need not be true for user-defined exceptions (although
2630it is a useful convention).
2631Standard exception names are built-in identifiers (not reserved
2632keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002633
Guido van Rossumb2c65561993-05-12 08:53:36 +00002634The rest of the line is a detail whose interpretation depends on the
2635exception type; its meaning is dependent on the exception type.
2636
2637The preceding part of the error message shows the context where the
2638exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002639In general it contains a stack backtrace listing source lines; however,
2640it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002641
Fred Drake8842e861998-02-13 07:16:30 +00002642The Library Reference lists the built-in exceptions and their
2643meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002644
Fred Drakeb7833d31998-09-11 16:21:55 +00002645\section{Handling Exceptions \label{handling}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002646
2647It is possible to write programs that handle selected exceptions.
2648Look at the following example, which prints a table of inverses of
2649some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002650
Fred Drake8842e861998-02-13 07:16:30 +00002651\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002652>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002653>>> for x in numbers:
2654... print x,
2655... try:
2656... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002657... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002658... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002659...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000026600.3333 3.00030003
26612.5 0.4
26620 *** has no inverse ***
266310 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002664\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002665
Fred Drake8842e861998-02-13 07:16:30 +00002666The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002667\begin{itemize}
2668\item
Fred Drake8842e861998-02-13 07:16:30 +00002669First, the \emph{try clause}
2670(the statement(s) between the \keyword{try} and \keyword{except}
2671keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002672\item
2673If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002674\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002675is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002676\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002677If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002678the rest of the clause is skipped. Then if its type matches the
2679exception named after the \keyword{except} keyword, the rest of the
2680try clause is skipped, the except clause is executed, and then
2681execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002682\item
2683If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002684except clause, it is passed on to outer \keyword{try} statements; if
2685no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002686and execution stops with a message as shown above.
2687\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002688A \keyword{try} statement may have more than one except clause, to
2689specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002690At most one handler will be executed.
2691Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002692clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002693An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002694e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002695
Fred Drake8842e861998-02-13 07:16:30 +00002696\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002697... except (RuntimeError, TypeError, NameError):
2698... pass
Fred Drake8842e861998-02-13 07:16:30 +00002699\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002700
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002701The last except clause may omit the exception name(s), to serve as a
2702wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002703Use this with extreme caution, since it is easy to mask a real
2704programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002705
Fred Drake8842e861998-02-13 07:16:30 +00002706The \keyword{try} \ldots\ \keyword{except} statement has an optional
2707\emph{else clause}, which must follow all except clauses. It is
2708useful to place code that must be executed if the try clause does not
2709raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002710
2711\begin{verbatim}
Guido van Rossuma4289a71998-07-07 20:18:06 +00002712for arg in sys.argv[1:]:
Fred Drake8842e861998-02-13 07:16:30 +00002713 try:
2714 f = open(arg, 'r')
2715 except IOError:
2716 print 'cannot open', arg
2717 else:
2718 print arg, 'has', len(f.readlines()), 'lines'
2719 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002720\end{verbatim}
2721
2722
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002723When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002724the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002725The presence and type of the argument depend on the exception type.
2726For exception types which have an argument, the except clause may
2727specify a variable after the exception name (or list) to receive the
2728argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002729
Fred Drake8842e861998-02-13 07:16:30 +00002730\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002731>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002732... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002733... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002734... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002735...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002736name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002737\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002738
Guido van Rossumb2c65561993-05-12 08:53:36 +00002739If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002740(`detail') of the message for unhandled exceptions.
2741
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002742Exception handlers don't just handle exceptions if they occur
2743immediately in the try clause, but also if they occur inside functions
2744that are called (even indirectly) in the try clause.
2745For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002746
Fred Drake8842e861998-02-13 07:16:30 +00002747\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002748>>> def this_fails():
2749... x = 1/0
2750...
2751>>> try:
2752... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002753... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002754... print 'Handling run-time error:', detail
2755...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002756Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002757\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002758
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002759
Fred Drakeb7833d31998-09-11 16:21:55 +00002760\section{Raising Exceptions \label{raising}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002761
Fred Drake8842e861998-02-13 07:16:30 +00002762The \keyword{raise} statement allows the programmer to force a
2763specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002764For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002765
Fred Drake8842e861998-02-13 07:16:30 +00002766\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002767>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002768Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002769 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002770NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002771\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002772
Fred Drake8842e861998-02-13 07:16:30 +00002773The first argument to \keyword{raise} names the exception to be
2774raised. The optional second argument specifies the exception's
2775argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002776
Guido van Rossum02455691997-07-17 16:21:52 +00002777
Fred Drakeb7833d31998-09-11 16:21:55 +00002778\section{User-defined Exceptions \label{userExceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002779
2780Programs may name their own exceptions by assigning a string to a
2781variable.
2782For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002783
Fred Drake8842e861998-02-13 07:16:30 +00002784\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002785>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002786>>> try:
2787... raise my_exc, 2*2
2788... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002789... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002790...
Guido van Rossum6938f061994-08-01 12:22:53 +00002791My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002792>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002793Traceback (innermost last):
2794 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002795my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002796\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002797
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002798Many standard modules use this to report errors that may occur in
2799functions they define.
2800
Guido van Rossum02455691997-07-17 16:21:52 +00002801
Fred Drakeb7833d31998-09-11 16:21:55 +00002802\section{Defining Clean-up Actions \label{cleanup}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002803
Fred Drake8842e861998-02-13 07:16:30 +00002804The \keyword{try} statement has another optional clause which is
2805intended to define clean-up actions that must be executed under all
2806circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002807
Fred Drake8842e861998-02-13 07:16:30 +00002808\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002809>>> try:
2810... raise KeyboardInterrupt
2811... finally:
2812... print 'Goodbye, world!'
2813...
2814Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002815Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002816 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002817KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002818\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002819
Fred Drake8842e861998-02-13 07:16:30 +00002820A \emph{finally clause} is executed whether or not an exception has
2821occurred in the try clause. When an exception has occurred, it is
2822re-raised after the finally clause is executed. The finally clause is
2823also executed ``on the way out'' when the \keyword{try} statement is
2824left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002825
Fred Drake8842e861998-02-13 07:16:30 +00002826A \keyword{try} statement must either have one or more except clauses
2827or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002828
Fred Drakeb7833d31998-09-11 16:21:55 +00002829\chapter{Classes \label{classes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002830
2831Python's class mechanism adds classes to the language with a minimum
2832of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002833found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002834do not put an absolute barrier between definition and user, but rather
2835rely on the politeness of the user not to ``break into the
2836definition.'' The most important features of classes are retained
2837with full power, however: the class inheritance mechanism allows
2838multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00002839base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002840same name. Objects can contain an arbitrary amount of private data.
2841
Guido van Rossum16d6e711994-08-08 12:30:22 +00002842In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002843\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002844no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002845shorthands for referencing the object's members from its methods: the
2846method function is declared with an explicit first argument
2847representing the object, which is provided implicitly by the call. As
2848in Smalltalk, classes themselves are objects, albeit in the wider
2849sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002850provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002851or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002852extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002853built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00002854subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002855
Fred Drakeb7833d31998-09-11 16:21:55 +00002856\section{A Word About Terminology \label{terminology}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002857
Fred Drake391564f1998-04-01 23:11:56 +00002858Lacking universally accepted terminology to talk about classes, I will
2859make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002860terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002861Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002862
2863I also have to warn you that there's a terminological pitfall for
2864object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002865necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2866unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00002867built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00002868exotic types like files aren't. However, \emph{all} Python types
2869share a little bit of common semantics that is best described by using
2870the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002871
2872Objects have individuality, and multiple names (in multiple scopes)
2873can be bound to the same object. This is known as aliasing in other
2874languages. This is usually not appreciated on a first glance at
2875Python, and can be safely ignored when dealing with immutable basic
2876types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002877(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002878objects such as lists, dictionaries, and most types representing
2879entities outside the program (files, windows, etc.). This is usually
2880used to the benefit of the program, since aliases behave like pointers
2881in some respects. For example, passing an object is cheap since only
2882a pointer is passed by the implementation; and if a function modifies
2883an object passed as an argument, the caller will see the change --- this
2884obviates the need for two different argument passing mechanisms as in
2885Pascal.
2886
2887
Fred Drakeb7833d31998-09-11 16:21:55 +00002888\section{Python Scopes and Name Spaces \label{scopes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002889
2890Before introducing classes, I first have to tell you something about
2891Python's scope rules. Class definitions play some neat tricks with
2892name spaces, and you need to know how scopes and name spaces work to
2893fully understand what's going on. Incidentally, knowledge about this
2894subject is useful for any advanced Python programmer.
2895
2896Let's begin with some definitions.
2897
Fred Drakeeee08cd1997-12-04 15:43:15 +00002898A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002899spaces are currently implemented as Python dictionaries, but that's
2900normally not noticeable in any way (except for performance), and it
2901may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002902built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002903names); the global names in a module; and the local names in a
2904function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002905also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002906spaces is that there is absolutely no relation between names in
2907different name spaces; for instance, two different modules may both
2908define a function ``maximize'' without confusion --- users of the
2909modules must prefix it with the module name.
2910
Fred Drakeeee08cd1997-12-04 15:43:15 +00002911By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002912dot --- for example, in the expression \code{z.real}, \code{real} is
2913an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002914names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002915\code{modname.funcname}, \code{modname} is a module object and
2916\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002917be a straightforward mapping between the module's attributes and the
2918global names defined in the module: they share the same name space!%
2919\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002920 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002921 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002922 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002923 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002924 Obviously, using this violates the abstraction of name space
2925 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002926 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002927}
2928
2929Attributes may be read-only or writable. In the latter case,
2930assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002931you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drake391564f1998-04-01 23:11:56 +00002932also be deleted with the \keyword{del} statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002933\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002934
2935Name spaces are created at different moments and have different
2936lifetimes. The name space containing the built-in names is created
2937when the Python interpreter starts up, and is never deleted. The
2938global name space for a module is created when the module definition
2939is read in; normally, module name spaces also last until the
2940interpreter quits. The statements executed by the top-level
2941invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002942interactively, are considered part of a module called
2943\module{__main__}, so they have their own global name space. (The
2944built-in names actually also live in a module; this is called
2945\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002946
2947The local name space for a function is created when the function is
2948called, and deleted when the function returns or raises an exception
2949that is not handled within the function. (Actually, forgetting would
2950be a better way to describe what actually happens.) Of course,
2951recursive invocations each have their own local name space.
2952
Fred Drakeeee08cd1997-12-04 15:43:15 +00002953A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002954is directly accessible. ``Directly accessible'' here means that an
2955unqualified reference to a name attempts to find the name in the name
2956space.
2957
2958Although scopes are determined statically, they are used dynamically.
2959At any time during execution, exactly three nested scopes are in use
2960(i.e., exactly three name spaces are directly accessible): the
2961innermost scope, which is searched first, contains the local names,
2962the middle scope, searched next, contains the current module's global
2963names, and the outermost scope (searched last) is the name space
2964containing built-in names.
2965
2966Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00002967current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002968the same name space as the global scope: the module's name space.
2969Class definitions place yet another name space in the local scope.
2970
2971It is important to realize that scopes are determined textually: the
2972global scope of a function defined in a module is that module's name
2973space, no matter from where or by what alias the function is called.
2974On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00002975run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002976static name resolution, at ``compile'' time, so don't rely on dynamic
2977name resolution! (In fact, local variables are already determined
2978statically.)
2979
2980A special quirk of Python is that assignments always go into the
2981innermost scope. Assignments do not copy data --- they just
2982bind names to objects. The same is true for deletions: the statement
Fred Drake391564f1998-04-01 23:11:56 +00002983\samp{del x} removes the binding of \code{x} from the name space
2984referenced by the local scope. In fact, all operations that introduce
2985new names use the local scope: in particular, import statements and
2986function definitions bind the module or function name in the local
2987scope. (The \keyword{global} statement can be used to indicate that
2988particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002989
2990
Fred Drakeb7833d31998-09-11 16:21:55 +00002991\section{A First Look at Classes \label{firstClasses}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002992
2993Classes introduce a little bit of new syntax, three new object types,
2994and some new semantics.
2995
2996
Fred Drakeb7833d31998-09-11 16:21:55 +00002997\subsection{Class Definition Syntax \label{classDefinition}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002998
2999The simplest form of class definition looks like this:
3000
3001\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003002class ClassName:
3003 <statement-1>
3004 .
3005 .
3006 .
3007 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003008\end{verbatim}
3009
Fred Drake8842e861998-02-13 07:16:30 +00003010Class definitions, like function definitions (\keyword{def}
3011statements) must be executed before they have any effect. (You could
3012conceivably place a class definition in a branch of an \keyword{if}
3013statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003014
3015In practice, the statements inside a class definition will usually be
3016function definitions, but other statements are allowed, and sometimes
3017useful --- we'll come back to this later. The function definitions
3018inside a class normally have a peculiar form of argument list,
3019dictated by the calling conventions for methods --- again, this is
3020explained later.
3021
3022When a class definition is entered, a new name space is created, and
3023used as the local scope --- thus, all assignments to local variables
3024go into this new name space. In particular, function definitions bind
3025the name of the new function here.
3026
Fred Drakeeee08cd1997-12-04 15:43:15 +00003027When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003028object} is created. This is basically a wrapper around the contents
3029of the name space created by the class definition; we'll learn more
3030about class objects in the next section. The original local scope
3031(the one in effect just before the class definitions was entered) is
Fred Drakea594baf1998-04-03 05:16:31 +00003032reinstated, and the class object is bound here to the class name given
3033in the class definition header (\class{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003034
3035
Fred Drakeb7833d31998-09-11 16:21:55 +00003036\subsection{Class Objects \label{classObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003037
3038Class objects support two kinds of operations: attribute references
3039and instantiation.
3040
Fred Drakeeee08cd1997-12-04 15:43:15 +00003041\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00003042attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003043names are all the names that were in the class's name space when the
3044class object was created. So, if the class definition looked like
3045this:
3046
3047\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003048class MyClass:
3049 "A simple example class"
3050 i = 12345
3051 def f(x):
3052 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003053\end{verbatim}
3054
Fred Drake8842e861998-02-13 07:16:30 +00003055then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003056references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00003057Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00003058of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00003059attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00003060the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003061
Fred Drakeeee08cd1997-12-04 15:43:15 +00003062Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003063the class object is a parameterless function that returns a new
3064instance of the class. For example, (assuming the above class):
3065
3066\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003067x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003068\end{verbatim}
3069
Fred Drakeeee08cd1997-12-04 15:43:15 +00003070creates a new \emph{instance} of the class and assigns this object to
3071the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003072
3073
Fred Drakeb7833d31998-09-11 16:21:55 +00003074\subsection{Instance Objects \label{instanceObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003075
3076Now what can we do with instance objects? The only operations
3077understood by instance objects are attribute references. There are
3078two kinds of valid attribute names.
3079
Fred Drakeeee08cd1997-12-04 15:43:15 +00003080The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00003081``instance variables'' in Smalltalk, and to ``data members'' in
3082\Cpp{}. Data attributes need not be declared; like local variables,
3083they spring into existence when they are first assigned to. For
3084example, if \code{x} is the instance of \class{MyClass} created above,
3085the following piece of code will print the value \code{16}, without
3086leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003087
3088\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003089x.counter = 1
3090while x.counter < 10:
3091 x.counter = x.counter * 2
3092print x.counter
3093del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003094\end{verbatim}
3095
3096The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00003097are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003098object. (In Python, the term method is not unique to class instances:
3099other object types can have methods as well, e.g., list objects have
3100methods called append, insert, remove, sort, and so on. However,
3101below, we'll use the term method exclusively to mean methods of class
3102instance objects, unless explicitly stated otherwise.)
3103
3104Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00003105definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003106objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00003107example, \code{x.f} is a valid method reference, since
3108\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00003109\code{MyClass.i} is not. But \code{x.f} is not the same thing as
3110\code{MyClass.f} --- it is a \emph{method object}, not a function
Fred Drakea594baf1998-04-03 05:16:31 +00003111object.%
3112\obindex{method}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003113
3114
Fred Drakeb7833d31998-09-11 16:21:55 +00003115\subsection{Method Objects \label{methodObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003116
3117Usually, a method is called immediately, e.g.:
3118
3119\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003120x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003121\end{verbatim}
3122
Fred Drake8842e861998-02-13 07:16:30 +00003123In our example, this will return the string \code{'hello world'}.
3124However, it is not necessary to call a method right away: \code{x.f}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003125is a method object, and can be stored away and called at a later
3126moment, for example:
3127
3128\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003129xf = x.f
3130while 1:
3131 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003132\end{verbatim}
3133
Fred Drake8842e861998-02-13 07:16:30 +00003134will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003135
3136What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00003137that \code{x.f()} was called without an argument above, even though
3138the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003139happened to the argument? Surely Python raises an exception when a
3140function that requires an argument is called without any --- even if
3141the argument isn't actually used...
3142
3143Actually, you may have guessed the answer: the special thing about
3144methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00003145function. In our example, the call \code{x.f()} is exactly equivalent
3146to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00003147\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003148with an argument list that is created by inserting the method's object
3149before the first argument.
3150
3151If you still don't understand how methods work, a look at the
3152implementation can perhaps clarify matters. When an instance
3153attribute is referenced that isn't a data attribute, its class is
3154searched. If the name denotes a valid class attribute that is a
3155function object, a method object is created by packing (pointers to)
3156the instance object and the function object just found together in an
3157abstract object: this is the method object. When the method object is
3158called with an argument list, it is unpacked again, a new argument
3159list is constructed from the instance object and the original argument
3160list, and the function object is called with this new argument list.
3161
3162
Fred Drakeb7833d31998-09-11 16:21:55 +00003163\section{Random Remarks \label{remarks}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003164
3165[These should perhaps be placed more carefully...]
3166
3167
3168Data attributes override method attributes with the same name; to
3169avoid accidental name conflicts, which may cause hard-to-find bugs in
3170large programs, it is wise to use some kind of convention that
3171minimizes the chance of conflicts, e.g., capitalize method names,
3172prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00003173an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003174
3175
3176Data attributes may be referenced by methods as well as by ordinary
3177users (``clients'') of an object. In other words, classes are not
3178usable to implement pure abstract data types. In fact, nothing in
3179Python makes it possible to enforce data hiding --- it is all based
3180upon convention. (On the other hand, the Python implementation,
Fred Drake3f205921998-01-13 18:56:38 +00003181written in \C{}, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003182access to an object if necessary; this can be used by extensions to
Fred Drake3f205921998-01-13 18:56:38 +00003183Python written in \C{}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003184
3185
3186Clients should use data attributes with care --- clients may mess up
3187invariants maintained by the methods by stamping on their data
3188attributes. Note that clients may add data attributes of their own to
3189an instance object without affecting the validity of the methods, as
3190long as name conflicts are avoided --- again, a naming convention can
3191save a lot of headaches here.
3192
3193
3194There is no shorthand for referencing data attributes (or other
3195methods!) from within methods. I find that this actually increases
3196the readability of methods: there is no chance of confusing local
3197variables and instance variables when glancing through a method.
3198
3199
3200Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00003201\code{self}. This is nothing more than a convention: the name
3202\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003203however, that by not following the convention your code may be less
3204readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00003205a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003206convention.)
3207
3208
3209Any function object that is a class attribute defines a method for
3210instances of that class. It is not necessary that the function
3211definition is textually enclosed in the class definition: assigning a
3212function object to a local variable in the class is also ok. For
3213example:
3214
3215\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003216# Function defined outside the class
3217def f1(self, x, y):
3218 return min(x, x+y)
3219
3220class C:
3221 f = f1
3222 def g(self):
3223 return 'hello world'
3224 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003225\end{verbatim}
3226
Fred Drake8842e861998-02-13 07:16:30 +00003227Now \code{f}, \code{g} and \code{h} are all attributes of class
3228\class{C} that refer to function objects, and consequently they are all
3229methods of instances of \class{C} --- \code{h} being exactly equivalent
3230to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003231the reader of a program.
3232
3233
3234Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00003235\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003236
3237\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003238class Bag:
3239 def empty(self):
3240 self.data = []
3241 def add(self, x):
3242 self.data.append(x)
3243 def addtwice(self, x):
3244 self.add(x)
3245 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003246\end{verbatim}
3247
3248
3249The instantiation operation (``calling'' a class object) creates an
3250empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00003251state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00003252\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003253
Guido van Rossum6938f061994-08-01 12:22:53 +00003254\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003255 def __init__(self):
3256 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00003257\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003258
Fred Drake8842e861998-02-13 07:16:30 +00003259When a class defines an \method{__init__()} method, class
3260instantiation automatically invokes \method{__init__()} for the
3261newly-created class instance. So in the \class{Bag} example, a new
3262and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003263
Guido van Rossum6938f061994-08-01 12:22:53 +00003264\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003265x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00003266\end{verbatim}
3267
Fred Drake8842e861998-02-13 07:16:30 +00003268Of course, the \method{__init__()} method may have arguments for
3269greater flexibility. In that case, arguments given to the class
3270instantiation operator are passed on to \method{__init__()}. For
3271example,
Guido van Rossum6938f061994-08-01 12:22:53 +00003272
Fred Drake8842e861998-02-13 07:16:30 +00003273\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00003274>>> class Complex:
3275... def __init__(self, realpart, imagpart):
3276... self.r = realpart
3277... self.i = imagpart
3278...
3279>>> x = Complex(3.0,-4.5)
3280>>> x.r, x.i
3281(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00003282\end{verbatim}
3283
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003284Methods may reference global names in the same way as ordinary
3285functions. The global scope associated with a method is the module
3286containing the class definition. (The class itself is never used as a
3287global scope!) While one rarely encounters a good reason for using
3288global data in a method, there are many legitimate uses of the global
3289scope: for one thing, functions and modules imported into the global
3290scope can be used by methods, as well as functions and classes defined
3291in it. Usually, the class containing the method is itself defined in
3292this global scope, and in the next section we'll find some good
3293reasons why a method would want to reference its own class!
3294
3295
Fred Drakeb7833d31998-09-11 16:21:55 +00003296\section{Inheritance \label{inheritance}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003297
3298Of course, a language feature would not be worthy of the name ``class''
3299without supporting inheritance. The syntax for a derived class
3300definition looks as follows:
3301
3302\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003303class DerivedClassName(BaseClassName):
3304 <statement-1>
3305 .
3306 .
3307 .
3308 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003309\end{verbatim}
3310
Fred Drake8842e861998-02-13 07:16:30 +00003311The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003312the derived class definition. Instead of a base class name, an
3313expression is also allowed. This is useful when the base class is
3314defined in another module, e.g.,
3315
3316\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003317class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003318\end{verbatim}
3319
3320Execution of a derived class definition proceeds the same as for a
3321base class. When the class object is constructed, the base class is
3322remembered. This is used for resolving attribute references: if a
3323requested attribute is not found in the class, it is searched in the
3324base class. This rule is applied recursively if the base class itself
3325is derived from some other class.
3326
3327There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00003328\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003329references are resolved as follows: the corresponding class attribute
3330is searched, descending down the chain of base classes if necessary,
3331and the method reference is valid if this yields a function object.
3332
3333Derived classes may override methods of their base classes. Because
3334methods have no special privileges when calling other methods of the
3335same object, a method of a base class that calls another method
3336defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003337a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003338in Python are ``virtual functions''.)
3339
3340An overriding method in a derived class may in fact want to extend
3341rather than simply replace the base class method of the same name.
3342There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003343call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003344occasionally useful to clients as well. (Note that this only works if
3345the base class is defined or imported directly in the global scope.)
3346
3347
Fred Drakeb7833d31998-09-11 16:21:55 +00003348\subsection{Multiple Inheritance \label{multiple}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003349
Guido van Rossum6938f061994-08-01 12:22:53 +00003350Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003351class definition with multiple base classes looks as follows:
3352
3353\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003354class DerivedClassName(Base1, Base2, Base3):
3355 <statement-1>
3356 .
3357 .
3358 .
3359 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003360\end{verbatim}
3361
3362The only rule necessary to explain the semantics is the resolution
3363rule used for class attribute references. This is depth-first,
3364left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003365\class{DerivedClassName}, it is searched in \class{Base1}, then
3366(recursively) in the base classes of \class{Base1}, and only if it is
3367not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003368
Fred Drake8842e861998-02-13 07:16:30 +00003369(To some people breadth first --- searching \class{Base2} and
3370\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003371natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003372attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003373one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003374a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003375rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003376\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003377
3378It is clear that indiscriminate use of multiple inheritance is a
3379maintenance nightmare, given the reliance in Python on conventions to
3380avoid accidental name conflicts. A well-known problem with multiple
3381inheritance is a class derived from two classes that happen to have a
3382common base class. While it is easy enough to figure out what happens
3383in this case (the instance will have a single copy of ``instance
3384variables'' or data attributes used by the common base class), it is
3385not clear that these semantics are in any way useful.
3386
3387
Fred Drakeb7833d31998-09-11 16:21:55 +00003388\section{Private Variables \label{private}}
Guido van Rossum02455691997-07-17 16:21:52 +00003389
Fred Drakea594baf1998-04-03 05:16:31 +00003390There is limited support for class-private
Guido van Rossum02455691997-07-17 16:21:52 +00003391identifiers. Any identifier of the form \code{__spam} (at least two
3392leading underscores, at most one trailing underscore) is now textually
3393replaced with \code{_classname__spam}, where \code{classname} is the
3394current class name with leading underscore(s) stripped. This mangling
3395is done without regard of the syntactic position of the identifier, so
3396it can be used to define class-private instance and class variables,
3397methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003398private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003399may occur when the mangled name would be longer than 255 characters.
3400Outside classes, or when the class name consists of only underscores,
3401no mangling occurs.
3402
3403Name mangling is intended to give classes an easy way to define
3404``private'' instance variables and methods, without having to worry
3405about instance variables defined by derived classes, or mucking with
3406instance variables by code outside the class. Note that the mangling
3407rules are designed mostly to avoid accidents; it still is possible for
3408a determined soul to access or modify a variable that is considered
3409private. This can even be useful, e.g. for the debugger, and that's
3410one reason why this loophole is not closed. (Buglet: derivation of a
3411class with the same name as the base class makes use of private
3412variables of the base class possible.)
3413
3414Notice that code passed to \code{exec}, \code{eval()} or
3415\code{evalfile()} does not consider the classname of the invoking
3416class to be the current class; this is similar to the effect of the
3417\code{global} statement, the effect of which is likewise restricted to
3418code that is byte-compiled together. The same restriction applies to
3419\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3420when referencing \code{__dict__} directly.
3421
3422Here's an example of a class that implements its own
3423\code{__getattr__} and \code{__setattr__} methods and stores all
3424attributes in a private variable, in a way that works in Python 1.4 as
3425well as in previous versions:
3426
3427\begin{verbatim}
3428class VirtualAttributes:
3429 __vdict = None
3430 __vdict_name = locals().keys()[0]
3431
3432 def __init__(self):
3433 self.__dict__[self.__vdict_name] = {}
3434
3435 def __getattr__(self, name):
3436 return self.__vdict[name]
3437
3438 def __setattr__(self, name, value):
3439 self.__vdict[name] = value
3440\end{verbatim}
3441
Fred Drakeaf8a0151998-01-14 14:51:31 +00003442%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003443%potential problems, refrain from using identifiers starting with
3444%double underscore except for predefined uses like \code{__init__}. To
3445%use private names while maintaining future compatibility: refrain from
3446%using the same private name in classes related via subclassing; avoid
3447%explicit (manual) mangling/unmangling; and assume that at some point
3448%in the future, leading double underscore will revert to being just a
3449%naming convention. Discussion on extensive compile-time declarations
3450%are currently underway, and it is impossible to predict what solution
3451%will eventually be chosen for private names. Double leading
3452%underscore is still a candidate, of course --- just not the only one.
3453%It is placed in the distribution in the belief that it is useful, and
3454%so that widespread experience with its use can be gained. It will not
3455%be removed without providing a better solution and a migration path.
3456
Fred Drakeb7833d31998-09-11 16:21:55 +00003457\section{Odds and Ends \label{odds}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003458
3459Sometimes it is useful to have a data type similar to the Pascal
Fred Drake3f205921998-01-13 18:56:38 +00003460``record'' or \C{} ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003461items. An empty class definition will do nicely, e.g.:
3462
3463\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003464class Employee:
3465 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003466
Fred Drake8842e861998-02-13 07:16:30 +00003467john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003468
Fred Drake8842e861998-02-13 07:16:30 +00003469# Fill the fields of the record
3470john.name = 'John Doe'
3471john.dept = 'computer lab'
3472john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003473\end{verbatim}
3474
3475
3476A piece of Python code that expects a particular abstract data type
3477can often be passed a class that emulates the methods of that data
3478type instead. For instance, if you have a function that formats some
3479data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003480\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00003481buffer instead, and pass it as an argument.% (Unfortunately, this
3482%technique has its limitations: a class can't define operations that
3483%are accessed by special syntax such as sequence subscripting or
3484%arithmetic operators, and assigning such a ``pseudo-file'' to
3485%\code{sys.stdin} will not cause the interpreter to read further input
3486%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003487
3488
Fred Drake8842e861998-02-13 07:16:30 +00003489Instance method objects have attributes, too: \code{m.im_self} is the
3490object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003491function object corresponding to the method.
3492
Fred Drakeb7833d31998-09-11 16:21:55 +00003493\subsection{Exceptions Can Be Classes \label{exceptionClasses}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003494
3495User-defined exceptions are no longer limited to being string objects
3496--- they can be identified by classes as well. Using this mechanism it
3497is possible to create extensible hierarchies of exceptions.
3498
3499There are two new valid (semantic) forms for the raise statement:
3500
3501\begin{verbatim}
3502raise Class, instance
3503
3504raise instance
3505\end{verbatim}
3506
Fred Drake8842e861998-02-13 07:16:30 +00003507In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003508or of a class derived from it. The second form is a shorthand for
3509
3510\begin{verbatim}
3511raise instance.__class__, instance
3512\end{verbatim}
3513
3514An except clause may list classes as well as string objects. A class
3515in an except clause is compatible with an exception if it is the same
3516class or a base class thereof (but not the other way around --- an
3517except clause listing a derived class is not compatible with a base
3518class). For example, the following code will print B, C, D in that
3519order:
3520
3521\begin{verbatim}
3522class B:
3523 pass
3524class C(B):
3525 pass
3526class D(C):
3527 pass
3528
3529for c in [B, C, D]:
3530 try:
3531 raise c()
3532 except D:
3533 print "D"
3534 except C:
3535 print "C"
3536 except B:
3537 print "B"
3538\end{verbatim}
3539
Fred Drake8842e861998-02-13 07:16:30 +00003540Note that if the except clauses were reversed (with \samp{except B}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003541first), it would have printed B, B, B --- the first matching except
3542clause is triggered.
3543
3544When an error message is printed for an unhandled exception which is a
3545class, the class name is printed, then a colon and a space, and
3546finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003547\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003548
Guido van Rossum194e57c1995-02-15 15:51:38 +00003549
Fred Drakeb7833d31998-09-11 16:21:55 +00003550\chapter{What Now? \label{whatNow}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003551
Guido van Rossum02455691997-07-17 16:21:52 +00003552Hopefully reading this tutorial has reinforced your interest in using
3553Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003554
Guido van Rossum02455691997-07-17 16:21:52 +00003555You should read, or at least page through, the Library Reference,
3556which gives complete (though terse) reference material about types,
3557functions, and modules that can save you a lot of time when writing
3558Python programs. The standard Python distribution includes a
Fred Drake3f205921998-01-13 18:56:38 +00003559\emph{lot} of code in both \C{} and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003560\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3561numbers, parse command-line options, write CGI programs, compress
3562data, and a lot more; skimming through the Library Reference will give
3563you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003564
Fred Drakeca6567f1998-01-22 20:44:18 +00003565The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003566code, documentation, and pointers to Python-related pages around the
Fred Drake391564f1998-04-01 23:11:56 +00003567Web. This web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00003568world, such as Europe, Japan, and Australia; a mirror may be faster
3569than the main site, depending on your geographical location. A more
Fred Drakeca6567f1998-01-22 20:44:18 +00003570informal site is \url{http://starship.skyport.net}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003571bunch of Python-related personal home pages; many people have
3572downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003573
Guido van Rossum02455691997-07-17 16:21:52 +00003574For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00003575newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
3576list at \email{python-list@cwi.nl}. The newsgroup and mailing list
3577are gatewayed, so messages posted to one will automatically be
3578forwarded to the other. There are around 35--45 postings a day,
3579% Postings figure based on average of last six months activity as
3580% reported by www.findmail.com; Oct. '97 - Mar. '98: 7480 msgs / 182
3581% days = 41.1 msgs / day.
3582asking (and answering) questions, suggesting new features, and
3583announcing new modules. Before posting, be sure to check the list of
3584Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003585\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3586\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003587answers many of the questions that come up again and again, and may
3588already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003589
Guido van Rossum02455691997-07-17 16:21:52 +00003590You can support the Python community by joining the Python Software
3591Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003592organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003593information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003594
Guido van Rossum194e57c1995-02-15 15:51:38 +00003595
Fred Drakea594baf1998-04-03 05:16:31 +00003596\appendix
Guido van Rossum194e57c1995-02-15 15:51:38 +00003597
Fred Drakeb7833d31998-09-11 16:21:55 +00003598\chapter{Interactive Input Editing and History Substitution
3599 \label{interacting}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003600
Guido van Rossum02455691997-07-17 16:21:52 +00003601Some versions of the Python interpreter support editing of the current
3602input line and history substitution, similar to facilities found in
3603the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003604\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003605editing. This library has its own documentation which I won't
Fred Drakecc09e8d1998-12-28 21:21:36 +00003606duplicate here; however, the basics are easily explained. The
3607interactive editing and history described here are optionally
3608available in the \UNIX{} and CygWin versions of the interpreter.
3609
3610This chapter does \emph{not} document the editing facilities of Mark
3611Hammond's PythonWin package or the Tk-based environment, IDLE,
3612distributed with Python. The command line history recall which
3613operates within DOS boxes on NT and some other DOS and Windows flavors
3614is yet another beast.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003615
Fred Drakeb7833d31998-09-11 16:21:55 +00003616\section{Line Editing \label{lineEditing}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003617
Guido van Rossum02455691997-07-17 16:21:52 +00003618If supported, input line editing is active whenever the interpreter
3619prints a primary or secondary prompt. The current line can be edited
3620using the conventional Emacs control characters. The most important
3621of these are: C-A (Control-A) moves the cursor to the beginning of the
3622line, C-E to the end, C-B moves it one position to the left, C-F to
3623the right. Backspace erases the character to the left of the cursor,
3624C-D the character to its right. C-K kills (erases) the rest of the
3625line to the right of the cursor, C-Y yanks back the last killed
3626string. C-underscore undoes the last change you made; it can be
3627repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003628
Fred Drakeb7833d31998-09-11 16:21:55 +00003629\section{History Substitution \label{history}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003630
Guido van Rossum02455691997-07-17 16:21:52 +00003631History substitution works as follows. All non-empty input lines
3632issued are saved in a history buffer, and when a new prompt is given
3633you are positioned on a new line at the bottom of this buffer. C-P
3634moves one line up (back) in the history buffer, C-N moves one down.
3635Any line in the history buffer can be edited; an asterisk appears in
3636front of the prompt to mark a line as modified. Pressing the Return
3637key passes the current line to the interpreter. C-R starts an
3638incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003639
Fred Drakeb7833d31998-09-11 16:21:55 +00003640\section{Key Bindings \label{keyBindings}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003641
Guido van Rossum02455691997-07-17 16:21:52 +00003642The key bindings and some other parameters of the Readline library can
3643be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003644\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003645
Fred Drake8842e861998-02-13 07:16:30 +00003646\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003647key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003648\end{verbatim}
3649
Guido van Rossum02455691997-07-17 16:21:52 +00003650or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003651
Fred Drake8842e861998-02-13 07:16:30 +00003652\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003653"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003654\end{verbatim}
3655
Guido van Rossum02455691997-07-17 16:21:52 +00003656and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003657
Fred Drake8842e861998-02-13 07:16:30 +00003658\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003659set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003660\end{verbatim}
3661
Guido van Rossum02455691997-07-17 16:21:52 +00003662For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003663
Fred Drake8842e861998-02-13 07:16:30 +00003664\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003665# I prefer vi-style editing:
3666set editing-mode vi
3667# Edit using a single line:
3668set horizontal-scroll-mode On
3669# Rebind some keys:
3670Meta-h: backward-kill-word
3671"\C-u": universal-argument
3672"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003673\end{verbatim}
3674
Guido van Rossum02455691997-07-17 16:21:52 +00003675Note that the default binding for TAB in Python is to insert a TAB
3676instead of Readline's default filename completion function. If you
3677insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003678
Fred Drake8842e861998-02-13 07:16:30 +00003679\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003680TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003681\end{verbatim}
3682
Fred Drakeeee08cd1997-12-04 15:43:15 +00003683in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003684indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003685
Fred Drake72389881998-04-13 01:31:10 +00003686Automatic completion of variable and module names is optionally
3687available. To enable it in the interpreter's interactive mode, add
3688the following to your \file{\$HOME/.pythonrc} file:% $ <- bow to font-lock
3689\indexii{.pythonrc.py}{file}%
3690\refstmodindex{rlcompleter}%
3691\refbimodindex{readline}
3692
3693\begin{verbatim}
3694import rlcompleter, readline
3695readline.parse_and_bind('tab: complete')
3696\end{verbatim}
3697
3698This binds the TAB key to the completion function, so hitting the TAB
3699key twice suggests completions; it looks at Python statement names,
3700the current local variables, and the available module names. For
3701dotted expressions such as \code{string.a}, it will evaluate the the
3702expression up to the final \character{.} and then suggest completions
3703from the attributes of the resulting object. Note that this may
3704execute application-defined code if an object with a
3705\method{__getattr__()} method is part of the expression.
3706
3707
Fred Drakeb7833d31998-09-11 16:21:55 +00003708\section{Commentary \label{commentary}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003709
Guido van Rossum02455691997-07-17 16:21:52 +00003710This facility is an enormous step forward compared to previous
3711versions of the interpreter; however, some wishes are left: It would
3712be nice if the proper indentation were suggested on continuation lines
3713(the parser knows if an indent token is required next). The
3714completion mechanism might use the interpreter's symbol table. A
3715command to check (or even suggest) matching parentheses, quotes etc.
3716would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003717
Fred Drake8842e861998-02-13 07:16:30 +00003718% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003719
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003720\end{document}
Guido van Rossum02455691997-07-17 16:21:52 +00003721