blob: f52ec61ee7db0d6bc0644be07378198f7f2e59d5 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002
Guido van Rossum02455691997-07-17 16:21:52 +00003% Things to do:
4% Add a section on file I/O
5% Write a chapter entitled ``Some Useful Modules''
6% --regex, math+cmath
7% Should really move the Python startup file info to an appendix
Guido van Rossum02455691997-07-17 16:21:52 +00008
Guido van Rossumdccc2981997-12-30 04:40:25 +00009\title{Python Tutorial}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010
Guido van Rossum16cd7f91994-10-06 10:29:26 +000011\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +000012
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000013\begin{document}
14
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000015\maketitle
16
Fred Drake9f86b661998-07-28 21:55:19 +000017\ifhtml
18\chapter*{Front Matter\label{front}}
19\fi
20
Guido van Rossum16cd7f91994-10-06 10:29:26 +000021\input{copyright}
22
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023\begin{abstract}
24
25\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000026Python is an easy to learn, powerful programming language. It has
27efficient high-level data structures and a simple but effective
28approach to object-oriented programming. Python's elegant syntax and
29dynamic typing, together with its interpreted nature, make it an ideal
30language for scripting and rapid application development in many areas
31on most platforms.
32
33The Python interpreter and the extensive standard library are freely
34available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000035Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000036distributed. The same site also contains distributions of and
37pointers to many free third party Python modules, programs and tools,
38and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000039
Guido van Rossum4410c751991-06-04 20:22:18 +000040The Python interpreter is easily extended with new functions and data
Fred Drakeee84d591999-03-10 17:25:30 +000041types implemented in C or \Cpp{} (or other languages callable from C).
Guido van Rossumdccc2981997-12-30 04:40:25 +000042Python is also suitable as an extension language for customizable
43applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000044
Guido van Rossum6fc178f1991-08-16 09:13:42 +000045This tutorial introduces the reader informally to the basic concepts
46and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000047Python interpreter handy for hands-on experience, but all examples are
48self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000049
Guido van Rossumdccc2981997-12-30 04:40:25 +000050For a description of standard objects and modules, see the
51\emph{Python Library Reference} document. The \emph{Python Reference
52Manual} gives a more formal definition of the language. To write
Fred Drakeee84d591999-03-10 17:25:30 +000053extensions in C or \Cpp{}, read the \emph{Extending and Embedding} and
54\emph{Python/C API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000055Python in depth.
56
57This tutorial does not attempt to be comprehensive and cover every
58single feature, or even every commonly used feature. Instead, it
59introduces many of Python's most noteworthy features, and will give
60you a good idea of the language's flavor and style. After reading it,
61you will be able to read and write Python modules and programs, and
62you will be ready to learn more about the various Python library
63modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000064
65\end{abstract}
66
Fred Drake4d4f9e71998-01-13 22:25:02 +000067\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000068
Guido van Rossum5e0759d1992-08-07 16:06:24 +000069
Fred Drakeb7833d31998-09-11 16:21:55 +000070\chapter{Whetting Your Appetite \label{intro}}
Guido van Rossum3a26dd81996-10-24 22:12:48 +000071
Guido van Rossum6fc178f1991-08-16 09:13:42 +000072If you ever wrote a large shell script, you probably know this
73feeling: you'd love to add yet another feature, but it's already so
74slow, and so big, and so complicated; or the feature involves a system
Fred Drakeee84d591999-03-10 17:25:30 +000075call or other function that is only accessible from C \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000076the problem at hand isn't serious enough to warrant rewriting the
Fred Drakeee84d591999-03-10 17:25:30 +000077script in C; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000078other data types (like sorted lists of file names) that are easy in
Fred Drakeee84d591999-03-10 17:25:30 +000079the shell but lots of work to implement in C, or perhaps you're not
80sufficiently familiar with C.
Guido van Rossum02455691997-07-17 16:21:52 +000081
Fred Drakeee84d591999-03-10 17:25:30 +000082Another situation: perhaps you have to work with several C libraries,
83and the usual C write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000084need to develop software more quickly. Possibly perhaps you've
85written a program that could use an extension language, and you don't
86want to design a language, write and debug an interpreter for it, then
87tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000088
Guido van Rossum6fc178f1991-08-16 09:13:42 +000089In such cases, Python may be just the language for you. Python is
90simple to use, but it is a real programming language, offering much
91more structure and support for large programs than the shell has. On
Fred Drakeee84d591999-03-10 17:25:30 +000092the other hand, it also offers much more error checking than C, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000093being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000094built in, such as flexible arrays and dictionaries that would cost you
Fred Drakeee84d591999-03-10 17:25:30 +000095days to implement efficiently in C. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000096types Python is applicable to a much larger problem domain than
97\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
98in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000099
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000100Python allows you to split up your program in modules that can be
101reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000102standard modules that you can use as the basis of your programs --- or
103as examples to start learning to program in Python. There are also
104built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000105sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000106
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000107Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000108during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000109necessary. The interpreter can be used interactively, which makes it
110easy to experiment with features of the language, to write throw-away
111programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000112It is also a handy desk calculator.
113
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000114Python allows writing very compact and readable programs. Programs
Fred Drakeee84d591999-03-10 17:25:30 +0000115written in Python are typically much shorter than equivalent C
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000116programs, for several reasons:
117\begin{itemize}
118\item
119the high-level data types allow you to express complex operations in a
120single statement;
121\item
122statement grouping is done by indentation instead of begin/end
123brackets;
124\item
125no variable or argument declarations are necessary.
126\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000127
Fred Drakeee84d591999-03-10 17:25:30 +0000128Python is \emph{extensible}: if you know how to program in C it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000129to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000130perform critical operations at maximum speed, or to link Python
131programs to libraries that may only be available in binary form (such
132as a vendor-specific graphics library). Once you are really hooked,
Fred Drakeee84d591999-03-10 17:25:30 +0000133you can link the Python interpreter into an application written in C
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000134and use it as an extension or command language for that application.
135
Guido van Rossum02455691997-07-17 16:21:52 +0000136By the way, the language is named after the BBC show ``Monty Python's
137Flying Circus'' and has nothing to do with nasty reptiles. Making
138references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000139it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000140
Fred Drakeb7833d31998-09-11 16:21:55 +0000141\section{Where From Here \label{where}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000142
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000143Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000144in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000145using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000146
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000147In the next chapter, the mechanics of using the interpreter are
148explained. This is rather mundane information, but essential for
149trying out the examples shown later.
150
Guido van Rossum4410c751991-06-04 20:22:18 +0000151The rest of the tutorial introduces various features of the Python
Fred Drakef64f8a01999-06-10 15:30:21 +0000152language and system through examples, beginning with simple
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000153expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000154and finally touching upon advanced concepts like exceptions
155and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000156
Fred Drakeb7833d31998-09-11 16:21:55 +0000157\chapter{Using the Python Interpreter \label{using}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000158
Fred Drakeb7833d31998-09-11 16:21:55 +0000159\section{Invoking the Interpreter \label{invoking}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000160
Fred Drakeeee08cd1997-12-04 15:43:15 +0000161The Python interpreter is usually installed as \file{/usr/local/bin/python}
162on those machines where it is available; putting \file{/usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000163your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000164typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000165
Fred Drake8842e861998-02-13 07:16:30 +0000166\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000167python
Fred Drake8842e861998-02-13 07:16:30 +0000168\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000169
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000170to the shell. Since the choice of the directory where the interpreter
171lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000172your local Python guru or system administrator. (E.g.,
173\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000174
Guido van Rossuma8a1b9b1998-06-22 14:28:39 +0000175Typing an EOF character (Control-D on \UNIX{}, Control-Z on DOS
Guido van Rossum02455691997-07-17 16:21:52 +0000176or Windows) at the primary prompt causes the interpreter to exit with
177a zero exit status. If that doesn't work, you can exit the
Fred Drake8842e861998-02-13 07:16:30 +0000178interpreter by typing the following commands: \samp{import sys;
Guido van Rossum02455691997-07-17 16:21:52 +0000179sys.exit()}.
180
181The interpreter's line-editing features usually aren't very
Fred Drake3f205921998-01-13 18:56:38 +0000182sophisticated. On \UNIX{}, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000183enabled support for the GNU readline library, which adds more
184elaborate interactive editing and history features. Perhaps the
185quickest check to see whether command line editing is supported is
186typing Control-P to the first Python prompt you get. If it beeps, you
187have command line editing; see Appendix A for an introduction to the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000188keys. If nothing appears to happen, or if \code{\^P} is echoed,
Guido van Rossum02455691997-07-17 16:21:52 +0000189command line editing isn't available; you'll only be able to use
190backspace to remove characters from the current line.
191
Fred Drake6dc2aae1996-12-13 21:56:03 +0000192The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000193with standard input connected to a tty device, it reads and executes
194commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000195a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000196that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000197
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000198A third way of starting the interpreter is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000199\samp{python -c command [arg] ...}, which
200executes the statement(s) in \code{command}, analogous to the shell's
201\code{-c} option. Since Python statements often contain spaces or other
202characters that are special to the shell, it is best to quote
203\code{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000204
Fred Drakeeee08cd1997-12-04 15:43:15 +0000205Note that there is a difference between \samp{python file} and
206\samp{python <file}. In the latter case, input requests from the
207program, such as calls to \code{input()} and \code{raw_input()}, are
208satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000209until the end by the parser before the program starts executing, the
210program will encounter EOF immediately. In the former case (which is
211usually what you want) they are satisfied from whatever file or device
212is connected to standard input of the Python interpreter.
213
Guido van Rossumb2c65561993-05-12 08:53:36 +0000214When a script file is used, it is sometimes useful to be able to run
215the script and enter interactive mode afterwards. This can be done by
Fred Drakeeee08cd1997-12-04 15:43:15 +0000216passing \code{-i} before the script. (This does not work if the script
Guido van Rossumb2c65561993-05-12 08:53:36 +0000217is read from standard input, for the same reason as explained in the
218previous paragraph.)
219
Fred Drakeb7833d31998-09-11 16:21:55 +0000220\subsection{Argument Passing \label{argPassing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000221
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000222When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000223arguments thereafter are passed to the script in the variable
224\code{sys.argv}, which is a list of strings. Its length is at least
225one; when no script and no arguments are given, \code{sys.argv[0]} is
226an empty string. When the script name is given as \code{'-'} (meaning
227standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c
228command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options
229found after \code{-c command} are not consumed by the Python
230interpreter's option processing but left in \code{sys.argv} for the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000231command to handle.
232
Fred Drakeb7833d31998-09-11 16:21:55 +0000233\subsection{Interactive Mode \label{interactive}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000234
Guido van Rossumdd010801991-06-07 14:31:11 +0000235When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000236\emph{interactive mode}. In this mode it prompts for the next command
237with the \emph{primary prompt}, usually three greater-than signs
Fred Drake8842e861998-02-13 07:16:30 +0000238(\samp{>>> }); for continuation lines it prompts with the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000239\emph{secondary prompt},
Fred Drake8842e861998-02-13 07:16:30 +0000240by default three dots (\samp{... }).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000241
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000242The interpreter prints a welcome message stating its version number
243and a copyright notice before printing the first prompt, e.g.:
244
Fred Drake8842e861998-02-13 07:16:30 +0000245\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000246python
Fred Drakeee84d591999-03-10 17:25:30 +0000247Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Fred Drakeeee08cd1997-12-04 15:43:15 +0000248Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000249>>>
Fred Drake8842e861998-02-13 07:16:30 +0000250\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000251
Fred Drakeb7833d31998-09-11 16:21:55 +0000252\section{The Interpreter and Its Environment \label{interp}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000253
Fred Drakeb7833d31998-09-11 16:21:55 +0000254\subsection{Error Handling \label{error}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000255
256When an error occurs, the interpreter prints an error
257message and a stack trace. In interactive mode, it then returns to
258the primary prompt; when input came from a file, it exits with a
259nonzero exit status after printing
Fred Drakeeee08cd1997-12-04 15:43:15 +0000260the stack trace. (Exceptions handled by an \code{except} clause in a
261\code{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000262unconditionally fatal and cause an exit with a nonzero exit; this
263applies to internal inconsistencies and some cases of running out of
264memory. All error messages are written to the standard error stream;
265normal output from the executed commands is written to standard
266output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000267
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000268Typing the interrupt character (usually Control-C or DEL) to the
269primary or secondary prompt cancels the input and returns to the
Fred Drake93aa0f21999-04-05 21:39:17 +0000270primary prompt.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000271 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000272}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000273Typing an interrupt while a command is executing raises the
274\code{KeyboardInterrupt} exception, which may be handled by a
275\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000276
Fred Drakeb7833d31998-09-11 16:21:55 +0000277\subsection{Executable Python Scripts \label{scripts}}
Guido van Rossum4410c751991-06-04 20:22:18 +0000278
Fred Drake6dc2aae1996-12-13 21:56:03 +0000279On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000280executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000281
Fred Drake8842e861998-02-13 07:16:30 +0000282\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000283#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000284\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000285
Fred Drake391564f1998-04-01 23:11:56 +0000286(assuming that the interpreter is on the user's \envvar{PATH}) at the
287beginning of the script and giving the file an executable mode. The
Fred Drakebdadf0f1999-04-29 13:20:25 +0000288\samp{\#!} must be the first two characters of the file. Note that
289the hash, or pound, character, \character{\#}, is used to start a
290comment in Python.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000291
Fred Drakeb7833d31998-09-11 16:21:55 +0000292\subsection{The Interactive Startup File \label{startup}}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000293
Fred Drake8842e861998-02-13 07:16:30 +0000294% XXX This should probably be dumped in an appendix, since most people
295% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000296
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000297When you use Python interactively, it is frequently handy to have some
298standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000299can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000300\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drakeeee08cd1997-12-04 15:43:15 +0000301commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000302shells.
303
304This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000305commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000306explicit source of commands (which otherwise behaves like an
307interactive session). It is executed in the same name space where
308interactive commands are executed, so that objects that it defines or
309imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000310You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000311this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000312
313If you want to read an additional start-up file from the current
Fred Drake72389881998-04-13 01:31:10 +0000314directory, you can program this in the global start-up file,
Fred Drakeee84d591999-03-10 17:25:30 +0000315e.g.\ \samp{execfile('.pythonrc.py')}\indexii{.pythonrc.py}{file}. If
Fred Drake72389881998-04-13 01:31:10 +0000316you want to use the startup file in a script, you must do this
317explicitly in the script:
Fred Drake8842e861998-02-13 07:16:30 +0000318
319\begin{verbatim}
320import os
Fred Drakeee84d591999-03-10 17:25:30 +0000321if os.environ.get('PYTHONSTARTUP') \
322 and os.path.isfile(os.environ['PYTHONSTARTUP']):
Fred Drake72389881998-04-13 01:31:10 +0000323 execfile(os.environ['PYTHONSTARTUP'])
Fred Drake8842e861998-02-13 07:16:30 +0000324\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000325
Fred Drake72389881998-04-13 01:31:10 +0000326
Fred Drakeb7833d31998-09-11 16:21:55 +0000327\chapter{An Informal Introduction to Python \label{informal}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000328
329In the following examples, input and output are distinguished by the
Fred Drake8842e861998-02-13 07:16:30 +0000330presence or absence of prompts (\samp{>>> } and \samp{... }): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000331the example, you must type everything after the prompt, when the
332prompt appears; lines that do not begin with a prompt are output from
Fred Drakebdadf0f1999-04-29 13:20:25 +0000333the interpreter. %
Guido van Rossum02455691997-07-17 16:21:52 +0000334%\footnote{
335% I'd prefer to use different fonts to distinguish input
336% from output, but the amount of LaTeX hacking that would require
337% is currently beyond my ability.
338%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000339Note that a secondary prompt on a line by itself in an example means
340you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000341
Fred Drakebdadf0f1999-04-29 13:20:25 +0000342Many of the examples in this manual, even those entered at the
343interactive prompt, include comments. Comments in Python start with
344the hash character, \character{\#}, and extend to the end of the
345physical line. A comment may appear at the start of a line or
346following whitespace or code, but not within a string literal. A hash
347character within a string literal is just a hash character.
348
349Some examples:
350
351\begin{verbatim}
352# this is the first comment
353SPAM = 1 # and this is the second comment
354 # ... and now a third!
355STRING = "# This is not a comment."
356\end{verbatim}
357
358
Fred Drakeb7833d31998-09-11 16:21:55 +0000359\section{Using Python as a Calculator \label{calculator}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000360
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000361Let's try some simple Python commands. Start the interpreter and wait
Fred Drake8842e861998-02-13 07:16:30 +0000362for the primary prompt, \samp{>>> }. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000363
Fred Drakeb7833d31998-09-11 16:21:55 +0000364\subsection{Numbers \label{numbers}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000365
366The interpreter acts as a simple calculator: you can type an
367expression at it and it will write the value. Expression syntax is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000368straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/}
Fred Drakeee84d591999-03-10 17:25:30 +0000369work just like in most other languages (e.g., Pascal or C); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000370can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000371
Fred Drake8842e861998-02-13 07:16:30 +0000372\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000373>>> 2+2
3744
Guido van Rossum6938f061994-08-01 12:22:53 +0000375>>> # This is a comment
376... 2+2
3774
378>>> 2+2 # and a comment on the same line as code
3794
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000380>>> (50-5*6)/4
3815
Guido van Rossum6938f061994-08-01 12:22:53 +0000382>>> # Integer division returns the floor:
383... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003842
Guido van Rossum6938f061994-08-01 12:22:53 +0000385>>> 7/-3
386-3
Fred Drake8842e861998-02-13 07:16:30 +0000387\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000388
Fred Drakeee84d591999-03-10 17:25:30 +0000389Like in C, the equal sign (\character{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000390variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000391
Fred Drake8842e861998-02-13 07:16:30 +0000392\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000393>>> width = 20
394>>> height = 5*9
395>>> width * height
396900
Fred Drake8842e861998-02-13 07:16:30 +0000397\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000398%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000399A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000400
Fred Drake8842e861998-02-13 07:16:30 +0000401\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000402>>> x = y = z = 0 # Zero x, y and z
403>>> x
4040
405>>> y
4060
407>>> z
4080
Fred Drake8842e861998-02-13 07:16:30 +0000409\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000410%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000411There is full support for floating point; operators with mixed type
412operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000413
Fred Drake8842e861998-02-13 07:16:30 +0000414\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000415>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004163.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000417>>> 7.0 / 2
4183.5
Fred Drake8842e861998-02-13 07:16:30 +0000419\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000420%
421Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000422a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
423real component are written as \samp{(\var{real}+\var{imag}j)}, or can
424be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000425
Fred Drake8842e861998-02-13 07:16:30 +0000426\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000427>>> 1j * 1J
428(-1+0j)
429>>> 1j * complex(0,1)
430(-1+0j)
431>>> 3+1j*3
432(3+3j)
433>>> (3+1j)*3
434(9+3j)
435>>> (1+2j)/(1+1j)
436(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000437\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000438%
439Complex numbers are always represented as two floating point numbers,
440the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000441number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000442
Fred Drake8842e861998-02-13 07:16:30 +0000443\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000444>>> a=1.5+0.5j
445>>> a.real
4461.5
447>>> a.imag
4480.5
Fred Drake8842e861998-02-13 07:16:30 +0000449\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000450%
451The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000452(\function{float()}, \function{int()} and \function{long()}) don't
453work for complex numbers --- there is no one correct way to convert a
454complex number to a real number. Use \code{abs(\var{z})} to get its
455magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000456
Fred Drake8842e861998-02-13 07:16:30 +0000457\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000458>>> a=1.5+0.5j
459>>> float(a)
460Traceback (innermost last):
461 File "<stdin>", line 1, in ?
462TypeError: can't convert complex to float; use e.g. abs(z)
463>>> a.real
4641.5
465>>> abs(a)
4661.58113883008
Fred Drake8842e861998-02-13 07:16:30 +0000467\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000468%
469In interactive mode, the last printed expression is assigned to the
470variable \code{_}. This means that when you are using Python as a
471desk calculator, it is somewhat easier to continue calculations, for
472example:
473
474\begin{verbatim}
475>>> tax = 17.5 / 100
476>>> price = 3.50
477>>> price * tax
4780.6125
479>>> price + _
4804.1125
481>>> round(_, 2)
4824.11
483\end{verbatim}
484
485This variable should be treated as read-only by the user. Don't
486explicitly assign a value to it --- you would create an independent
487local variable with the same name masking the built-in variable with
488its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000489
Fred Drakeb7833d31998-09-11 16:21:55 +0000490\subsection{Strings \label{strings}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000491
Guido van Rossum02455691997-07-17 16:21:52 +0000492Besides numbers, Python can also manipulate strings, which can be
493expressed in several ways. They can be enclosed in single quotes or
494double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000495
Fred Drake8842e861998-02-13 07:16:30 +0000496\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000497>>> 'spam eggs'
498'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000499>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000500"doesn't"
501>>> "doesn't"
502"doesn't"
503>>> '"Yes," he said.'
504'"Yes," he said.'
505>>> "\"Yes,\" he said."
506'"Yes," he said.'
507>>> '"Isn\'t," she said.'
508'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000509\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000510
Fred Drake8842e861998-02-13 07:16:30 +0000511String literals can span multiple lines in several ways. Newlines can
512be escaped with backslashes, e.g.:
Guido van Rossum02455691997-07-17 16:21:52 +0000513
514\begin{verbatim}
515hello = "This is a rather long string containing\n\
516several lines of text just as you would do in C.\n\
517 Note that whitespace at the beginning of the line is\
518 significant.\n"
519print hello
520\end{verbatim}
521
522which would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000523
Guido van Rossum02455691997-07-17 16:21:52 +0000524\begin{verbatim}
525This is a rather long string containing
526several lines of text just as you would do in C.
527 Note that whitespace at the beginning of the line is significant.
528\end{verbatim}
529
530Or, strings can be surrounded in a pair of matching triple-quotes:
531\code{"""} or \code {'''}. End of lines do not need to be escaped
532when using triple-quotes, but they will be included in the string.
533
534\begin{verbatim}
535print """
536Usage: thingy [OPTIONS]
537 -h Display this usage message
538 -H hostname Hostname to connect to
539"""
540\end{verbatim}
541
542produces the following output:
543
Fred Drake8842e861998-02-13 07:16:30 +0000544\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000545Usage: thingy [OPTIONS]
546 -h Display this usage message
547 -H hostname Hostname to connect to
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 +0000550The interpreter prints the result of string operations in the same way
551as they are typed for input: inside quotes, and with quotes and other
552funny characters escaped by backslashes, to show the precise
553value. The string is enclosed in double quotes if the string contains
554a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000555quotes. (The \keyword{print} statement, described later, can be used
556to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000557
Fred Drakeeee08cd1997-12-04 15:43:15 +0000558Strings can be concatenated (glued together) with the \code{+}
559operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000560
Fred Drake8842e861998-02-13 07:16:30 +0000561\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000562>>> word = 'Help' + 'A'
563>>> word
564'HelpA'
565>>> '<' + word*5 + '>'
566'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000567\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000568
Guido van Rossum02455691997-07-17 16:21:52 +0000569Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000570the first line above could also have been written \samp{word = 'Help'
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000571'A'}; this only works with two literals, not with arbitrary string
572expressions:
573
574\begin{verbatim}
575>>> 'str' 'ing' # <- This is ok
576'string'
577>>> string.strip('str') + 'ing' # <- This is ok
578'string'
579>>> string.strip('str') 'ing' # <- This is invalid
580 File "<stdin>", line 1
581 string.strip('str') 'ing'
582 ^
583SyntaxError: invalid syntax
584\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000585
Fred Drakeee84d591999-03-10 17:25:30 +0000586Strings can be subscripted (indexed); like in C, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000587of a string has subscript (index) 0. There is no separate character
588type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000589substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000590separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000591
Fred Drake8842e861998-02-13 07:16:30 +0000592\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000593>>> word[4]
594'A'
595>>> word[0:2]
596'He'
597>>> word[2:4]
598'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000599\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000600
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000601Slice indices have useful defaults; an omitted first index defaults to
602zero, an omitted second index defaults to the size of the string being
603sliced.
604
Fred Drake8842e861998-02-13 07:16:30 +0000605\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000606>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000607'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000608>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000609'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000610\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000611
Fred Drakeeee08cd1997-12-04 15:43:15 +0000612Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
613equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000614
Fred Drake8842e861998-02-13 07:16:30 +0000615\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000616>>> word[:2] + word[2:]
617'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000618>>> word[:3] + word[3:]
619'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000620\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000621
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000622Degenerate slice indices are handled gracefully: an index that is too
623large is replaced by the string size, an upper bound smaller than the
624lower bound returns an empty string.
625
Fred Drake8842e861998-02-13 07:16:30 +0000626\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000627>>> word[1:100]
628'elpA'
629>>> word[10:]
630''
631>>> word[2:1]
632''
Fred Drake8842e861998-02-13 07:16:30 +0000633\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000634
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000635Indices may be negative numbers, to start counting from the right.
636For example:
637
Fred Drake8842e861998-02-13 07:16:30 +0000638\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000639>>> word[-1] # The last character
640'A'
641>>> word[-2] # The last-but-one character
642'p'
643>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000644'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000645>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000646'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000647\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000648
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000649But note that -0 is really the same as 0, so it does not count from
650the right!
651
Fred Drake8842e861998-02-13 07:16:30 +0000652\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000653>>> word[-0] # (since -0 equals 0)
654'H'
Fred Drake8842e861998-02-13 07:16:30 +0000655\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000656
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000657Out-of-range negative slice indices are truncated, but don't try this
658for single-element (non-slice) indices:
659
Fred Drake8842e861998-02-13 07:16:30 +0000660\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000661>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000662'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000663>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000664Traceback (innermost last):
665 File "<stdin>", line 1
666IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000667\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000668
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000669The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000670pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000671character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000672string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000673
Fred Drake8842e861998-02-13 07:16:30 +0000674\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000675 +---+---+---+---+---+
676 | H | e | l | p | A |
677 +---+---+---+---+---+
678 0 1 2 3 4 5
679-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000680\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000681
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000682The first row of numbers gives the position of the indices 0...5 in
683the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000684The slice from \var{i} to \var{j} consists of all characters between
685the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000686
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000687For nonnegative indices, the length of a slice is the difference of
688the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000689\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000690
Fred Drake8842e861998-02-13 07:16:30 +0000691The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000692
Fred Drake8842e861998-02-13 07:16:30 +0000693\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000694>>> s = 'supercalifragilisticexpialidocious'
695>>> len(s)
69634
Fred Drake8842e861998-02-13 07:16:30 +0000697\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000698
Fred Drakeb7833d31998-09-11 16:21:55 +0000699\subsection{Lists \label{lists}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000700
Fred Drakeeee08cd1997-12-04 15:43:15 +0000701Python knows a number of \emph{compound} data types, used to group
702together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000703can be written as a list of comma-separated values (items) between
704square brackets. List items need not all have the same type.
705
Fred Drake8842e861998-02-13 07:16:30 +0000706\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000707>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000708>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000709['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000710\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000711
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000712Like string indices, list indices start at 0, and lists can be sliced,
713concatenated and so on:
714
Fred Drake8842e861998-02-13 07:16:30 +0000715\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000716>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000717'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000718>>> a[3]
7191234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000720>>> a[-2]
721100
722>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000723['eggs', 100]
724>>> a[:2] + ['bacon', 2*2]
725['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000726>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000727['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000728\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000729
Fred Drakeeee08cd1997-12-04 15:43:15 +0000730Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000731individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000732
Fred Drake8842e861998-02-13 07:16:30 +0000733\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000734>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000735['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000736>>> a[2] = a[2] + 23
737>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000738['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000739\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000740
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000741Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000742of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000743
Fred Drake8842e861998-02-13 07:16:30 +0000744\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000745>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000746... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000747>>> a
748[1, 12, 123, 1234]
749>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000750... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000751>>> a
752[123, 1234]
753>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000754... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000755>>> a
756[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000757>>> a[:0] = a # Insert (a copy of) itself at the beginning
758>>> a
759[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000760\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000761
Fred Drake8842e861998-02-13 07:16:30 +0000762The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000763
Fred Drake8842e861998-02-13 07:16:30 +0000764\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000765>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007668
Fred Drake8842e861998-02-13 07:16:30 +0000767\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000768
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000769It is possible to nest lists (create lists containing other lists),
770for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000771
Fred Drake8842e861998-02-13 07:16:30 +0000772\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000773>>> q = [2, 3]
774>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000775>>> len(p)
7763
777>>> p[1]
778[2, 3]
779>>> p[1][0]
7802
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000781>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000782>>> p
783[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000784>>> q
785[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000786\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000787
Fred Drakeeee08cd1997-12-04 15:43:15 +0000788Note that in the last example, \code{p[1]} and \code{q} really refer to
789the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000790
Fred Drakeb7833d31998-09-11 16:21:55 +0000791\section{First Steps Towards Programming \label{firstSteps}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000792
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000793Of course, we can use Python for more complicated tasks than adding
794two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000795subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000796
Fred Drake8842e861998-02-13 07:16:30 +0000797\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000798>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000799... # the sum of two elements defines the next
800... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000801>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000802... print b
803... a, b = b, a+b
804...
8051
8061
8072
8083
8095
8108
Fred Drake8842e861998-02-13 07:16:30 +0000811\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000812
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000813This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000814
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000815\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000816
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000817\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000818The first line contains a \emph{multiple assignment}: the variables
819\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000820last line this is used again, demonstrating that the expressions on
821the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000822assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000823
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000824\item
Fred Drake8842e861998-02-13 07:16:30 +0000825The \keyword{while} loop executes as long as the condition (here:
Fred Drakeee84d591999-03-10 17:25:30 +0000826\code{b < 10}) remains true. In Python, like in C, any non-zero
Fred Drake8842e861998-02-13 07:16:30 +0000827integer value is true; zero is false. The condition may also be a
828string or list value, in fact any sequence; anything with a non-zero
829length is true, empty sequences are false. The test used in the
830example is a simple comparison. The standard comparison operators are
Fred Drakeee84d591999-03-10 17:25:30 +0000831written the same as in C: \code{<}, \code{>}, \code{==}, \code{<=},
Fred Drake8842e861998-02-13 07:16:30 +0000832\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000833
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000834\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000835The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000836way of grouping statements. Python does not (yet!) provide an
837intelligent input line editing facility, so you have to type a tab or
838space(s) for each indented line. In practice you will prepare more
839complicated input for Python with a text editor; most text editors have
840an auto-indent facility. When a compound statement is entered
841interactively, it must be followed by a blank line to indicate
842completion (since the parser cannot guess when you have typed the last
843line).
844
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000845\item
Fred Drake8842e861998-02-13 07:16:30 +0000846The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000847given. It differs from just writing the expression you want to write
848(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000849multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000850and a space is inserted between items, so you can format things nicely,
851like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000852
Fred Drake8842e861998-02-13 07:16:30 +0000853\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000854>>> i = 256*256
855>>> print 'The value of i is', i
856The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000857\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000858
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000859A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000860
Fred Drake8842e861998-02-13 07:16:30 +0000861\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000862>>> a, b = 0, 1
863>>> while b < 1000:
864... print b,
865... a, b = b, a+b
866...
8671 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000868\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000869
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000870Note that the interpreter inserts a newline before it prints the next
871prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000872
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000873\end{itemize}
874
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000875
Fred Drakeb7833d31998-09-11 16:21:55 +0000876\chapter{More Control Flow Tools \label{moreControl}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000877
Fred Drake8842e861998-02-13 07:16:30 +0000878Besides the \keyword{while} statement just introduced, Python knows
879the usual control flow statements known from other languages, with
880some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000881
Fred Drakeb7833d31998-09-11 16:21:55 +0000882\section{\keyword{if} Statements \label{if}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000883
Fred Drake8842e861998-02-13 07:16:30 +0000884Perhaps the most well-known statement type is the \keyword{if}
885statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000886
Fred Drake8842e861998-02-13 07:16:30 +0000887\begin{verbatim}
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000888>>> # [Code which sets 'x' to a value...]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000889>>> if x < 0:
890... x = 0
891... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000892... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000893... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000894... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000895... print 'Single'
896... else:
897... print 'More'
898...
Fred Drake8842e861998-02-13 07:16:30 +0000899\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000900
Fred Drake8842e861998-02-13 07:16:30 +0000901There can be zero or more \keyword{elif} parts, and the \keyword{else}
902part is optional. The keyword `\keyword{elif}' is short for `else
903if', and is useful to avoid excessive indentation. An
904\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif}
905\ldots\ sequence is a substitute for the \emph{switch} or
906% ^^^^
907% Weird spacings happen here if the wrapping of the source text
908% gets changed in the wrong way.
909\emph{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000910
Fred Drakeb7833d31998-09-11 16:21:55 +0000911
912\section{\keyword{for} Statements \label{for}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000913
Fred Drakef790b161998-11-30 20:37:24 +0000914The \keyword{for}\stindex{for} statement in Python differs a bit from
Fred Drakeee84d591999-03-10 17:25:30 +0000915what you may be used to in C or Pascal. Rather than always
Fred Drakef790b161998-11-30 20:37:24 +0000916iterating over an arithmetic progression of numbers (like in Pascal),
917or giving the user the ability to define both the iteration step and
Fred Drakeee84d591999-03-10 17:25:30 +0000918halting condition (as C), Python's \keyword{for}\stindex{for}
Fred Drakef790b161998-11-30 20:37:24 +0000919statement iterates over the items of any sequence (e.g., a list or a
920string), in the order that they appear in the sequence. For example
921(no pun intended):
922% One suggestion was to give a real C example here, but that may only
923% serve to confuse non-C programmers.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000924
Fred Drake8842e861998-02-13 07:16:30 +0000925\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000926>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000927... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000928>>> for x in a:
929... print x, len(x)
930...
931cat 3
932window 6
933defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000934\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000935
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000936It is not safe to modify the sequence being iterated over in the loop
937(this can only happen for mutable sequence types, i.e., lists). If
938you need to modify the list you are iterating over, e.g., duplicate
939selected items, you must iterate over a copy. The slice notation
940makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000941
Fred Drake8842e861998-02-13 07:16:30 +0000942\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000943>>> for x in a[:]: # make a slice copy of the entire list
944... if len(x) > 6: a.insert(0, x)
945...
946>>> a
947['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000948\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000949
Fred Drakeb7833d31998-09-11 16:21:55 +0000950
951\section{The \function{range()} Function \label{range}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000952
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000953If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000954function \function{range()} comes in handy. It generates lists
955containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000956
Fred Drake8842e861998-02-13 07:16:30 +0000957\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000958>>> range(10)
959[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000960\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000961
Fred Drake8842e861998-02-13 07:16:30 +0000962The given end point is never part of the generated list;
963\code{range(10)} generates a list of 10 values, exactly the legal
964indices for items of a sequence of length 10. It is possible to let
965the range start at another number, or to specify a different increment
966(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000967
Fred Drake8842e861998-02-13 07:16:30 +0000968\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000969>>> range(5, 10)
970[5, 6, 7, 8, 9]
971>>> range(0, 10, 3)
972[0, 3, 6, 9]
973>>> range(-10, -100, -30)
974[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000975\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000976
Fred Drake8842e861998-02-13 07:16:30 +0000977To iterate over the indices of a sequence, combine \function{range()}
978and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000979
Fred Drake8842e861998-02-13 07:16:30 +0000980\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000981>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000982>>> for i in range(len(a)):
983... print i, a[i]
984...
9850 Mary
9861 had
9872 a
9883 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009894 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000990\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000991
Fred Drake391564f1998-04-01 23:11:56 +0000992\section{\keyword{break} and \keyword{continue} Statements, and
Fred Drakeb7833d31998-09-11 16:21:55 +0000993 \keyword{else} Clauses on Loops
994 \label{break}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000995
Fred Drakeee84d591999-03-10 17:25:30 +0000996The \keyword{break} statement, like in C, breaks out of the smallest
Fred Drake8842e861998-02-13 07:16:30 +0000997enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000998
Fred Drakeee84d591999-03-10 17:25:30 +0000999The \keyword{continue} statement, also borrowed from C, continues
Fred Drake8842e861998-02-13 07:16:30 +00001000with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001001
Fred Drake8842e861998-02-13 07:16:30 +00001002Loop statements may have an \code{else} clause; it is executed when
1003the loop terminates through exhaustion of the list (with
1004\keyword{for}) or when the condition becomes false (with
1005\keyword{while}), but not when the loop is terminated by a
1006\keyword{break} statement. This is exemplified by the following loop,
1007which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001008
Fred Drake8842e861998-02-13 07:16:30 +00001009\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001010>>> for n in range(2, 10):
1011... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001012... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001013... print n, 'equals', x, '*', n/x
1014... break
1015... else:
1016... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001017...
Guido van Rossum2292b8e1991-01-23 16:31:24 +000010182 is a prime number
10193 is a prime number
10204 equals 2 * 2
10215 is a prime number
10226 equals 2 * 3
10237 is a prime number
10248 equals 2 * 4
10259 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +00001026\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001027
Fred Drakeb7833d31998-09-11 16:21:55 +00001028\section{\keyword{pass} Statements \label{pass}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001029
Fred Drake8842e861998-02-13 07:16:30 +00001030The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001031It can be used when a statement is required syntactically but the
1032program requires no action.
1033For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001034
Fred Drake8842e861998-02-13 07:16:30 +00001035\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001036>>> while 1:
1037... pass # Busy-wait for keyboard interrupt
1038...
Fred Drake8842e861998-02-13 07:16:30 +00001039\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001040
Fred Drakeb7833d31998-09-11 16:21:55 +00001041\section{Defining Functions \label{functions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001042
1043We can create a function that writes the Fibonacci series to an
1044arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001045
Fred Drake8842e861998-02-13 07:16:30 +00001046\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001047>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001048... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001049... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001050... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001051... print b,
1052... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001053...
1054>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001055... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010561 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001057\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001058
Fred Drake8842e861998-02-13 07:16:30 +00001059The keyword \keyword{def} introduces a function \emph{definition}. It
1060must be followed by the function name and the parenthesized list of
1061formal parameters. The statements that form the body of the function
1062start at the next line, indented by a tab stop. The first statement
1063of the function body can optionally be a string literal; this string
1064literal is the function's documentation string, or \dfn{docstring}.
1065There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001066documentation, or to let the user interactively browse through code;
1067it's good practice to include docstrings in code that you write, so
1068try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001069
Fred Drakeeee08cd1997-12-04 15:43:15 +00001070The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001071for the local variables of the function. More precisely, all variable
1072assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001073whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001074in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001075Thus, global variables cannot be directly assigned a value within a
1076function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001077they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001078
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001079The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001080the local symbol table of the called function when it is called; thus,
Fred Drake93aa0f21999-04-05 21:39:17 +00001081arguments are passed using \emph{call by value}.\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001082 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001083 description, since if a mutable object is passed, the caller
1084 will see any changes the callee makes to it (e.g., items
1085 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001086}
1087When a function calls another function, a new local symbol table is
1088created for that call.
1089
Fred Drake8842e861998-02-13 07:16:30 +00001090A function definition introduces the function name in the current
1091symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001092has a type that is recognized by the interpreter as a user-defined
1093function. This value can be assigned to another name which can then
1094also be used as a function. This serves as a general renaming
1095mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001096
Fred Drake8842e861998-02-13 07:16:30 +00001097\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001098>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001099<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001100>>> f = fib
1101>>> f(100)
11021 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001103\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001104
Fred Drakeeee08cd1997-12-04 15:43:15 +00001105You might object that \code{fib} is not a function but a procedure. In
Fred Drakeee84d591999-03-10 17:25:30 +00001106Python, like in C, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001107value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001108albeit a rather boring one. This value is called \code{None} (it's a
1109built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001110the interpreter if it would be the only value written. You can see it
1111if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001112
Fred Drake8842e861998-02-13 07:16:30 +00001113\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001114>>> print fib(0)
1115None
Fred Drake8842e861998-02-13 07:16:30 +00001116\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001117
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001118It is simple to write a function that returns a list of the numbers of
1119the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001120
Fred Drake8842e861998-02-13 07:16:30 +00001121\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001122>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001123... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001124... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001125... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001126... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001127... result.append(b) # see below
1128... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001129... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001130...
1131>>> f100 = fib2(100) # call it
1132>>> f100 # write the result
1133[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001134\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001135%
Guido van Rossum4410c751991-06-04 20:22:18 +00001136This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001137
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001138\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001139
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001140\item
Fred Drake8842e861998-02-13 07:16:30 +00001141The \keyword{return} statement returns with a value from a function.
1142\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001143the middle of a procedure (falling off the end also returns from a
1144procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001145
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001146\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001147The statement \code{result.append(b)} calls a \emph{method} of the list
1148object \code{result}. A method is a function that `belongs' to an
1149object and is named \code{obj.methodname}, where \code{obj} is some
1150object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001151of a method that is defined by the object's type. Different types
1152define different methods. Methods of different types may have the
1153same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001154own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001155in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001156The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001157list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001158example it is equivalent to \samp{result = result + [b]}, but more
1159efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001160
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001161\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001162
Fred Drakeb7833d31998-09-11 16:21:55 +00001163\section{More on Defining Functions \label{defining}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001164
Guido van Rossum02455691997-07-17 16:21:52 +00001165It is also possible to define functions with a variable number of
1166arguments. There are three forms, which can be combined.
1167
Fred Drakeb7833d31998-09-11 16:21:55 +00001168\subsection{Default Argument Values \label{defaultArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001169
1170The most useful form is to specify a default value for one or more
1171arguments. This creates a function that can be called with fewer
1172arguments than it is defined, e.g.
1173
1174\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001175def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1176 while 1:
1177 ok = raw_input(prompt)
1178 if ok in ('y', 'ye', 'yes'): return 1
1179 if ok in ('n', 'no', 'nop', 'nope'): return 0
1180 retries = retries - 1
1181 if retries < 0: raise IOError, 'refusenik user'
1182 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001183\end{verbatim}
1184
1185This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001186\code{ask_ok('Do you really want to quit?')} or like this:
1187\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001188
1189The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001190in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001191
1192\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001193i = 5
1194def f(arg = i): print arg
1195i = 6
1196f()
Guido van Rossum02455691997-07-17 16:21:52 +00001197\end{verbatim}
1198
Fred Drakeeee08cd1997-12-04 15:43:15 +00001199will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001200
Guido van Rossumaee5e261998-08-07 17:45:09 +00001201\strong{Important warning:} The default value is evaluated only once.
1202This makes a difference when the default is a mutable object such as a
1203list or dictionary. For example, the following function accumulates
1204the arguments passed to it on subsequent calls:
1205
1206\begin{verbatim}
1207def f(a, l = []):
1208 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001209 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001210print f(1)
1211print f(2)
1212print f(3)
1213\end{verbatim}
1214
1215This will print
1216
1217\begin{verbatim}
1218[1]
1219[1, 2]
1220[1, 2, 3]
1221\end{verbatim}
1222
1223If you don't want the default to be shared between subsequent calls,
1224you can write the function like this instead:
1225
1226\begin{verbatim}
1227def f(a, l = None):
1228 if l is None:
1229 l = []
1230 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001231 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001232\end{verbatim}
1233
Fred Drakeb7833d31998-09-11 16:21:55 +00001234\subsection{Keyword Arguments \label{keywordArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001235
1236Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001237keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001238instance, the following function:
1239
1240\begin{verbatim}
1241def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1242 print "-- This parrot wouldn't", action,
1243 print "if you put", voltage, "Volts through it."
1244 print "-- Lovely plumage, the", type
1245 print "-- It's", state, "!"
1246\end{verbatim}
1247
1248could be called in any of the following ways:
1249
1250\begin{verbatim}
1251parrot(1000)
1252parrot(action = 'VOOOOOM', voltage = 1000000)
1253parrot('a thousand', state = 'pushing up the daisies')
1254parrot('a million', 'bereft of life', 'jump')
1255\end{verbatim}
1256
1257but the following calls would all be invalid:
1258
1259\begin{verbatim}
1260parrot() # required argument missing
1261parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1262parrot(110, voltage=220) # duplicate value for argument
1263parrot(actor='John Cleese') # unknown keyword
1264\end{verbatim}
1265
1266In general, an argument list must have any positional arguments
1267followed by any keyword arguments, where the keywords must be chosen
1268from the formal parameter names. It's not important whether a formal
Fred Drakef1ad2071999-06-30 15:32:50 +00001269parameter has a default value or not. No argument may receive a
Guido van Rossum02455691997-07-17 16:21:52 +00001270value more than once --- formal parameter names corresponding to
1271positional arguments cannot be used as keywords in the same calls.
Fred Drakef1ad2071999-06-30 15:32:50 +00001272Here's an example that fails due to this restriction:
1273
1274\begin{verbatim}
1275>>> def function(a):
1276... pass
1277...
1278>>> function(0, a=0)
1279Traceback (innermost last):
1280 File "<stdin>", line 1, in ?
1281TypeError: keyword parameter redefined
1282\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00001283
1284When a final formal parameter of the form \code{**\var{name}} is
1285present, it receives a dictionary containing all keyword arguments
1286whose keyword doesn't correspond to a formal parameter. This may be
1287combined with a formal parameter of the form \code{*\var{name}}
1288(described in the next subsection) which receives a tuple containing
1289the positional arguments beyond the formal parameter list.
1290(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1291example, if we define a function like this:
1292
1293\begin{verbatim}
1294def cheeseshop(kind, *arguments, **keywords):
1295 print "-- Do you have any", kind, '?'
1296 print "-- I'm sorry, we're all out of", kind
1297 for arg in arguments: print arg
1298 print '-'*40
1299 for kw in keywords.keys(): print kw, ':', keywords[kw]
1300\end{verbatim}
1301
1302It could be called like this:
1303
1304\begin{verbatim}
1305cheeseshop('Limburger', "It's very runny, sir.",
1306 "It's really very, VERY runny, sir.",
1307 client='John Cleese',
1308 shopkeeper='Michael Palin',
1309 sketch='Cheese Shop Sketch')
1310\end{verbatim}
1311
1312and of course it would print:
1313
1314\begin{verbatim}
1315-- Do you have any Limburger ?
1316-- I'm sorry, we're all out of Limburger
1317It's very runny, sir.
1318It's really very, VERY runny, sir.
1319----------------------------------------
1320client : John Cleese
1321shopkeeper : Michael Palin
1322sketch : Cheese Shop Sketch
1323\end{verbatim}
1324
Fred Drakeb7833d31998-09-11 16:21:55 +00001325\subsection{Arbitrary Argument Lists \label{arbitraryArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001326
1327Finally, the least frequently used option is to specify that a
1328function can be called with an arbitrary number of arguments. These
1329arguments will be wrapped up in a tuple. Before the variable number
1330of arguments, zero or more normal arguments may occur.
1331
1332\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001333def fprintf(file, format, *args):
1334 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001335\end{verbatim}
1336
Fred Drakea594baf1998-04-03 05:16:31 +00001337
Fred Drakeb7833d31998-09-11 16:21:55 +00001338\subsection{Lambda Forms \label{lambda}}
Fred Drakea594baf1998-04-03 05:16:31 +00001339
1340By popular demand, a few features commonly found in functional
1341programming languages and Lisp have been added to Python. With the
1342\keyword{lambda} keyword, small anonymous functions can be created.
1343Here's a function that returns the sum of its two arguments:
1344\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1345objects are required. They are syntactically restricted to a single
1346expression. Semantically, they are just syntactic sugar for a normal
1347function definition. Like nested function definitions, lambda forms
1348cannot reference variables from the containing scope, but this can be
1349overcome through the judicious use of default argument values, e.g.
1350
1351\begin{verbatim}
1352def make_incrementor(n):
1353 return lambda x, incr=n: x+incr
1354\end{verbatim}
1355
Fred Drakeb7833d31998-09-11 16:21:55 +00001356\subsection{Documentation Strings \label{docstrings}}
Fred Drakea594baf1998-04-03 05:16:31 +00001357
1358There are emerging conventions about the content and formatting of
1359documentation strings.
1360
1361The first line should always be a short, concise summary of the
1362object's purpose. For brevity, it should not explicitly state the
1363object's name or type, since these are available by other means
1364(except if the name happens to be a verb describing a function's
1365operation). This line should begin with a capital letter and end with
1366a period.
1367
1368If there are more lines in the documentation string, the second line
1369should be blank, visually separating the summary from the rest of the
Fred Drake4b1a07a1999-03-12 18:21:32 +00001370description. The following lines should be one or more paragraphs
1371describing the object's calling conventions, its side effects, etc.
Fred Drakea594baf1998-04-03 05:16:31 +00001372
1373The Python parser does not strip indentation from multi-line string
1374literals in Python, so tools that process documentation have to strip
1375indentation. This is done using the following convention. The first
1376non-blank line \emph{after} the first line of the string determines the
1377amount of indentation for the entire documentation string. (We can't
1378use the first line since it is generally adjacent to the string's
1379opening quotes so its indentation is not apparent in the string
1380literal.) Whitespace ``equivalent'' to this indentation is then
1381stripped from the start of all lines of the string. Lines that are
1382indented less should not occur, but if they occur all their leading
1383whitespace should be stripped. Equivalence of whitespace should be
1384tested after expansion of tabs (to 8 spaces, normally).
1385
1386
1387
Fred Drakeb7833d31998-09-11 16:21:55 +00001388\chapter{Data Structures \label{structures}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001389
1390This chapter describes some things you've learned about already in
1391more detail, and adds some new things as well.
1392
Fred Drakeb7833d31998-09-11 16:21:55 +00001393\section{More on Lists \label{moreLists}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001394
1395The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001396of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001397
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001398\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001399
Fred Drakeeee08cd1997-12-04 15:43:15 +00001400\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001401Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001402the element before which to insert, so \code{a.insert(0, x)} inserts at
1403the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1404\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001405
Fred Drakeeee08cd1997-12-04 15:43:15 +00001406\item[\code{append(x)}]
Fred Drakef1ad2071999-06-30 15:32:50 +00001407Append an item to the list;
1408equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001409
Fred Drakeeee08cd1997-12-04 15:43:15 +00001410\item[\code{index(x)}]
1411Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001412It is an error if there is no such item.
1413
Fred Drakeeee08cd1997-12-04 15:43:15 +00001414\item[\code{remove(x)}]
1415Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001416It is an error if there is no such item.
1417
Fred Drakeeee08cd1997-12-04 15:43:15 +00001418\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001419Sort the items of the list, in place.
1420
Fred Drakeeee08cd1997-12-04 15:43:15 +00001421\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001422Reverse the elements of the list, in place.
1423
Fred Drakeeee08cd1997-12-04 15:43:15 +00001424\item[\code{count(x)}]
1425Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001426
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001427\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001428
1429An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001430
Fred Drake8842e861998-02-13 07:16:30 +00001431\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001432>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001433>>> print a.count(333), a.count(66.6), a.count('x')
14342 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001435>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001436>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001437>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001438[66.6, 333, -1, 333, 1, 1234.5, 333]
1439>>> a.index(333)
14401
1441>>> a.remove(333)
1442>>> a
1443[66.6, -1, 333, 1, 1234.5, 333]
1444>>> a.reverse()
1445>>> a
1446[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001447>>> a.sort()
1448>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001449[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001450\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001451
Fred Drakeb7833d31998-09-11 16:21:55 +00001452\subsection{Functional Programming Tools \label{functional}}
Guido van Rossum02455691997-07-17 16:21:52 +00001453
1454There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001455lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001456
Fred Drake8842e861998-02-13 07:16:30 +00001457\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1458the same type, if possible) consisting of those items from the
1459sequence for which \code{\var{function}(\var{item})} is true. For
1460example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001461
1462\begin{verbatim}
Fred Drakeee84d591999-03-10 17:25:30 +00001463>>> def f(x): return x % 2 != 0 and x % 3 != 0
Fred Drake8842e861998-02-13 07:16:30 +00001464...
1465>>> filter(f, range(2, 25))
1466[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001467\end{verbatim}
1468
Fred Drake8842e861998-02-13 07:16:30 +00001469\samp{map(\var{function}, \var{sequence})} calls
1470\code{\var{function}(\var{item})} for each of the sequence's items and
1471returns a list of the return values. For example, to compute some
1472cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001473
1474\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001475>>> def cube(x): return x*x*x
1476...
1477>>> map(cube, range(1, 11))
1478[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001479\end{verbatim}
1480
1481More than one sequence may be passed; the function must then have as
1482many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001483corresponding item from each sequence (or \code{None} if some sequence
1484is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001485a function returning its argument(s) is substituted.
1486
1487Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001488\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1489turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001490
1491\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001492>>> seq = range(8)
1493>>> def square(x): return x*x
1494...
1495>>> map(None, seq, map(square, seq))
1496[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001497\end{verbatim}
1498
Fred Drake8842e861998-02-13 07:16:30 +00001499\samp{reduce(\var{func}, \var{sequence})} returns a single value
1500constructed by calling the binary function \var{func} on the first two
1501items of the sequence, then on the result and the next item, and so
1502on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001503
1504\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001505>>> def add(x,y): return x+y
1506...
1507>>> reduce(add, range(1, 11))
150855
Guido van Rossum02455691997-07-17 16:21:52 +00001509\end{verbatim}
1510
1511If there's only one item in the sequence, its value is returned; if
1512the sequence is empty, an exception is raised.
1513
1514A third argument can be passed to indicate the starting value. In this
1515case the starting value is returned for an empty sequence, and the
1516function is first applied to the starting value and the first sequence
1517item, then to the result and the next item, and so on. For example,
1518
1519\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001520>>> def sum(seq):
1521... def add(x,y): return x+y
1522... return reduce(add, seq, 0)
1523...
1524>>> sum(range(1, 11))
152555
1526>>> sum([])
15270
Guido van Rossum02455691997-07-17 16:21:52 +00001528\end{verbatim}
1529
Fred Drakeb7833d31998-09-11 16:21:55 +00001530\section{The \keyword{del} statement \label{del}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001531
1532There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001533of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001534remove slices from a list (which we did earlier by assignment of an
1535empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001536
Fred Drake8842e861998-02-13 07:16:30 +00001537\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001538>>> a
1539[-1, 1, 66.6, 333, 333, 1234.5]
1540>>> del a[0]
1541>>> a
1542[1, 66.6, 333, 333, 1234.5]
1543>>> del a[2:4]
1544>>> a
1545[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001546\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001547
1548\keyword{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001549
Fred Drake8842e861998-02-13 07:16:30 +00001550\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001551>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001552\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001553
Fred Drakeeee08cd1997-12-04 15:43:15 +00001554Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001555another value is assigned to it). We'll find other uses for
1556\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001557
Fred Drakeb7833d31998-09-11 16:21:55 +00001558\section{Tuples and Sequences \label{tuples}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001559
1560We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001561indexing and slicing operations. They are two examples of
1562\emph{sequence} data types. Since Python is an evolving language,
1563other sequence data types may be added. There is also another
1564standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001565
1566A tuple consists of a number of values separated by commas, for
1567instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001568
Fred Drake8842e861998-02-13 07:16:30 +00001569\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001570>>> t = 12345, 54321, 'hello!'
1571>>> t[0]
157212345
1573>>> t
1574(12345, 54321, 'hello!')
1575>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001576... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001577>>> u
1578((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001579\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001580
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001581As you see, on output tuples are alway enclosed in parentheses, so
1582that nested tuples are interpreted correctly; they may be input with
1583or without surrounding parentheses, although often parentheses are
1584necessary anyway (if the tuple is part of a larger expression).
1585
1586Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1587from a database, etc. Tuples, like strings, are immutable: it is not
1588possible to assign to the individual items of a tuple (you can
1589simulate much of the same effect with slicing and concatenation,
1590though).
1591
1592A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001593items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001594tuples are constructed by an empty pair of parentheses; a tuple with
1595one item is constructed by following a value with a comma
1596(it is not sufficient to enclose a single value in parentheses).
1597Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001598
Fred Drake8842e861998-02-13 07:16:30 +00001599\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001600>>> empty = ()
1601>>> singleton = 'hello', # <-- note trailing comma
1602>>> len(empty)
16030
1604>>> len(singleton)
16051
1606>>> singleton
1607('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001608\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001609
Fred Drakeeee08cd1997-12-04 15:43:15 +00001610The statement \code{t = 12345, 54321, 'hello!'} is an example of
1611\emph{tuple packing}: the values \code{12345}, \code{54321} and
1612\code{'hello!'} are packed together in a tuple. The reverse operation
1613is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001614
Fred Drake8842e861998-02-13 07:16:30 +00001615\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001616>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001617\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001618
Fred Drakeeee08cd1997-12-04 15:43:15 +00001619This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Fred Drakef1ad2071999-06-30 15:32:50 +00001620unpacking requires that the list of variables on the left have the same
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001621number of elements as the length of the tuple. Note that multiple
1622assignment is really just a combination of tuple packing and tuple
1623unpacking!
1624
Guido van Rossumaee5e261998-08-07 17:45:09 +00001625% XXX This is no longer necessary!
Fred Drakeeee08cd1997-12-04 15:43:15 +00001626Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001627unpacking}. This is supported by enclosing the list of variables in
1628square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001629
Fred Drake8842e861998-02-13 07:16:30 +00001630\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001631>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001632>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001633\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001634
Guido van Rossumaee5e261998-08-07 17:45:09 +00001635% XXX Add a bit on the difference between tuples and lists.
1636% XXX Also explain that a tuple can *contain* a mutable object!
1637
Fred Drakeb7833d31998-09-11 16:21:55 +00001638\section{Dictionaries \label{dictionaries}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001639
Fred Drakeeee08cd1997-12-04 15:43:15 +00001640Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001641Dictionaries are sometimes found in other languages as ``associative
1642memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001643indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Fred Drakef1ad2071999-06-30 15:32:50 +00001644which can be any immutable type; strings and numbers can always be
Guido van Rossum02455691997-07-17 16:21:52 +00001645keys. Tuples can be used as keys if they contain only strings,
1646numbers, or tuples. You can't use lists as keys, since lists can be
1647modified in place using their \code{append()} method.
1648
Guido van Rossum6938f061994-08-01 12:22:53 +00001649It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001650\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001651(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001652A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001653Placing a comma-separated list of key:value pairs within the
1654braces adds initial key:value pairs to the dictionary; this is also the
1655way dictionaries are written on output.
1656
1657The main operations on a dictionary are storing a value with some key
1658and extracting the value given the key. It is also possible to delete
1659a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001660with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001661If you store using a key that is already in use, the old value
1662associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001663value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001664
Fred Drakeeee08cd1997-12-04 15:43:15 +00001665The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001666keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001667just apply the \code{sort()} method to the list of keys). To check
1668whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001669method of the dictionary.
1670
1671Here is a small example using a dictionary:
1672
Fred Drake8842e861998-02-13 07:16:30 +00001673\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001674>>> tel = {'jack': 4098, 'sape': 4139}
1675>>> tel['guido'] = 4127
1676>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001677{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001678>>> tel['jack']
16794098
1680>>> del tel['sape']
1681>>> tel['irv'] = 4127
1682>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001683{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001684>>> tel.keys()
1685['guido', 'irv', 'jack']
1686>>> tel.has_key('guido')
16871
Fred Drake8842e861998-02-13 07:16:30 +00001688\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001689
Fred Drakeb7833d31998-09-11 16:21:55 +00001690\section{More on Conditions \label{conditions}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001691
Fred Drakeeee08cd1997-12-04 15:43:15 +00001692The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001693contain other operators besides comparisons.
1694
Fred Drakeeee08cd1997-12-04 15:43:15 +00001695The comparison operators \code{in} and \code{not in} check whether a value
1696occurs (does not occur) in a sequence. The operators \code{is} and
1697\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001698only matters for mutable objects like lists. All comparison operators
1699have the same priority, which is lower than that of all numerical
1700operators.
1701
Fred Drakef1ad2071999-06-30 15:32:50 +00001702Comparisons can be chained: e.g., \code{a < b == c} tests whether
1703\code{a} is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001704
Fred Drakeeee08cd1997-12-04 15:43:15 +00001705Comparisons may be combined by the Boolean operators \code{and} and
1706\code{or}, and the outcome of a comparison (or of any other Boolean
1707expression) may be negated with \code{not}. These all have lower
1708priorities than comparison operators again; between them, \code{not} has
1709the highest priority, and \code{or} the lowest, so that
1710\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 +00001711course, parentheses can be used to express the desired composition.
1712
Fred Drakeeee08cd1997-12-04 15:43:15 +00001713The Boolean operators \code{and} and \code{or} are so-called
1714\emph{shortcut} operators: their arguments are evaluated from left to
1715right, and evaluation stops as soon as the outcome is determined.
1716E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1717and B and C} does not evaluate the expression C. In general, the
1718return value of a shortcut operator, when used as a general value and
1719not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001720
1721It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001722expression to a variable. For example,
1723
Fred Drake8842e861998-02-13 07:16:30 +00001724\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001725>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1726>>> non_null = string1 or string2 or string3
1727>>> non_null
1728'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001729\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001730
Fred Drakeee84d591999-03-10 17:25:30 +00001731Note that in Python, unlike C, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001732
Fred Drakeb7833d31998-09-11 16:21:55 +00001733\section{Comparing Sequences and Other Types \label{comparing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001734
1735Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001736sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001737first the first two items are compared, and if they differ this
1738determines the outcome of the comparison; if they are equal, the next
1739two items are compared, and so on, until either sequence is exhausted.
1740If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001741the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001742items of two sequences compare equal, the sequences are considered
1743equal. If one sequence is an initial subsequence of the other, the
1744shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001745strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001746examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001747
Fred Drake8842e861998-02-13 07:16:30 +00001748\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001749(1, 2, 3) < (1, 2, 4)
1750[1, 2, 3] < [1, 2, 4]
1751'ABC' < 'C' < 'Pascal' < 'Python'
1752(1, 2, 3, 4) < (1, 2, 4)
1753(1, 2) < (1, 2, -1)
Fred Drake511281a1999-04-16 13:17:04 +00001754(1, 2, 3) == (1.0, 2.0, 3.0)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001755(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001756\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001757
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001758Note that comparing objects of different types is legal. The outcome
1759is deterministic but arbitrary: the types are ordered by their name.
1760Thus, a list is always smaller than a string, a string is always
1761smaller than a tuple, etc. Mixed numeric types are compared according
Fred Drake93aa0f21999-04-05 21:39:17 +00001762to their numeric value, so 0 equals 0.0, etc.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001763 The rules for comparing objects of different types should
1764 not be relied upon; they may change in a future version of
1765 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001766}
1767
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001768
Fred Drakeb7833d31998-09-11 16:21:55 +00001769\chapter{Modules \label{modules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001770
Guido van Rossum4410c751991-06-04 20:22:18 +00001771If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001772definitions you have made (functions and variables) are lost.
1773Therefore, if you want to write a somewhat longer program, you are
1774better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001775and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001776\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001777into several files for easier maintenance. You may also want to use a
1778handy function that you've written in several programs without copying
1779its definition into each program.
1780
Guido van Rossum4410c751991-06-04 20:22:18 +00001781To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001782them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001783Such a file is called a \emph{module}; definitions from a module can be
1784\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001785collection of variables that you have access to in a script
1786executed at the top level
1787and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001788
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001789A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001790file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001791a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001792the global variable \code{__name__}. For instance, use your favorite text
1793editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001794with the following contents:
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# Fibonacci numbers module
1798
1799def fib(n): # write Fibonacci series up to n
1800 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001801 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001802 print b,
1803 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001804
1805def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001806 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001807 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001808 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001809 result.append(b)
1810 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001811 return result
Fred Drake8842e861998-02-13 07:16:30 +00001812\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001813
Guido van Rossum4410c751991-06-04 20:22:18 +00001814Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001815following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001816
Fred Drake8842e861998-02-13 07:16:30 +00001817\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001818>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001819\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001820
Fred Drakef1ad2071999-06-30 15:32:50 +00001821This does not enter the names of the functions defined in \code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001822directly in the current symbol table; it only enters the module name
Fred Drakef1ad2071999-06-30 15:32:50 +00001823\code{fibo} there.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001824Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001825
Fred Drake8842e861998-02-13 07:16:30 +00001826\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001827>>> fibo.fib(1000)
18281 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1829>>> fibo.fib2(100)
1830[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001831>>> fibo.__name__
1832'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001833\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001834%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001835If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001836
Fred Drake8842e861998-02-13 07:16:30 +00001837\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001838>>> fib = fibo.fib
1839>>> fib(500)
18401 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001841\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001842
Guido van Rossum02455691997-07-17 16:21:52 +00001843
Fred Drakeb7833d31998-09-11 16:21:55 +00001844\section{More on Modules \label{moreModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001845
1846A module can contain executable statements as well as function
1847definitions.
1848These statements are intended to initialize the module.
1849They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001850\emph{first}
Fred Drake93aa0f21999-04-05 21:39:17 +00001851time the module is imported somewhere.\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001852 In fact function definitions are also `statements' that are
1853 `executed'; the execution enters the function name in the
1854 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001855}
1856
1857Each module has its own private symbol table, which is used as the
1858global symbol table by all functions defined in the module.
1859Thus, the author of a module can use global variables in the module
1860without worrying about accidental clashes with a user's global
1861variables.
1862On the other hand, if you know what you are doing you can touch a
1863module's global variables with the same notation used to refer to its
1864functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001865\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001866
1867Modules can import other modules.
1868It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001869\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001870statements at the beginning of a module (or script, for that matter).
1871The imported module names are placed in the importing module's global
1872symbol table.
1873
1874There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001875\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001876statement that imports names from a module directly into the importing
1877module's symbol table.
1878For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001879
Fred Drake8842e861998-02-13 07:16:30 +00001880\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001881>>> from fibo import fib, fib2
1882>>> fib(500)
18831 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001884\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001885
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001886This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001887in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001888defined).
1889
1890There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001891
Fred Drake8842e861998-02-13 07:16:30 +00001892\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001893>>> from fibo import *
1894>>> fib(500)
18951 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001896\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001897
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001898This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001899(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001900
Fred Drakeb7833d31998-09-11 16:21:55 +00001901\subsection{The Module Search Path \label{searchPath}}
Guido van Rossum02455691997-07-17 16:21:52 +00001902
Guido van Rossumaee5e261998-08-07 17:45:09 +00001903% XXX Need to document that a lone .pyc/.pyo is acceptable too!
1904
Fred Drake391564f1998-04-01 23:11:56 +00001905\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00001906When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001907for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001908and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00001909the environment variable \envvar{PYTHONPATH}. This has the same syntax as
1910the shell variable \envvar{PATH}, i.e., a list of
1911directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001912is not found there, the search continues in an installation-dependent
Fred Drake391564f1998-04-01 23:11:56 +00001913default path; on \UNIX{}, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001914
1915Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001916variable \code{sys.path} which is initialized from the directory
1917containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00001918\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001919Python programs that know what they're doing to modify or replace the
1920module search path. See the section on Standard Modules later.
1921
1922\subsection{``Compiled'' Python files}
1923
1924As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001925use a lot of standard modules, if a file called \file{spam.pyc} exists
1926in the directory where \file{spam.py} is found, this is assumed to
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001927contain an already-``byte-compiled'' version of the module \module{spam}.
Fred Drake8842e861998-02-13 07:16:30 +00001928The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001929\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1930ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001931
Fred Drakeeee08cd1997-12-04 15:43:15 +00001932Normally, you don't need to do anything to create the \file{spam.pyc} file.
1933Whenever \file{spam.py} is successfully compiled, an attempt is made to
1934write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001935this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001936completely, the resulting \file{spam.pyc} file will be recognized as
1937invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001938file is platform independent, so a Python module directory can be
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001939shared by machines of different architectures.
Guido van Rossum02455691997-07-17 16:21:52 +00001940
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001941Some tips for experts:
1942
1943\begin{itemize}
1944
1945\item
1946When the Python interpreter is invoked with the \code{-O} flag,
1947optimized code is generated and stored in \file{.pyo} files.
1948The optimizer currently doesn't help much; it only removes
1949\keyword{assert} statements and \code{SET_LINENO} instructions.
1950When \code{-O} is used, \emph{all} bytecode is optimized; \code{.pyc}
1951files are ignored and \code{.py} files are compiled to optimized
1952bytecode.
1953
1954\item
Guido van Rossum6b86a421999-01-28 15:07:47 +00001955Passing two \code{-O} flags to the Python interpreter (\code{-OO})
1956will cause the bytecode compiler to perform optimizations that could
1957in some rare cases result in malfunctioning programs. Currently only
1958\code{__doc__} strings are removed from the bytecode, resulting in more
1959compact \file{.pyo} files. Since some programs may rely on having
1960these available, you should only use this option if you know what
1961you're doing.
1962
1963\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001964A program doesn't run any faster when it is read from a
1965\file{.pyc} or \file{.pyo} file than when it is read from a \file{.py}
1966file; the only thing that's faster about \file{.pyc} or \file{.pyo}
1967files is the speed with which they are loaded.
1968
1969\item
Guido van Rossum002f7aa1998-06-28 19:16:38 +00001970When a script is run by giving its name on the command line, the
1971bytecode for the script is never written to a \file{.pyc} or
1972\file{.pyo} file. Thus, the startup time of a script may be reduced
1973by moving most of its code to a module and having a small bootstrap
1974script that imports that module.
1975
1976\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001977It is possible to have a file called \file{spam.pyc} (or
1978\file{spam.pyo} when \code{-O} is used) without a module
1979\file{spam.py} in the same module. This can be used to distribute
1980a library of Python code in a form that is moderately hard to reverse
1981engineer.
1982
1983\item
1984The module \module{compileall}\refstmodindex{compileall} can create
1985\file{.pyc} files (or \file{.pyo} files when \code{-O} is used) for
1986all modules in a directory.
1987
1988\end{itemize}
1989
Guido van Rossum02455691997-07-17 16:21:52 +00001990
Fred Drakeb7833d31998-09-11 16:21:55 +00001991\section{Standard Modules \label{standardModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001992
Guido van Rossum4410c751991-06-04 20:22:18 +00001993Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001994document, the \emph{Python Library Reference} (``Library Reference''
1995hereafter). Some modules are built into the interpreter; these
1996provide access to operations that are not part of the core of the
1997language but are nevertheless built in, either for efficiency or to
1998provide access to operating system primitives such as system calls.
1999The set of such modules is a configuration option; e.g., the
2000\module{amoeba} module is only provided on systems that somehow
2001support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00002002attention: \module{sys}\refstmodindex{sys}, which is built into every
Fred Drakeee84d591999-03-10 17:25:30 +00002003Python interpreter. The variables \code{sys.ps1} and
2004\code{sys.ps2} define the strings used as primary and secondary
2005prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002006
Fred Drake8842e861998-02-13 07:16:30 +00002007\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002008>>> import sys
2009>>> sys.ps1
2010'>>> '
2011>>> sys.ps2
2012'... '
2013>>> sys.ps1 = 'C> '
2014C> print 'Yuck!'
2015Yuck!
2016C>
Fred Drake8842e861998-02-13 07:16:30 +00002017\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002018
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002019These two variables are only defined if the interpreter is in
2020interactive mode.
2021
Fred Drakeee84d591999-03-10 17:25:30 +00002022The variable \code{sys.path} is a list of strings that determine the
2023interpreter's search path for modules. It is initialized to a default
2024path taken from the environment variable \envvar{PYTHONPATH}, or from
2025a built-in default if \envvar{PYTHONPATH} is not set. You can modify
2026it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002027
Fred Drake8842e861998-02-13 07:16:30 +00002028\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002029>>> import sys
2030>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00002031\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002032
Fred Drakeb7833d31998-09-11 16:21:55 +00002033\section{The \function{dir()} Function \label{dir}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002034
Fred Drake8842e861998-02-13 07:16:30 +00002035The built-in function \function{dir()} is used to find out which names
2036a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002037
Fred Drake8842e861998-02-13 07:16:30 +00002038\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002039>>> import fibo, sys
2040>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00002041['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002042>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00002043['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
2044'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
2045'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00002046\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002047
Fred Drake8842e861998-02-13 07:16:30 +00002048Without arguments, \function{dir()} lists the names you have defined
2049currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002050
Fred Drake8842e861998-02-13 07:16:30 +00002051\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002052>>> a = [1, 2, 3, 4, 5]
2053>>> import fibo, sys
2054>>> fib = fibo.fib
2055>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00002056['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00002057\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002058
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002059Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002060
Fred Drake8842e861998-02-13 07:16:30 +00002061\function{dir()} does not list the names of built-in functions and
2062variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00002063standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002064
Fred Drake8842e861998-02-13 07:16:30 +00002065\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00002066>>> import __builtin__
2067>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00002068['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
2069'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2070'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
2071'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
2072'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
2073'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
2074'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
2075'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
2076'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00002077\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002078
Fred Drakeb7833d31998-09-11 16:21:55 +00002079\section{Packages \label{packages}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002080
2081Packages are a way of structuring Python's module namespace
Fred Drakeb7833d31998-09-11 16:21:55 +00002082by using ``dotted module names''. For example, the module name
2083\module{A.B} designates a submodule named \samp{B} in a package named
2084\samp{A}. Just like the use of modules saves the authors of different
2085modules from having to worry about each other's global variable names,
2086the use of dotted module names saves the authors of multi-module
2087packages like NumPy or PIL from having to worry about each other's
2088module names.
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002089
2090Suppose you want to design a collection of modules (a ``package'') for
2091the uniform handling of sound files and sound data. There are many
2092different sound file formats (usually recognized by their extension,
2093e.g. \file{.wav}, \file{.aiff}, \file{.au}), so you may need to create
2094and maintain a growing collection of modules for the conversion
2095between the various file formats. There are also many different
2096operations you might want to perform on sound data (e.g. mixing,
2097adding echo, applying an equalizer function, creating an artificial
2098stereo effect), so in addition you will be writing a never-ending
2099stream of modules to perform these operations. Here's a possible
2100structure for your package (expressed in terms of a hierarchical
2101filesystem):
2102
2103\begin{verbatim}
2104Sound/ Top-level package
2105 __init__.py Initialize the sound package
2106 Formats/ Subpackage for file format conversions
2107 __init__.py
2108 wavread.py
2109 wavwrite.py
2110 aiffread.py
2111 aiffwrite.py
2112 auread.py
2113 auwrite.py
2114 ...
2115 Effects/ Subpackage for sound effects
2116 __init__.py
2117 echo.py
2118 surround.py
2119 reverse.py
2120 ...
2121 Filters/ Subpackage for filters
2122 __init__.py
2123 equalizer.py
2124 vocoder.py
2125 karaoke.py
2126 ...
2127\end{verbatim}
2128The \file{__init__.py} files are required to make Python treat the
2129directories as containing packages; this is done to prevent
2130directories with a common name, such as \samp{string}, from
2131unintentionally hiding valid modules that occur later on the module
2132search path. In the simplest case, \file{__init__.py} can just be an
2133empty file, but it can also execute initialization code for the
2134package or set the \code{__all__} variable, described later.
2135
2136Users of the package can import individual modules from the
2137package, for example:
2138
2139\begin{verbatim}
2140import Sound.Effects.echo
2141\end{verbatim}
2142This loads the submodule \module{Sound.Effects.echo}. It must be referenced
2143with its full name, e.g.
2144
2145\begin{verbatim}
2146Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
2147\end{verbatim}
2148An alternative way of importing the submodule is:
2149
2150\begin{verbatim}
2151from Sound.Effects import echo
2152\end{verbatim}
2153This also loads the submodule \module{echo}, and makes it available without
2154its package prefix, so it can be used as follows:
2155
2156\begin{verbatim}
2157echo.echofilter(input, output, delay=0.7, atten=4)
2158\end{verbatim}
2159
2160Yet another variation is to import the desired function or variable directly:
2161
2162\begin{verbatim}
2163from Sound.Effects.echo import echofilter
2164\end{verbatim}
2165
2166Again, this loads the submodule \module{echo}, but this makes its function
2167echofilter directly available:
2168
2169\begin{verbatim}
2170echofilter(input, output, delay=0.7, atten=4)
2171\end{verbatim}
2172
2173Note that when using \code{from \var{package} import \var{item}}, the
2174item can be either a submodule (or subpackage) of the package, or some
2175other name defined in the package, like a function, class or
2176variable. The \code{import} statement first tests whether the item is
2177defined in the package; if not, it assumes it is a module and attempts
2178to load it. If it fails to find it, \exception{ImportError} is raised.
2179
2180Contrarily, when using syntax like \code{import
2181\var{item.subitem.subsubitem}}, each item except for the last must be
2182a package; the last item can be a module or a package but can't be a
2183class or function or variable defined in the previous item.
2184
Fred Drakeb7833d31998-09-11 16:21:55 +00002185\subsection{Importing * From a Package \label{pkg-import-star}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002186%The \code{__all__} Attribute
2187
2188Now what happens when the user writes \code{from Sound.Effects import
2189*}? Ideally, one would hope that this somehow goes out to the
2190filesystem, finds which submodules are present in the package, and
2191imports them all. Unfortunately, this operation does not work very
2192well on Mac and Windows platforms, where the filesystem does not
2193always have accurate information about the case of a filename! On
2194these platforms, there is no guaranteed way to know whether a file
2195\file{ECHO.PY} should be imported as a module \module{echo},
2196\module{Echo} or \module{ECHO}. (For example, Windows 95 has the
2197annoying practice of showing all file names with a capitalized first
2198letter.) The DOS 8+3 filename restriction adds another interesting
2199problem for long module names.
2200
2201The only solution is for the package author to provide an explicit
2202index of the package. The import statement uses the following
2203convention: if a package's \file{__init__.py} code defines a list named
2204\code{__all__}, it is taken to be the list of module names that should be imported
2205when \code{from \var{package} import *} is
2206encountered. It is up to the package author to keep this list
2207up-to-date when a new version of the package is released. Package
2208authors may also decide not to support it, if they don't see a use for
2209importing * from their package. For example, the file
2210\code{Sounds/Effects/__init__.py} could contain the following code:
2211
2212\begin{verbatim}
2213__all__ = ["echo", "surround", "reverse"]
2214\end{verbatim}
2215
2216This would mean that \code{from Sound.Effects import *} would
2217import the three named submodules of the \module{Sound} package.
2218
2219If \code{__all__} is not defined, the statement \code{from Sound.Effects
2220import *} does \emph{not} import all submodules from the package
2221\module{Sound.Effects} into the current namespace; it only ensures that the
2222package \module{Sound.Effects} has been imported (possibly running its
2223initialization code, \file{__init__.py}) and then imports whatever names are
2224defined in the package. This includes any names defined (and
2225submodules explicitly loaded) by \file{__init__.py}. It also includes any
2226submodules of the package that were explicitly loaded by previous
2227import statements, e.g.
2228
2229\begin{verbatim}
2230import Sound.Effects.echo
2231import Sound.Effects.surround
2232from Sound.Effects import *
2233\end{verbatim}
2234
2235
2236In this example, the echo and surround modules are imported in the
2237current namespace because they are defined in the \module{Sound.Effects}
2238package when the \code{from...import} statement is executed. (This also
2239works when \code{__all__} is defined.)
2240
2241Note that in general the practicing of importing * from a module or
2242package is frowned upon, since it often causes poorly readable code.
2243However, it is okay to use it to save typing in interactive sessions,
2244and certain modules are designed to export only names that follow
2245certain patterns.
2246
2247Remember, there is nothing wrong with using \code{from Package
2248import specific_submodule}! In fact, this is the
2249recommended notation unless the importing module needs to use
2250submodules with the same name from different packages.
2251
2252
2253\subsection{Intra-package References}
2254
2255The submodules often need to refer to each other. For example, the
2256\module{surround} module might use the \module{echo} module. In fact, such references
2257are so common that the \code{import} statement first looks in the
2258containing package before looking in the standard module search path.
2259Thus, the surround module can simply use \code{import echo} or
2260\code{from echo import echofilter}. If the imported module is not
2261found in the current package (the package of which the current module
2262is a submodule), the \code{import} statement looks for a top-level module
2263with the given name.
2264
2265When packages are structured into subpackages (as with the \module{Sound}
2266package in the example), there's no shortcut to refer to submodules of
2267sibling packages - the full name of the subpackage must be used. For
2268example, if the module \module{Sound.Filters.vocoder} needs to use the \module{echo}
2269module in the \module{Sound.Effects} package, it can use \code{from
2270Sound.Effects import echo}.
2271
2272%(One could design a notation to refer to parent packages, similar to
2273%the use of ".." to refer to the parent directory in Unix and Windows
2274%filesystems. In fact, the \module{ni} module, which was the
2275%ancestor of this package system, supported this using \code{__} for
2276%the package containing the current module,
2277%\code{__.__} for the parent package, and so on. This feature was dropped
2278%because of its awkwardness; since most packages will have a relative
2279%shallow substructure, this is no big loss.)
2280
2281
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002282
Fred Drakeb7833d31998-09-11 16:21:55 +00002283\chapter{Input and Output \label{io}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002284
Guido van Rossum02455691997-07-17 16:21:52 +00002285There are several ways to present the output of a program; data can be
2286printed in a human-readable form, or written to a file for future use.
2287This chapter will discuss some of the possibilities.
2288
Fred Drakeb7833d31998-09-11 16:21:55 +00002289
2290\section{Fancier Output Formatting \label{formatting}}
2291
Fred Drakeeee08cd1997-12-04 15:43:15 +00002292So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00002293statements} and the \keyword{print} statement. (A third way is using
2294the \method{write()} method of file objects; the standard output file
2295can be referenced as \code{sys.stdout}. See the Library Reference for
2296more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002297
2298Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00002299simply printing space-separated values. There are two ways to format
2300your output; the first way is to do all the string handling yourself;
2301using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00002302lay-out you can imagine. The standard module
2303\module{string}\refstmodindex{string} contains some useful operations
2304for padding strings to a given column width;
Guido van Rossum02455691997-07-17 16:21:52 +00002305these will be discussed shortly. The second way is to use the
2306\code{\%} operator with a string as the left argument. \code{\%}
Fred Drakeee84d591999-03-10 17:25:30 +00002307interprets the left argument as a C \cfunction{sprintf()}-style
Fred Drake8842e861998-02-13 07:16:30 +00002308format string to be applied to the right argument, and returns the
2309string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002310
2311One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00002312Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00002313the \function{repr()} function, or just write the value between
2314reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002315
Fred Drake8842e861998-02-13 07:16:30 +00002316\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002317>>> x = 10 * 3.14
2318>>> y = 200*200
2319>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2320>>> print s
2321The value of x is 31.4, and y is 40000...
2322>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00002323... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00002324>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002325>>> ps
2326'[31.4, 40000]'
2327>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00002328... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002329>>> hellos = `hello`
2330>>> print hellos
2331'hello, world\012'
2332>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002333... `x, y, ('spam', 'eggs')`
2334"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00002335\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002336
Guido van Rossum6938f061994-08-01 12:22:53 +00002337Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002338
Fred Drake8842e861998-02-13 07:16:30 +00002339\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002340>>> import string
2341>>> for x in range(1, 11):
2342... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
2343... # Note trailing comma on previous line
2344... print string.rjust(`x*x*x`, 4)
2345...
2346 1 1 1
2347 2 4 8
2348 3 9 27
2349 4 16 64
2350 5 25 125
2351 6 36 216
2352 7 49 343
2353 8 64 512
2354 9 81 729
235510 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002356>>> for x in range(1,11):
2357... print '%2d %3d %4d' % (x, x*x, x*x*x)
2358...
2359 1 1 1
2360 2 4 8
2361 3 9 27
2362 4 16 64
2363 5 25 125
2364 6 36 216
2365 7 49 343
2366 8 64 512
2367 9 81 729
236810 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002369\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002370
Fred Drake8842e861998-02-13 07:16:30 +00002371(Note that one space between each column was added by the way
2372\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002373
Fred Drake8842e861998-02-13 07:16:30 +00002374This example demonstrates the function \function{string.rjust()},
2375which right-justifies a string in a field of a given width by padding
2376it with spaces on the left. There are similar functions
2377\function{string.ljust()} and \function{string.center()}. These
2378functions do not write anything, they just return a new string. If
2379the input string is too long, they don't truncate it, but return it
2380unchanged; this will mess up your column lay-out but that's usually
2381better than the alternative, which would be lying about a value. (If
2382you really want truncation you can always add a slice operation, as in
2383\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002384
Fred Drake8842e861998-02-13 07:16:30 +00002385There is another function, \function{string.zfill()}, which pads a
2386numeric string on the left with zeros. It understands about plus and
2387minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002388
Fred Drake8842e861998-02-13 07:16:30 +00002389\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002390>>> string.zfill('12', 5)
2391'00012'
2392>>> string.zfill('-3.14', 7)
2393'-003.14'
2394>>> string.zfill('3.14159265359', 5)
2395'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002396\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002397%
2398Using the \code{\%} operator looks like this:
2399
2400\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002401>>> import math
2402>>> print 'The value of PI is approximately %5.3f.' % math.pi
2403The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002404\end{verbatim}
2405
2406If there is more than one format in the string you pass a tuple as
2407right operand, e.g.
2408
2409\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002410>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2411>>> for name, phone in table.items():
2412... print '%-10s ==> %10d' % (name, phone)
2413...
2414Jack ==> 4098
2415Dcab ==> 8637678
2416Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002417\end{verbatim}
2418
Fred Drakeee84d591999-03-10 17:25:30 +00002419Most formats work exactly as in C and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002420type; however, if you don't you get an exception, not a core dump.
Fred Drakedb70d061998-11-17 21:59:04 +00002421The \code{\%s} format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002422not a string object, it is converted to string using the
2423\function{str()} built-in function. Using \code{*} to pass the width
2424or precision in as a separate (integer) argument is supported. The
Fred Drakeee84d591999-03-10 17:25:30 +00002425C formats \code{\%n} and \code{\%p} are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002426
2427If you have a really long format string that you don't want to split
2428up, it would be nice if you could reference the variables to be
2429formatted by name instead of by position. This can be done by using
Fred Drakeee84d591999-03-10 17:25:30 +00002430an extension of C formats using the form \code{\%(name)format}, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002431
2432\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002433>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2434>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2435Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002436\end{verbatim}
2437
2438This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002439\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002440local variables.
2441
Fred Drakeb7833d31998-09-11 16:21:55 +00002442\section{Reading and Writing Files \label{files}}
Fred Drake6c2176e1998-02-26 21:47:54 +00002443
Guido van Rossum02455691997-07-17 16:21:52 +00002444% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002445\function{open()}\bifuncindex{open} returns a file
2446object\obindex{file}, and is most commonly used with two arguments:
2447\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002448
Fred Drake8842e861998-02-13 07:16:30 +00002449\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002450>>> f=open('/tmp/workfile', 'w')
2451>>> print f
2452<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002453\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002454
Guido van Rossum02455691997-07-17 16:21:52 +00002455The first argument is a string containing the filename. The second
2456argument is another string containing a few characters describing the
2457way in which the file will be used. \var{mode} can be \code{'r'} when
2458the file will only be read, \code{'w'} for only writing (an existing
2459file with the same name will be erased), and \code{'a'} opens the file
2460for appending; any data written to the file is automatically added to
2461the end. \code{'r+'} opens the file for both reading and writing.
2462The \var{mode} argument is optional; \code{'r'} will be assumed if
2463it's omitted.
2464
Fred Drake391564f1998-04-01 23:11:56 +00002465On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00002466mode opens the file in binary mode, so there are also modes like
2467\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2468distinction between text and binary files; the end-of-line characters
2469in text files are automatically altered slightly when data is read or
2470written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002471\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2472\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00002473writing such files. (Note that the precise semantics of text mode on
Fred Drakeee84d591999-03-10 17:25:30 +00002474the Macintosh depends on the underlying C library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00002475
Fred Drakeb7833d31998-09-11 16:21:55 +00002476\subsection{Methods of File Objects \label{fileMethods}}
Guido van Rossum02455691997-07-17 16:21:52 +00002477
2478The rest of the examples in this section will assume that a file
2479object called \code{f} has already been created.
2480
2481To read a file's contents, call \code{f.read(\var{size})}, which reads
2482some quantity of data and returns it as a string. \var{size} is an
2483optional numeric argument. When \var{size} is omitted or negative,
2484the entire contents of the file will be read and returned; it's your
2485problem if the file is twice as large as your machine's memory.
2486Otherwise, at most \var{size} bytes are read and returned. If the end
2487of the file has been reached, \code{f.read()} will return an empty
2488string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002489\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002490>>> f.read()
2491'This is the entire file.\012'
2492>>> f.read()
2493''
Fred Drake8842e861998-02-13 07:16:30 +00002494\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002495
Guido van Rossum02455691997-07-17 16:21:52 +00002496\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002497character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002498omitted on the last line of the file if the file doesn't end in a
2499newline. This makes the return value unambiguous; if
2500\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002501been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002502string containing only a single newline.
2503
Fred Drake8842e861998-02-13 07:16:30 +00002504\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002505>>> f.readline()
2506'This is the first line of the file.\012'
2507>>> f.readline()
2508'Second line of the file\012'
2509>>> f.readline()
2510''
Fred Drake8842e861998-02-13 07:16:30 +00002511\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002512
Fred Drakeeee08cd1997-12-04 15:43:15 +00002513\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002514a list containing all the lines of data in the file.
2515
Fred Drake8842e861998-02-13 07:16:30 +00002516\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002517>>> f.readlines()
2518['This is the first line of the file.\012', 'Second line of the file\012']
Fred Drake8842e861998-02-13 07:16:30 +00002519\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002520
Guido van Rossum02455691997-07-17 16:21:52 +00002521\code{f.write(\var{string})} writes the contents of \var{string} to
2522the file, returning \code{None}.
2523
Fred Drake8842e861998-02-13 07:16:30 +00002524\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002525>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002526\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002527
Guido van Rossum02455691997-07-17 16:21:52 +00002528\code{f.tell()} returns an integer giving the file object's current
2529position in the file, measured in bytes from the beginning of the
2530file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002531\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002532computed from adding \var{offset} to a reference point; the reference
2533point is selected by the \var{from_what} argument. A \var{from_what}
2534value of 0 measures from the beginning of the file, 1 uses the current
2535file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002536\var{from_what} can be omitted and defaults to 0, using the beginning
2537of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002538
Fred Drake8842e861998-02-13 07:16:30 +00002539\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002540>>> f=open('/tmp/workfile', 'r+')
2541>>> f.write('0123456789abcdef')
2542>>> f.seek(5) # Go to the 5th byte in the file
2543>>> f.read(1)
2544'5'
2545>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2546>>> f.read(1)
2547'd'
Fred Drake8842e861998-02-13 07:16:30 +00002548\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002549
Guido van Rossum02455691997-07-17 16:21:52 +00002550When you're done with a file, call \code{f.close()} to close it and
2551free up any system resources taken up by the open file. After calling
2552\code{f.close()}, attempts to use the file object will automatically fail.
2553
Fred Drake8842e861998-02-13 07:16:30 +00002554\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002555>>> f.close()
2556>>> f.read()
2557Traceback (innermost last):
2558 File "<stdin>", line 1, in ?
2559ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002560\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002561
Fred Drake8842e861998-02-13 07:16:30 +00002562File objects have some additional methods, such as \method{isatty()}
2563and \method{truncate()} which are less frequently used; consult the
2564Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002565
Fred Drakeb7833d31998-09-11 16:21:55 +00002566\subsection{The \module{pickle} Module \label{pickle}}
Fred Drake391564f1998-04-01 23:11:56 +00002567\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00002568
2569Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002570bit more effort, since the \method{read()} method only returns
2571strings, which will have to be passed to a function like
2572\function{string.atoi()}, which takes a string like \code{'123'} and
2573returns its numeric value 123. However, when you want to save more
2574complex data types like lists, dictionaries, or class instances,
2575things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002576
2577Rather than have users be constantly writing and debugging code to
2578save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002579\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002580any Python object (even some forms of Python code!), and convert it to
2581a string representation; this process is called \dfn{pickling}.
2582Reconstructing the object from the string representation is called
2583\dfn{unpickling}. Between pickling and unpickling, the string
2584representing the object may have been stored in a file or data, or
2585sent over a network connection to some distant machine.
2586
2587If you have an object \code{x}, and a file object \code{f} that's been
2588opened for writing, the simplest way to pickle the object takes only
2589one line of code:
2590
Fred Drake8842e861998-02-13 07:16:30 +00002591\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002592pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002593\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002594
Fred Drake8842e861998-02-13 07:16:30 +00002595To unpickle the object again, if \code{f} is a file object which has
2596been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002597
Fred Drake8842e861998-02-13 07:16:30 +00002598\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002599x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002600\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002601
Guido van Rossum02455691997-07-17 16:21:52 +00002602(There are other variants of this, used when pickling many objects or
2603when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002604complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002605
Fred Drake8842e861998-02-13 07:16:30 +00002606\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002607stored and reused by other programs or by a future invocation of the
2608same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002609object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002610write Python extensions take care to ensure that new data types such
Fred Drake72389881998-04-13 01:31:10 +00002611as matrices can be properly pickled and unpickled.
Guido van Rossum02455691997-07-17 16:21:52 +00002612
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002613
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002614
Fred Drakeb7833d31998-09-11 16:21:55 +00002615\chapter{Errors and Exceptions \label{errors}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002616
2617Until now error messages haven't been more than mentioned, but if you
2618have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002619(at least) two distinguishable kinds of errors: \emph{syntax errors}
2620and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002621
Fred Drakeb7833d31998-09-11 16:21:55 +00002622\section{Syntax Errors \label{syntaxErrors}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002623
2624Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002625kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002626
Fred Drake8842e861998-02-13 07:16:30 +00002627\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002628>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002629 File "<stdin>", line 1
2630 while 1 print 'Hello world'
2631 ^
2632SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002633\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002634
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002635The parser repeats the offending line and displays a little `arrow'
2636pointing at the earliest point in the line where the error was detected.
2637The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002638\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002639the arrow: in the example, the error is detected at the keyword
Fred Drake391564f1998-04-01 23:11:56 +00002640\keyword{print}, since a colon (\character{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002641File name and line number are printed so you know where to look in case
2642the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002643
Fred Drakeb7833d31998-09-11 16:21:55 +00002644\section{Exceptions \label{exceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002645
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002646Even if a statement or expression is syntactically correct, it may
2647cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002648Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002649not unconditionally fatal: you will soon learn how to handle them in
2650Python programs. Most exceptions are not handled by programs,
2651however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002652
Fred Drake8842e861998-02-13 07:16:30 +00002653\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002654>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002655Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002656 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002657ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002658>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002659Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002660 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002661NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002662>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002663Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002664 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002665TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002666\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002667
Guido van Rossumb2c65561993-05-12 08:53:36 +00002668The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002669Exceptions come in different types, and the type is printed as part of
2670the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002671\exception{ZeroDivisionError},
2672\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002673and
Fred Drake8842e861998-02-13 07:16:30 +00002674\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002675The string printed as the exception type is the name of the built-in
2676name for the exception that occurred. This is true for all built-in
2677exceptions, but need not be true for user-defined exceptions (although
2678it is a useful convention).
2679Standard exception names are built-in identifiers (not reserved
2680keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002681
Guido van Rossumb2c65561993-05-12 08:53:36 +00002682The rest of the line is a detail whose interpretation depends on the
2683exception type; its meaning is dependent on the exception type.
2684
2685The preceding part of the error message shows the context where the
2686exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002687In general it contains a stack backtrace listing source lines; however,
2688it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002689
Fred Drake8842e861998-02-13 07:16:30 +00002690The Library Reference lists the built-in exceptions and their
2691meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002692
Fred Drakeb7833d31998-09-11 16:21:55 +00002693\section{Handling Exceptions \label{handling}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002694
2695It is possible to write programs that handle selected exceptions.
2696Look at the following example, which prints a table of inverses of
2697some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002698
Fred Drake8842e861998-02-13 07:16:30 +00002699\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002700>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002701>>> for x in numbers:
2702... print x,
2703... try:
2704... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002705... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002706... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002707...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000027080.3333 3.00030003
27092.5 0.4
27100 *** has no inverse ***
271110 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002712\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002713
Fred Drake8842e861998-02-13 07:16:30 +00002714The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002715\begin{itemize}
2716\item
Fred Drake8842e861998-02-13 07:16:30 +00002717First, the \emph{try clause}
2718(the statement(s) between the \keyword{try} and \keyword{except}
2719keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002720\item
2721If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002722\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002723is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002724\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002725If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002726the rest of the clause is skipped. Then if its type matches the
2727exception named after the \keyword{except} keyword, the rest of the
2728try clause is skipped, the except clause is executed, and then
2729execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002730\item
2731If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002732except clause, it is passed on to outer \keyword{try} statements; if
2733no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002734and execution stops with a message as shown above.
2735\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002736A \keyword{try} statement may have more than one except clause, to
2737specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002738At most one handler will be executed.
2739Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002740clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002741An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002742e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002743
Fred Drake8842e861998-02-13 07:16:30 +00002744\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002745... except (RuntimeError, TypeError, NameError):
2746... pass
Fred Drake8842e861998-02-13 07:16:30 +00002747\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002748
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002749The last except clause may omit the exception name(s), to serve as a
2750wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002751Use this with extreme caution, since it is easy to mask a real
2752programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002753
Fred Drake2900ff91999-08-24 22:14:57 +00002754Each exception clause must have at least one line of executable code
2755in the block. Comments are not executable code. If you want the
2756exception clause to do nothing, use the \keyword{pass} statement.
2757
Fred Drake8842e861998-02-13 07:16:30 +00002758The \keyword{try} \ldots\ \keyword{except} statement has an optional
2759\emph{else clause}, which must follow all except clauses. It is
2760useful to place code that must be executed if the try clause does not
2761raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002762
2763\begin{verbatim}
Guido van Rossuma4289a71998-07-07 20:18:06 +00002764for arg in sys.argv[1:]:
Fred Drake8842e861998-02-13 07:16:30 +00002765 try:
2766 f = open(arg, 'r')
2767 except IOError:
2768 print 'cannot open', arg
2769 else:
2770 print arg, 'has', len(f.readlines()), 'lines'
2771 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002772\end{verbatim}
2773
2774
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002775When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002776the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002777The presence and type of the argument depend on the exception type.
2778For exception types which have an argument, the except clause may
2779specify a variable after the exception name (or list) to receive the
2780argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002781
Fred Drake8842e861998-02-13 07:16:30 +00002782\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002783>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002784... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002785... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002786... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002787...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002788name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002789\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002790
Guido van Rossumb2c65561993-05-12 08:53:36 +00002791If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002792(`detail') of the message for unhandled exceptions.
2793
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002794Exception handlers don't just handle exceptions if they occur
2795immediately in the try clause, but also if they occur inside functions
2796that are called (even indirectly) in the try clause.
2797For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002798
Fred Drake8842e861998-02-13 07:16:30 +00002799\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002800>>> def this_fails():
2801... x = 1/0
2802...
2803>>> try:
2804... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002805... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002806... print 'Handling run-time error:', detail
2807...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002808Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002809\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002810
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002811
Fred Drakeb7833d31998-09-11 16:21:55 +00002812\section{Raising Exceptions \label{raising}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002813
Fred Drake8842e861998-02-13 07:16:30 +00002814The \keyword{raise} statement allows the programmer to force a
2815specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002816For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002817
Fred Drake8842e861998-02-13 07:16:30 +00002818\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002819>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002820Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002821 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002822NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002823\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002824
Fred Drake8842e861998-02-13 07:16:30 +00002825The first argument to \keyword{raise} names the exception to be
2826raised. The optional second argument specifies the exception's
2827argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002828
Guido van Rossum02455691997-07-17 16:21:52 +00002829
Fred Drakeb7833d31998-09-11 16:21:55 +00002830\section{User-defined Exceptions \label{userExceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002831
2832Programs may name their own exceptions by assigning a string to a
2833variable.
2834For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002835
Fred Drake8842e861998-02-13 07:16:30 +00002836\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002837>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002838>>> try:
2839... raise my_exc, 2*2
2840... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002841... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002842...
Guido van Rossum6938f061994-08-01 12:22:53 +00002843My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002844>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002845Traceback (innermost last):
2846 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002847my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002848\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002849
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002850Many standard modules use this to report errors that may occur in
2851functions they define.
2852
Guido van Rossum02455691997-07-17 16:21:52 +00002853
Fred Drakeb7833d31998-09-11 16:21:55 +00002854\section{Defining Clean-up Actions \label{cleanup}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002855
Fred Drake8842e861998-02-13 07:16:30 +00002856The \keyword{try} statement has another optional clause which is
2857intended to define clean-up actions that must be executed under all
2858circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002859
Fred Drake8842e861998-02-13 07:16:30 +00002860\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002861>>> try:
2862... raise KeyboardInterrupt
2863... finally:
2864... print 'Goodbye, world!'
2865...
2866Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002867Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002868 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002869KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002870\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002871
Fred Drake8842e861998-02-13 07:16:30 +00002872A \emph{finally clause} is executed whether or not an exception has
2873occurred in the try clause. When an exception has occurred, it is
2874re-raised after the finally clause is executed. The finally clause is
2875also executed ``on the way out'' when the \keyword{try} statement is
2876left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002877
Fred Drake8842e861998-02-13 07:16:30 +00002878A \keyword{try} statement must either have one or more except clauses
2879or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002880
Fred Drakeb7833d31998-09-11 16:21:55 +00002881\chapter{Classes \label{classes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002882
2883Python's class mechanism adds classes to the language with a minimum
2884of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002885found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002886do not put an absolute barrier between definition and user, but rather
2887rely on the politeness of the user not to ``break into the
2888definition.'' The most important features of classes are retained
2889with full power, however: the class inheritance mechanism allows
2890multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00002891base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002892same name. Objects can contain an arbitrary amount of private data.
2893
Guido van Rossum16d6e711994-08-08 12:30:22 +00002894In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002895\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002896no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002897shorthands for referencing the object's members from its methods: the
2898method function is declared with an explicit first argument
2899representing the object, which is provided implicitly by the call. As
2900in Smalltalk, classes themselves are objects, albeit in the wider
2901sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002902provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002903or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002904extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002905built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00002906subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002907
Fred Drakeb7833d31998-09-11 16:21:55 +00002908\section{A Word About Terminology \label{terminology}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002909
Fred Drake391564f1998-04-01 23:11:56 +00002910Lacking universally accepted terminology to talk about classes, I will
2911make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002912terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002913Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002914
2915I also have to warn you that there's a terminological pitfall for
2916object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002917necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2918unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00002919built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00002920exotic types like files aren't. However, \emph{all} Python types
2921share a little bit of common semantics that is best described by using
2922the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002923
2924Objects have individuality, and multiple names (in multiple scopes)
2925can be bound to the same object. This is known as aliasing in other
2926languages. This is usually not appreciated on a first glance at
2927Python, and can be safely ignored when dealing with immutable basic
2928types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002929(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002930objects such as lists, dictionaries, and most types representing
2931entities outside the program (files, windows, etc.). This is usually
2932used to the benefit of the program, since aliases behave like pointers
2933in some respects. For example, passing an object is cheap since only
2934a pointer is passed by the implementation; and if a function modifies
2935an object passed as an argument, the caller will see the change --- this
2936obviates the need for two different argument passing mechanisms as in
2937Pascal.
2938
2939
Fred Drakeb7833d31998-09-11 16:21:55 +00002940\section{Python Scopes and Name Spaces \label{scopes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002941
2942Before introducing classes, I first have to tell you something about
2943Python's scope rules. Class definitions play some neat tricks with
2944name spaces, and you need to know how scopes and name spaces work to
2945fully understand what's going on. Incidentally, knowledge about this
2946subject is useful for any advanced Python programmer.
2947
2948Let's begin with some definitions.
2949
Fred Drakeeee08cd1997-12-04 15:43:15 +00002950A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002951spaces are currently implemented as Python dictionaries, but that's
2952normally not noticeable in any way (except for performance), and it
2953may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002954built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002955names); the global names in a module; and the local names in a
2956function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002957also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002958spaces is that there is absolutely no relation between names in
2959different name spaces; for instance, two different modules may both
2960define a function ``maximize'' without confusion --- users of the
2961modules must prefix it with the module name.
2962
Fred Drakeeee08cd1997-12-04 15:43:15 +00002963By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002964dot --- for example, in the expression \code{z.real}, \code{real} is
2965an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002966names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002967\code{modname.funcname}, \code{modname} is a module object and
2968\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002969be a straightforward mapping between the module's attributes and the
Fred Drake93aa0f21999-04-05 21:39:17 +00002970global names defined in the module: they share the same name
2971space!\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002972 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002973 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002974 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002975 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002976 Obviously, using this violates the abstraction of name space
2977 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002978 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002979}
2980
2981Attributes may be read-only or writable. In the latter case,
2982assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002983you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drake391564f1998-04-01 23:11:56 +00002984also be deleted with the \keyword{del} statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002985\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002986
2987Name spaces are created at different moments and have different
2988lifetimes. The name space containing the built-in names is created
2989when the Python interpreter starts up, and is never deleted. The
2990global name space for a module is created when the module definition
2991is read in; normally, module name spaces also last until the
2992interpreter quits. The statements executed by the top-level
2993invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002994interactively, are considered part of a module called
2995\module{__main__}, so they have their own global name space. (The
2996built-in names actually also live in a module; this is called
2997\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002998
2999The local name space for a function is created when the function is
3000called, and deleted when the function returns or raises an exception
3001that is not handled within the function. (Actually, forgetting would
3002be a better way to describe what actually happens.) Of course,
3003recursive invocations each have their own local name space.
3004
Fred Drakeeee08cd1997-12-04 15:43:15 +00003005A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003006is directly accessible. ``Directly accessible'' here means that an
3007unqualified reference to a name attempts to find the name in the name
3008space.
3009
3010Although scopes are determined statically, they are used dynamically.
3011At any time during execution, exactly three nested scopes are in use
3012(i.e., exactly three name spaces are directly accessible): the
3013innermost scope, which is searched first, contains the local names,
3014the middle scope, searched next, contains the current module's global
3015names, and the outermost scope (searched last) is the name space
3016containing built-in names.
3017
3018Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00003019current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003020the same name space as the global scope: the module's name space.
3021Class definitions place yet another name space in the local scope.
3022
3023It is important to realize that scopes are determined textually: the
3024global scope of a function defined in a module is that module's name
3025space, no matter from where or by what alias the function is called.
3026On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00003027run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003028static name resolution, at ``compile'' time, so don't rely on dynamic
3029name resolution! (In fact, local variables are already determined
3030statically.)
3031
3032A special quirk of Python is that assignments always go into the
3033innermost scope. Assignments do not copy data --- they just
3034bind names to objects. The same is true for deletions: the statement
Fred Drake391564f1998-04-01 23:11:56 +00003035\samp{del x} removes the binding of \code{x} from the name space
3036referenced by the local scope. In fact, all operations that introduce
3037new names use the local scope: in particular, import statements and
3038function definitions bind the module or function name in the local
3039scope. (The \keyword{global} statement can be used to indicate that
3040particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003041
3042
Fred Drakeb7833d31998-09-11 16:21:55 +00003043\section{A First Look at Classes \label{firstClasses}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003044
3045Classes introduce a little bit of new syntax, three new object types,
3046and some new semantics.
3047
3048
Fred Drakeb7833d31998-09-11 16:21:55 +00003049\subsection{Class Definition Syntax \label{classDefinition}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003050
3051The simplest form of class definition looks like this:
3052
3053\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003054class ClassName:
3055 <statement-1>
3056 .
3057 .
3058 .
3059 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003060\end{verbatim}
3061
Fred Drake8842e861998-02-13 07:16:30 +00003062Class definitions, like function definitions (\keyword{def}
3063statements) must be executed before they have any effect. (You could
3064conceivably place a class definition in a branch of an \keyword{if}
3065statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003066
3067In practice, the statements inside a class definition will usually be
3068function definitions, but other statements are allowed, and sometimes
3069useful --- we'll come back to this later. The function definitions
3070inside a class normally have a peculiar form of argument list,
3071dictated by the calling conventions for methods --- again, this is
3072explained later.
3073
3074When a class definition is entered, a new name space is created, and
3075used as the local scope --- thus, all assignments to local variables
3076go into this new name space. In particular, function definitions bind
3077the name of the new function here.
3078
Fred Drakeeee08cd1997-12-04 15:43:15 +00003079When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003080object} is created. This is basically a wrapper around the contents
3081of the name space created by the class definition; we'll learn more
3082about class objects in the next section. The original local scope
3083(the one in effect just before the class definitions was entered) is
Fred Drakea594baf1998-04-03 05:16:31 +00003084reinstated, and the class object is bound here to the class name given
3085in the class definition header (\class{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003086
3087
Fred Drakeb7833d31998-09-11 16:21:55 +00003088\subsection{Class Objects \label{classObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003089
3090Class objects support two kinds of operations: attribute references
3091and instantiation.
3092
Fred Drakeeee08cd1997-12-04 15:43:15 +00003093\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00003094attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003095names are all the names that were in the class's name space when the
3096class object was created. So, if the class definition looked like
3097this:
3098
3099\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003100class MyClass:
3101 "A simple example class"
3102 i = 12345
3103 def f(x):
3104 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003105\end{verbatim}
3106
Fred Drake8842e861998-02-13 07:16:30 +00003107then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003108references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00003109Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00003110of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00003111attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00003112the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003113
Fred Drakeeee08cd1997-12-04 15:43:15 +00003114Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003115the class object is a parameterless function that returns a new
3116instance of the class. For example, (assuming the above class):
3117
3118\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003119x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003120\end{verbatim}
3121
Fred Drakeeee08cd1997-12-04 15:43:15 +00003122creates a new \emph{instance} of the class and assigns this object to
3123the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003124
3125
Fred Drakeb7833d31998-09-11 16:21:55 +00003126\subsection{Instance Objects \label{instanceObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003127
3128Now what can we do with instance objects? The only operations
3129understood by instance objects are attribute references. There are
3130two kinds of valid attribute names.
3131
Fred Drakeeee08cd1997-12-04 15:43:15 +00003132The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00003133``instance variables'' in Smalltalk, and to ``data members'' in
3134\Cpp{}. Data attributes need not be declared; like local variables,
3135they spring into existence when they are first assigned to. For
3136example, if \code{x} is the instance of \class{MyClass} created above,
3137the following piece of code will print the value \code{16}, without
3138leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003139
3140\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003141x.counter = 1
3142while x.counter < 10:
3143 x.counter = x.counter * 2
3144print x.counter
3145del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003146\end{verbatim}
3147
3148The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00003149are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003150object. (In Python, the term method is not unique to class instances:
3151other object types can have methods as well, e.g., list objects have
3152methods called append, insert, remove, sort, and so on. However,
3153below, we'll use the term method exclusively to mean methods of class
3154instance objects, unless explicitly stated otherwise.)
3155
3156Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00003157definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003158objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00003159example, \code{x.f} is a valid method reference, since
3160\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00003161\code{MyClass.i} is not. But \code{x.f} is not the same thing as
3162\code{MyClass.f} --- it is a \emph{method object}, not a function
Fred Drakea594baf1998-04-03 05:16:31 +00003163object.%
3164\obindex{method}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003165
3166
Fred Drakeb7833d31998-09-11 16:21:55 +00003167\subsection{Method Objects \label{methodObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003168
3169Usually, a method is called immediately, e.g.:
3170
3171\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003172x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003173\end{verbatim}
3174
Fred Drake8842e861998-02-13 07:16:30 +00003175In our example, this will return the string \code{'hello world'}.
Fred Drakeee84d591999-03-10 17:25:30 +00003176However, it is not necessary to call a method right away:
3177\code{x.f} is a method object, and can be stored away and called at a
3178later time. For example:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003179
3180\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003181xf = x.f
3182while 1:
3183 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003184\end{verbatim}
3185
Fred Drake8842e861998-02-13 07:16:30 +00003186will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003187
3188What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00003189that \code{x.f()} was called without an argument above, even though
3190the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003191happened to the argument? Surely Python raises an exception when a
3192function that requires an argument is called without any --- even if
3193the argument isn't actually used...
3194
3195Actually, you may have guessed the answer: the special thing about
3196methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00003197function. In our example, the call \code{x.f()} is exactly equivalent
3198to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00003199\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003200with an argument list that is created by inserting the method's object
3201before the first argument.
3202
3203If you still don't understand how methods work, a look at the
3204implementation can perhaps clarify matters. When an instance
3205attribute is referenced that isn't a data attribute, its class is
3206searched. If the name denotes a valid class attribute that is a
3207function object, a method object is created by packing (pointers to)
3208the instance object and the function object just found together in an
3209abstract object: this is the method object. When the method object is
3210called with an argument list, it is unpacked again, a new argument
3211list is constructed from the instance object and the original argument
3212list, and the function object is called with this new argument list.
3213
3214
Fred Drakeb7833d31998-09-11 16:21:55 +00003215\section{Random Remarks \label{remarks}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003216
3217[These should perhaps be placed more carefully...]
3218
3219
3220Data attributes override method attributes with the same name; to
3221avoid accidental name conflicts, which may cause hard-to-find bugs in
3222large programs, it is wise to use some kind of convention that
3223minimizes the chance of conflicts, e.g., capitalize method names,
3224prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00003225an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003226
3227
3228Data attributes may be referenced by methods as well as by ordinary
3229users (``clients'') of an object. In other words, classes are not
3230usable to implement pure abstract data types. In fact, nothing in
3231Python makes it possible to enforce data hiding --- it is all based
3232upon convention. (On the other hand, the Python implementation,
Fred Drakeee84d591999-03-10 17:25:30 +00003233written in C, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003234access to an object if necessary; this can be used by extensions to
Fred Drakeee84d591999-03-10 17:25:30 +00003235Python written in C.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003236
3237
3238Clients should use data attributes with care --- clients may mess up
3239invariants maintained by the methods by stamping on their data
3240attributes. Note that clients may add data attributes of their own to
3241an instance object without affecting the validity of the methods, as
3242long as name conflicts are avoided --- again, a naming convention can
3243save a lot of headaches here.
3244
3245
3246There is no shorthand for referencing data attributes (or other
3247methods!) from within methods. I find that this actually increases
3248the readability of methods: there is no chance of confusing local
3249variables and instance variables when glancing through a method.
3250
3251
3252Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00003253\code{self}. This is nothing more than a convention: the name
3254\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003255however, that by not following the convention your code may be less
3256readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00003257a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003258convention.)
3259
3260
3261Any function object that is a class attribute defines a method for
3262instances of that class. It is not necessary that the function
3263definition is textually enclosed in the class definition: assigning a
3264function object to a local variable in the class is also ok. For
3265example:
3266
3267\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003268# Function defined outside the class
3269def f1(self, x, y):
3270 return min(x, x+y)
3271
3272class C:
3273 f = f1
3274 def g(self):
3275 return 'hello world'
3276 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003277\end{verbatim}
3278
Fred Drake8842e861998-02-13 07:16:30 +00003279Now \code{f}, \code{g} and \code{h} are all attributes of class
3280\class{C} that refer to function objects, and consequently they are all
3281methods of instances of \class{C} --- \code{h} being exactly equivalent
3282to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003283the reader of a program.
3284
3285
3286Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00003287\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003288
3289\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003290class Bag:
3291 def empty(self):
3292 self.data = []
3293 def add(self, x):
3294 self.data.append(x)
3295 def addtwice(self, x):
3296 self.add(x)
3297 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003298\end{verbatim}
3299
3300
3301The instantiation operation (``calling'' a class object) creates an
3302empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00003303state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00003304\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003305
Guido van Rossum6938f061994-08-01 12:22:53 +00003306\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003307 def __init__(self):
3308 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00003309\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003310
Fred Drake8842e861998-02-13 07:16:30 +00003311When a class defines an \method{__init__()} method, class
3312instantiation automatically invokes \method{__init__()} for the
3313newly-created class instance. So in the \class{Bag} example, a new
3314and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003315
Guido van Rossum6938f061994-08-01 12:22:53 +00003316\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003317x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00003318\end{verbatim}
3319
Fred Drake8842e861998-02-13 07:16:30 +00003320Of course, the \method{__init__()} method may have arguments for
3321greater flexibility. In that case, arguments given to the class
3322instantiation operator are passed on to \method{__init__()}. For
3323example,
Guido van Rossum6938f061994-08-01 12:22:53 +00003324
Fred Drake8842e861998-02-13 07:16:30 +00003325\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00003326>>> class Complex:
3327... def __init__(self, realpart, imagpart):
3328... self.r = realpart
3329... self.i = imagpart
3330...
3331>>> x = Complex(3.0,-4.5)
3332>>> x.r, x.i
3333(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00003334\end{verbatim}
3335
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003336Methods may reference global names in the same way as ordinary
3337functions. The global scope associated with a method is the module
3338containing the class definition. (The class itself is never used as a
3339global scope!) While one rarely encounters a good reason for using
3340global data in a method, there are many legitimate uses of the global
3341scope: for one thing, functions and modules imported into the global
3342scope can be used by methods, as well as functions and classes defined
3343in it. Usually, the class containing the method is itself defined in
3344this global scope, and in the next section we'll find some good
3345reasons why a method would want to reference its own class!
3346
3347
Fred Drakeb7833d31998-09-11 16:21:55 +00003348\section{Inheritance \label{inheritance}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003349
3350Of course, a language feature would not be worthy of the name ``class''
3351without supporting inheritance. The syntax for a derived class
3352definition looks as follows:
3353
3354\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003355class DerivedClassName(BaseClassName):
3356 <statement-1>
3357 .
3358 .
3359 .
3360 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003361\end{verbatim}
3362
Fred Drake8842e861998-02-13 07:16:30 +00003363The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003364the derived class definition. Instead of a base class name, an
3365expression is also allowed. This is useful when the base class is
3366defined in another module, e.g.,
3367
3368\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003369class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003370\end{verbatim}
3371
3372Execution of a derived class definition proceeds the same as for a
3373base class. When the class object is constructed, the base class is
3374remembered. This is used for resolving attribute references: if a
3375requested attribute is not found in the class, it is searched in the
3376base class. This rule is applied recursively if the base class itself
3377is derived from some other class.
3378
3379There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00003380\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003381references are resolved as follows: the corresponding class attribute
3382is searched, descending down the chain of base classes if necessary,
3383and the method reference is valid if this yields a function object.
3384
3385Derived classes may override methods of their base classes. Because
3386methods have no special privileges when calling other methods of the
3387same object, a method of a base class that calls another method
3388defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003389a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003390in Python are ``virtual functions''.)
3391
3392An overriding method in a derived class may in fact want to extend
3393rather than simply replace the base class method of the same name.
3394There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003395call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003396occasionally useful to clients as well. (Note that this only works if
3397the base class is defined or imported directly in the global scope.)
3398
3399
Fred Drakeb7833d31998-09-11 16:21:55 +00003400\subsection{Multiple Inheritance \label{multiple}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003401
Guido van Rossum6938f061994-08-01 12:22:53 +00003402Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003403class definition with multiple base classes looks as follows:
3404
3405\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003406class DerivedClassName(Base1, Base2, Base3):
3407 <statement-1>
3408 .
3409 .
3410 .
3411 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003412\end{verbatim}
3413
3414The only rule necessary to explain the semantics is the resolution
3415rule used for class attribute references. This is depth-first,
3416left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003417\class{DerivedClassName}, it is searched in \class{Base1}, then
3418(recursively) in the base classes of \class{Base1}, and only if it is
3419not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003420
Fred Drake8842e861998-02-13 07:16:30 +00003421(To some people breadth first --- searching \class{Base2} and
3422\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003423natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003424attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003425one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003426a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003427rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003428\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003429
3430It is clear that indiscriminate use of multiple inheritance is a
3431maintenance nightmare, given the reliance in Python on conventions to
3432avoid accidental name conflicts. A well-known problem with multiple
3433inheritance is a class derived from two classes that happen to have a
3434common base class. While it is easy enough to figure out what happens
3435in this case (the instance will have a single copy of ``instance
3436variables'' or data attributes used by the common base class), it is
3437not clear that these semantics are in any way useful.
3438
3439
Fred Drakeb7833d31998-09-11 16:21:55 +00003440\section{Private Variables \label{private}}
Guido van Rossum02455691997-07-17 16:21:52 +00003441
Fred Drakea594baf1998-04-03 05:16:31 +00003442There is limited support for class-private
Guido van Rossum02455691997-07-17 16:21:52 +00003443identifiers. Any identifier of the form \code{__spam} (at least two
3444leading underscores, at most one trailing underscore) is now textually
3445replaced with \code{_classname__spam}, where \code{classname} is the
3446current class name with leading underscore(s) stripped. This mangling
3447is done without regard of the syntactic position of the identifier, so
3448it can be used to define class-private instance and class variables,
3449methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003450private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003451may occur when the mangled name would be longer than 255 characters.
3452Outside classes, or when the class name consists of only underscores,
3453no mangling occurs.
3454
3455Name mangling is intended to give classes an easy way to define
3456``private'' instance variables and methods, without having to worry
3457about instance variables defined by derived classes, or mucking with
3458instance variables by code outside the class. Note that the mangling
3459rules are designed mostly to avoid accidents; it still is possible for
3460a determined soul to access or modify a variable that is considered
3461private. This can even be useful, e.g. for the debugger, and that's
3462one reason why this loophole is not closed. (Buglet: derivation of a
3463class with the same name as the base class makes use of private
3464variables of the base class possible.)
3465
3466Notice that code passed to \code{exec}, \code{eval()} or
3467\code{evalfile()} does not consider the classname of the invoking
3468class to be the current class; this is similar to the effect of the
3469\code{global} statement, the effect of which is likewise restricted to
3470code that is byte-compiled together. The same restriction applies to
3471\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3472when referencing \code{__dict__} directly.
3473
3474Here's an example of a class that implements its own
3475\code{__getattr__} and \code{__setattr__} methods and stores all
3476attributes in a private variable, in a way that works in Python 1.4 as
3477well as in previous versions:
3478
3479\begin{verbatim}
3480class VirtualAttributes:
3481 __vdict = None
3482 __vdict_name = locals().keys()[0]
3483
3484 def __init__(self):
3485 self.__dict__[self.__vdict_name] = {}
3486
3487 def __getattr__(self, name):
3488 return self.__vdict[name]
3489
3490 def __setattr__(self, name, value):
3491 self.__vdict[name] = value
3492\end{verbatim}
3493
Fred Drakeaf8a0151998-01-14 14:51:31 +00003494%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003495%potential problems, refrain from using identifiers starting with
3496%double underscore except for predefined uses like \code{__init__}. To
3497%use private names while maintaining future compatibility: refrain from
3498%using the same private name in classes related via subclassing; avoid
3499%explicit (manual) mangling/unmangling; and assume that at some point
3500%in the future, leading double underscore will revert to being just a
3501%naming convention. Discussion on extensive compile-time declarations
3502%are currently underway, and it is impossible to predict what solution
3503%will eventually be chosen for private names. Double leading
3504%underscore is still a candidate, of course --- just not the only one.
3505%It is placed in the distribution in the belief that it is useful, and
3506%so that widespread experience with its use can be gained. It will not
3507%be removed without providing a better solution and a migration path.
3508
Fred Drakeb7833d31998-09-11 16:21:55 +00003509\section{Odds and Ends \label{odds}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003510
3511Sometimes it is useful to have a data type similar to the Pascal
Fred Drakeee84d591999-03-10 17:25:30 +00003512``record'' or C ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003513items. An empty class definition will do nicely, e.g.:
3514
3515\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003516class Employee:
3517 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003518
Fred Drake8842e861998-02-13 07:16:30 +00003519john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003520
Fred Drake8842e861998-02-13 07:16:30 +00003521# Fill the fields of the record
3522john.name = 'John Doe'
3523john.dept = 'computer lab'
3524john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003525\end{verbatim}
3526
3527
3528A piece of Python code that expects a particular abstract data type
3529can often be passed a class that emulates the methods of that data
3530type instead. For instance, if you have a function that formats some
3531data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003532\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00003533buffer instead, and pass it as an argument.% (Unfortunately, this
3534%technique has its limitations: a class can't define operations that
3535%are accessed by special syntax such as sequence subscripting or
3536%arithmetic operators, and assigning such a ``pseudo-file'' to
3537%\code{sys.stdin} will not cause the interpreter to read further input
3538%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003539
3540
Fred Drake8842e861998-02-13 07:16:30 +00003541Instance method objects have attributes, too: \code{m.im_self} is the
3542object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003543function object corresponding to the method.
3544
Fred Drakeb7833d31998-09-11 16:21:55 +00003545\subsection{Exceptions Can Be Classes \label{exceptionClasses}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003546
3547User-defined exceptions are no longer limited to being string objects
3548--- they can be identified by classes as well. Using this mechanism it
3549is possible to create extensible hierarchies of exceptions.
3550
3551There are two new valid (semantic) forms for the raise statement:
3552
3553\begin{verbatim}
3554raise Class, instance
3555
3556raise instance
3557\end{verbatim}
3558
Fred Drake8842e861998-02-13 07:16:30 +00003559In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003560or of a class derived from it. The second form is a shorthand for
3561
3562\begin{verbatim}
3563raise instance.__class__, instance
3564\end{verbatim}
3565
3566An except clause may list classes as well as string objects. A class
3567in an except clause is compatible with an exception if it is the same
3568class or a base class thereof (but not the other way around --- an
3569except clause listing a derived class is not compatible with a base
3570class). For example, the following code will print B, C, D in that
3571order:
3572
3573\begin{verbatim}
3574class B:
3575 pass
3576class C(B):
3577 pass
3578class D(C):
3579 pass
3580
3581for c in [B, C, D]:
3582 try:
3583 raise c()
3584 except D:
3585 print "D"
3586 except C:
3587 print "C"
3588 except B:
3589 print "B"
3590\end{verbatim}
3591
Fred Drakeee84d591999-03-10 17:25:30 +00003592Note that if the except clauses were reversed (with
3593\samp{except B} first), it would have printed B, B, B --- the first
3594matching except clause is triggered.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003595
3596When an error message is printed for an unhandled exception which is a
3597class, the class name is printed, then a colon and a space, and
3598finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003599\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003600
Guido van Rossum194e57c1995-02-15 15:51:38 +00003601
Fred Drakeb7833d31998-09-11 16:21:55 +00003602\chapter{What Now? \label{whatNow}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003603
Guido van Rossum02455691997-07-17 16:21:52 +00003604Hopefully reading this tutorial has reinforced your interest in using
3605Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003606
Guido van Rossum02455691997-07-17 16:21:52 +00003607You should read, or at least page through, the Library Reference,
3608which gives complete (though terse) reference material about types,
3609functions, and modules that can save you a lot of time when writing
3610Python programs. The standard Python distribution includes a
Fred Drakeee84d591999-03-10 17:25:30 +00003611\emph{lot} of code in both C and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003612\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3613numbers, parse command-line options, write CGI programs, compress
3614data, and a lot more; skimming through the Library Reference will give
3615you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003616
Fred Drakeca6567f1998-01-22 20:44:18 +00003617The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003618code, documentation, and pointers to Python-related pages around the
Fred Drake391564f1998-04-01 23:11:56 +00003619Web. This web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00003620world, such as Europe, Japan, and Australia; a mirror may be faster
3621than the main site, depending on your geographical location. A more
Fred Drakec0fcbc11999-04-29 02:30:04 +00003622informal site is \url{http://starship.python.net/}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003623bunch of Python-related personal home pages; many people have
Fred Drakec0fcbc11999-04-29 02:30:04 +00003624downloadable software there.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003625
Guido van Rossum02455691997-07-17 16:21:52 +00003626For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00003627newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
3628list at \email{python-list@cwi.nl}. The newsgroup and mailing list
3629are gatewayed, so messages posted to one will automatically be
3630forwarded to the other. There are around 35--45 postings a day,
3631% Postings figure based on average of last six months activity as
3632% reported by www.findmail.com; Oct. '97 - Mar. '98: 7480 msgs / 182
3633% days = 41.1 msgs / day.
3634asking (and answering) questions, suggesting new features, and
3635announcing new modules. Before posting, be sure to check the list of
3636Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003637\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3638\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003639answers many of the questions that come up again and again, and may
3640already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003641
Guido van Rossum02455691997-07-17 16:21:52 +00003642You can support the Python community by joining the Python Software
3643Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003644organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003645information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003646
Guido van Rossum194e57c1995-02-15 15:51:38 +00003647
Fred Drakea594baf1998-04-03 05:16:31 +00003648\appendix
Guido van Rossum194e57c1995-02-15 15:51:38 +00003649
Fred Drakeb7833d31998-09-11 16:21:55 +00003650\chapter{Interactive Input Editing and History Substitution
3651 \label{interacting}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003652
Guido van Rossum02455691997-07-17 16:21:52 +00003653Some versions of the Python interpreter support editing of the current
3654input line and history substitution, similar to facilities found in
3655the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003656\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003657editing. This library has its own documentation which I won't
Fred Drakecc09e8d1998-12-28 21:21:36 +00003658duplicate here; however, the basics are easily explained. The
3659interactive editing and history described here are optionally
3660available in the \UNIX{} and CygWin versions of the interpreter.
3661
3662This chapter does \emph{not} document the editing facilities of Mark
3663Hammond's PythonWin package or the Tk-based environment, IDLE,
3664distributed with Python. The command line history recall which
3665operates within DOS boxes on NT and some other DOS and Windows flavors
3666is yet another beast.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003667
Fred Drakeb7833d31998-09-11 16:21:55 +00003668\section{Line Editing \label{lineEditing}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003669
Guido van Rossum02455691997-07-17 16:21:52 +00003670If supported, input line editing is active whenever the interpreter
3671prints a primary or secondary prompt. The current line can be edited
3672using the conventional Emacs control characters. The most important
3673of these are: C-A (Control-A) moves the cursor to the beginning of the
3674line, C-E to the end, C-B moves it one position to the left, C-F to
3675the right. Backspace erases the character to the left of the cursor,
3676C-D the character to its right. C-K kills (erases) the rest of the
3677line to the right of the cursor, C-Y yanks back the last killed
3678string. C-underscore undoes the last change you made; it can be
3679repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003680
Fred Drakeb7833d31998-09-11 16:21:55 +00003681\section{History Substitution \label{history}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003682
Guido van Rossum02455691997-07-17 16:21:52 +00003683History substitution works as follows. All non-empty input lines
3684issued are saved in a history buffer, and when a new prompt is given
3685you are positioned on a new line at the bottom of this buffer. C-P
3686moves one line up (back) in the history buffer, C-N moves one down.
3687Any line in the history buffer can be edited; an asterisk appears in
3688front of the prompt to mark a line as modified. Pressing the Return
3689key passes the current line to the interpreter. C-R starts an
3690incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003691
Fred Drakeb7833d31998-09-11 16:21:55 +00003692\section{Key Bindings \label{keyBindings}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003693
Guido van Rossum02455691997-07-17 16:21:52 +00003694The key bindings and some other parameters of the Readline library can
3695be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003696\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003697
Fred Drake8842e861998-02-13 07:16:30 +00003698\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003699key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003700\end{verbatim}
3701
Guido van Rossum02455691997-07-17 16:21:52 +00003702or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003703
Fred Drake8842e861998-02-13 07:16:30 +00003704\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003705"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003706\end{verbatim}
3707
Guido van Rossum02455691997-07-17 16:21:52 +00003708and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003709
Fred Drake8842e861998-02-13 07:16:30 +00003710\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003711set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003712\end{verbatim}
3713
Guido van Rossum02455691997-07-17 16:21:52 +00003714For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003715
Fred Drake8842e861998-02-13 07:16:30 +00003716\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003717# I prefer vi-style editing:
3718set editing-mode vi
3719# Edit using a single line:
3720set horizontal-scroll-mode On
3721# Rebind some keys:
3722Meta-h: backward-kill-word
3723"\C-u": universal-argument
3724"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003725\end{verbatim}
3726
Guido van Rossum02455691997-07-17 16:21:52 +00003727Note that the default binding for TAB in Python is to insert a TAB
3728instead of Readline's default filename completion function. If you
3729insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003730
Fred Drake8842e861998-02-13 07:16:30 +00003731\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003732TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003733\end{verbatim}
3734
Fred Drakeeee08cd1997-12-04 15:43:15 +00003735in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003736indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003737
Fred Drake72389881998-04-13 01:31:10 +00003738Automatic completion of variable and module names is optionally
3739available. To enable it in the interpreter's interactive mode, add
Fred Drakeee84d591999-03-10 17:25:30 +00003740the following to your \file{\$HOME/.pythonrc.py} file:% $ <- bow to font-lock
3741\indexii{.pythonrc.py}{file}
3742\refstmodindex{rlcompleter}
Fred Drake72389881998-04-13 01:31:10 +00003743\refbimodindex{readline}
3744
3745\begin{verbatim}
3746import rlcompleter, readline
3747readline.parse_and_bind('tab: complete')
3748\end{verbatim}
3749
3750This binds the TAB key to the completion function, so hitting the TAB
3751key twice suggests completions; it looks at Python statement names,
3752the current local variables, and the available module names. For
3753dotted expressions such as \code{string.a}, it will evaluate the the
3754expression up to the final \character{.} and then suggest completions
3755from the attributes of the resulting object. Note that this may
3756execute application-defined code if an object with a
3757\method{__getattr__()} method is part of the expression.
3758
3759
Fred Drakeb7833d31998-09-11 16:21:55 +00003760\section{Commentary \label{commentary}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003761
Guido van Rossum02455691997-07-17 16:21:52 +00003762This facility is an enormous step forward compared to previous
3763versions of the interpreter; however, some wishes are left: It would
3764be nice if the proper indentation were suggested on continuation lines
3765(the parser knows if an indent token is required next). The
3766completion mechanism might use the interpreter's symbol table. A
3767command to check (or even suggest) matching parentheses, quotes etc.
3768would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003769
Fred Drake8842e861998-02-13 07:16:30 +00003770% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003771
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003772\end{document}