blob: 11434c46ef42578a1740c2b2f3547420d9359be8 [file] [log] [blame]
Fred Drake6659c301998-03-03 22:02:19 +00001\documentclass{manual}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002
Guido van Rossum02455691997-07-17 16:21:52 +00003% Things to do:
4% Add a section on file I/O
5% Write a chapter entitled ``Some Useful Modules''
6% --regex, math+cmath
7% Should really move the Python startup file info to an appendix
Guido van Rossum02455691997-07-17 16:21:52 +00008
Guido van Rossumdccc2981997-12-30 04:40:25 +00009\title{Python Tutorial}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010
Guido van Rossum16cd7f91994-10-06 10:29:26 +000011\input{boilerplate}
Guido van Rossum83eb9621993-11-23 16:28:45 +000012
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000013\begin{document}
14
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000015\maketitle
16
Fred Drake9f86b661998-07-28 21:55:19 +000017\ifhtml
18\chapter*{Front Matter\label{front}}
19\fi
20
Guido van Rossum16cd7f91994-10-06 10:29:26 +000021\input{copyright}
22
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000023\begin{abstract}
24
25\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000026Python is an easy to learn, powerful programming language. It has
27efficient high-level data structures and a simple but effective
28approach to object-oriented programming. Python's elegant syntax and
29dynamic typing, together with its interpreted nature, make it an ideal
30language for scripting and rapid application development in many areas
31on most platforms.
32
33The Python interpreter and the extensive standard library are freely
34available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000035Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000036distributed. The same site also contains distributions of and
37pointers to many free third party Python modules, programs and tools,
38and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000039
Guido van Rossum4410c751991-06-04 20:22:18 +000040The Python interpreter is easily extended with new functions and data
Fred Drakeee84d591999-03-10 17:25:30 +000041types implemented in C or \Cpp{} (or other languages callable from C).
Guido van Rossumdccc2981997-12-30 04:40:25 +000042Python is also suitable as an extension language for customizable
43applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000044
Guido van Rossum6fc178f1991-08-16 09:13:42 +000045This tutorial introduces the reader informally to the basic concepts
46and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000047Python interpreter handy for hands-on experience, but all examples are
48self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000049
Guido van Rossumdccc2981997-12-30 04:40:25 +000050For a description of standard objects and modules, see the
51\emph{Python Library Reference} document. The \emph{Python Reference
52Manual} gives a more formal definition of the language. To write
Fred Drakeee84d591999-03-10 17:25:30 +000053extensions in C or \Cpp{}, read the \emph{Extending and Embedding} and
54\emph{Python/C API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000055Python in depth.
56
57This tutorial does not attempt to be comprehensive and cover every
58single feature, or even every commonly used feature. Instead, it
59introduces many of Python's most noteworthy features, and will give
60you a good idea of the language's flavor and style. After reading it,
61you will be able to read and write Python modules and programs, and
62you will be ready to learn more about the various Python library
63modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000064
65\end{abstract}
66
Fred Drake4d4f9e71998-01-13 22:25:02 +000067\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000068
Guido van Rossum5e0759d1992-08-07 16:06:24 +000069
Fred Drakeb7833d31998-09-11 16:21:55 +000070\chapter{Whetting Your Appetite \label{intro}}
Guido van Rossum3a26dd81996-10-24 22:12:48 +000071
Guido van Rossum6fc178f1991-08-16 09:13:42 +000072If you ever wrote a large shell script, you probably know this
73feeling: you'd love to add yet another feature, but it's already so
74slow, and so big, and so complicated; or the feature involves a system
Fred Drakeee84d591999-03-10 17:25:30 +000075call or other function that is only accessible from C \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000076the problem at hand isn't serious enough to warrant rewriting the
Fred Drakeee84d591999-03-10 17:25:30 +000077script in C; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000078other data types (like sorted lists of file names) that are easy in
Fred Drakeee84d591999-03-10 17:25:30 +000079the shell but lots of work to implement in C, or perhaps you're not
80sufficiently familiar with C.
Guido van Rossum02455691997-07-17 16:21:52 +000081
Fred Drakeee84d591999-03-10 17:25:30 +000082Another situation: perhaps you have to work with several C libraries,
83and the usual C write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000084need to develop software more quickly. Possibly perhaps you've
85written a program that could use an extension language, and you don't
86want to design a language, write and debug an interpreter for it, then
87tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000088
Guido van Rossum6fc178f1991-08-16 09:13:42 +000089In such cases, Python may be just the language for you. Python is
90simple to use, but it is a real programming language, offering much
91more structure and support for large programs than the shell has. On
Fred Drakeee84d591999-03-10 17:25:30 +000092the other hand, it also offers much more error checking than C, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000093being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000094built in, such as flexible arrays and dictionaries that would cost you
Fred Drakeee84d591999-03-10 17:25:30 +000095days to implement efficiently in C. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000096types Python is applicable to a much larger problem domain than
97\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
98in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000099
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000100Python allows you to split up your program in modules that can be
101reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000102standard modules that you can use as the basis of your programs --- or
103as examples to start learning to program in Python. There are also
104built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000105sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000106
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000107Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000108during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000109necessary. The interpreter can be used interactively, which makes it
110easy to experiment with features of the language, to write throw-away
111programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000112It is also a handy desk calculator.
113
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000114Python allows writing very compact and readable programs. Programs
Fred Drakeee84d591999-03-10 17:25:30 +0000115written in Python are typically much shorter than equivalent C
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000116programs, for several reasons:
117\begin{itemize}
118\item
119the high-level data types allow you to express complex operations in a
120single statement;
121\item
122statement grouping is done by indentation instead of begin/end
123brackets;
124\item
125no variable or argument declarations are necessary.
126\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000127
Fred Drakeee84d591999-03-10 17:25:30 +0000128Python is \emph{extensible}: if you know how to program in C it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000129to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000130perform critical operations at maximum speed, or to link Python
131programs to libraries that may only be available in binary form (such
132as a vendor-specific graphics library). Once you are really hooked,
Fred Drakeee84d591999-03-10 17:25:30 +0000133you can link the Python interpreter into an application written in C
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000134and use it as an extension or command language for that application.
135
Guido van Rossum02455691997-07-17 16:21:52 +0000136By the way, the language is named after the BBC show ``Monty Python's
137Flying Circus'' and has nothing to do with nasty reptiles. Making
138references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000139it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000140
Fred Drakeb7833d31998-09-11 16:21:55 +0000141\section{Where From Here \label{where}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000142
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000143Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000144in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000145using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000146
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000147In the next chapter, the mechanics of using the interpreter are
148explained. This is rather mundane information, but essential for
149trying out the examples shown later.
150
Guido van Rossum4410c751991-06-04 20:22:18 +0000151The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000152language and system though examples, beginning with simple
153expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000154and finally touching upon advanced concepts like exceptions
155and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000156
Fred Drakeb7833d31998-09-11 16:21:55 +0000157\chapter{Using the Python Interpreter \label{using}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000158
Fred Drakeb7833d31998-09-11 16:21:55 +0000159\section{Invoking the Interpreter \label{invoking}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000160
Fred Drakeeee08cd1997-12-04 15:43:15 +0000161The Python interpreter is usually installed as \file{/usr/local/bin/python}
162on those machines where it is available; putting \file{/usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000163your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000164typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000165
Fred Drake8842e861998-02-13 07:16:30 +0000166\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000167python
Fred Drake8842e861998-02-13 07:16:30 +0000168\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000169
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000170to the shell. Since the choice of the directory where the interpreter
171lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000172your local Python guru or system administrator. (E.g.,
173\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000174
Guido van Rossuma8a1b9b1998-06-22 14:28:39 +0000175Typing an EOF character (Control-D on \UNIX{}, Control-Z on DOS
Guido van Rossum02455691997-07-17 16:21:52 +0000176or Windows) at the primary prompt causes the interpreter to exit with
177a zero exit status. If that doesn't work, you can exit the
Fred Drake8842e861998-02-13 07:16:30 +0000178interpreter by typing the following commands: \samp{import sys;
Guido van Rossum02455691997-07-17 16:21:52 +0000179sys.exit()}.
180
181The interpreter's line-editing features usually aren't very
Fred Drake3f205921998-01-13 18:56:38 +0000182sophisticated. On \UNIX{}, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000183enabled support for the GNU readline library, which adds more
184elaborate interactive editing and history features. Perhaps the
185quickest check to see whether command line editing is supported is
186typing Control-P to the first Python prompt you get. If it beeps, you
187have command line editing; see Appendix A for an introduction to the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000188keys. If nothing appears to happen, or if \code{\^P} is echoed,
Guido van Rossum02455691997-07-17 16:21:52 +0000189command line editing isn't available; you'll only be able to use
190backspace to remove characters from the current line.
191
Fred Drake6dc2aae1996-12-13 21:56:03 +0000192The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000193with standard input connected to a tty device, it reads and executes
194commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000195a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000196that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000197
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000198A third way of starting the interpreter is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000199\samp{python -c command [arg] ...}, which
200executes the statement(s) in \code{command}, analogous to the shell's
201\code{-c} option. Since Python statements often contain spaces or other
202characters that are special to the shell, it is best to quote
203\code{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000204
Fred Drakeeee08cd1997-12-04 15:43:15 +0000205Note that there is a difference between \samp{python file} and
206\samp{python <file}. In the latter case, input requests from the
207program, such as calls to \code{input()} and \code{raw_input()}, are
208satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000209until the end by the parser before the program starts executing, the
210program will encounter EOF immediately. In the former case (which is
211usually what you want) they are satisfied from whatever file or device
212is connected to standard input of the Python interpreter.
213
Guido van Rossumb2c65561993-05-12 08:53:36 +0000214When a script file is used, it is sometimes useful to be able to run
215the script and enter interactive mode afterwards. This can be done by
Fred Drakeeee08cd1997-12-04 15:43:15 +0000216passing \code{-i} before the script. (This does not work if the script
Guido van Rossumb2c65561993-05-12 08:53:36 +0000217is read from standard input, for the same reason as explained in the
218previous paragraph.)
219
Fred Drakeb7833d31998-09-11 16:21:55 +0000220\subsection{Argument Passing \label{argPassing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000221
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000222When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000223arguments thereafter are passed to the script in the variable
224\code{sys.argv}, which is a list of strings. Its length is at least
225one; when no script and no arguments are given, \code{sys.argv[0]} is
226an empty string. When the script name is given as \code{'-'} (meaning
227standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c
228command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options
229found after \code{-c command} are not consumed by the Python
230interpreter's option processing but left in \code{sys.argv} for the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000231command to handle.
232
Fred Drakeb7833d31998-09-11 16:21:55 +0000233\subsection{Interactive Mode \label{interactive}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000234
Guido van Rossumdd010801991-06-07 14:31:11 +0000235When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000236\emph{interactive mode}. In this mode it prompts for the next command
237with the \emph{primary prompt}, usually three greater-than signs
Fred Drake8842e861998-02-13 07:16:30 +0000238(\samp{>>> }); for continuation lines it prompts with the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000239\emph{secondary prompt},
Fred Drake8842e861998-02-13 07:16:30 +0000240by default three dots (\samp{... }).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000241
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000242The interpreter prints a welcome message stating its version number
243and a copyright notice before printing the first prompt, e.g.:
244
Fred Drake8842e861998-02-13 07:16:30 +0000245\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000246python
Fred Drakeee84d591999-03-10 17:25:30 +0000247Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5
Fred Drakeeee08cd1997-12-04 15:43:15 +0000248Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000249>>>
Fred Drake8842e861998-02-13 07:16:30 +0000250\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000251
Fred Drakeb7833d31998-09-11 16:21:55 +0000252\section{The Interpreter and Its Environment \label{interp}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000253
Fred Drakeb7833d31998-09-11 16:21:55 +0000254\subsection{Error Handling \label{error}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000255
256When an error occurs, the interpreter prints an error
257message and a stack trace. In interactive mode, it then returns to
258the primary prompt; when input came from a file, it exits with a
259nonzero exit status after printing
Fred Drakeeee08cd1997-12-04 15:43:15 +0000260the stack trace. (Exceptions handled by an \code{except} clause in a
261\code{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000262unconditionally fatal and cause an exit with a nonzero exit; this
263applies to internal inconsistencies and some cases of running out of
264memory. All error messages are written to the standard error stream;
265normal output from the executed commands is written to standard
266output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000267
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000268Typing the interrupt character (usually Control-C or DEL) to the
269primary or secondary prompt cancels the input and returns to the
270primary prompt.%
271\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000272 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000273}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000274Typing an interrupt while a command is executing raises the
275\code{KeyboardInterrupt} exception, which may be handled by a
276\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000277
Fred Drakeb7833d31998-09-11 16:21:55 +0000278\subsection{Executable Python Scripts \label{scripts}}
Guido van Rossum4410c751991-06-04 20:22:18 +0000279
Fred Drake6dc2aae1996-12-13 21:56:03 +0000280On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000281executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000282
Fred Drake8842e861998-02-13 07:16:30 +0000283\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000284#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000285\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000286
Fred Drake391564f1998-04-01 23:11:56 +0000287(assuming that the interpreter is on the user's \envvar{PATH}) at the
288beginning of the script and giving the file an executable mode. The
289\samp{\#!} must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000290
Fred Drakeb7833d31998-09-11 16:21:55 +0000291\subsection{The Interactive Startup File \label{startup}}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000292
Fred Drake8842e861998-02-13 07:16:30 +0000293% XXX This should probably be dumped in an appendix, since most people
294% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000295
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000296When you use Python interactively, it is frequently handy to have some
297standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000298can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000299\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drakeeee08cd1997-12-04 15:43:15 +0000300commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000301shells.
302
303This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000304commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000305explicit source of commands (which otherwise behaves like an
306interactive session). It is executed in the same name space where
307interactive commands are executed, so that objects that it defines or
308imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000309You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000310this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000311
312If you want to read an additional start-up file from the current
Fred Drake72389881998-04-13 01:31:10 +0000313directory, you can program this in the global start-up file,
Fred Drakeee84d591999-03-10 17:25:30 +0000314e.g.\ \samp{execfile('.pythonrc.py')}\indexii{.pythonrc.py}{file}. If
Fred Drake72389881998-04-13 01:31:10 +0000315you want to use the startup file in a script, you must do this
316explicitly in the script:
Fred Drake8842e861998-02-13 07:16:30 +0000317
318\begin{verbatim}
319import os
Fred Drakeee84d591999-03-10 17:25:30 +0000320if os.environ.get('PYTHONSTARTUP') \
321 and os.path.isfile(os.environ['PYTHONSTARTUP']):
Fred Drake72389881998-04-13 01:31:10 +0000322 execfile(os.environ['PYTHONSTARTUP'])
Fred Drake8842e861998-02-13 07:16:30 +0000323\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000324
Fred Drake72389881998-04-13 01:31:10 +0000325
Fred Drakeb7833d31998-09-11 16:21:55 +0000326\chapter{An Informal Introduction to Python \label{informal}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000327
328In the following examples, input and output are distinguished by the
Fred Drake8842e861998-02-13 07:16:30 +0000329presence or absence of prompts (\samp{>>> } and \samp{... }): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000330the example, you must type everything after the prompt, when the
331prompt appears; lines that do not begin with a prompt are output from
332the interpreter.%
Guido van Rossum02455691997-07-17 16:21:52 +0000333%\footnote{
334% I'd prefer to use different fonts to distinguish input
335% from output, but the amount of LaTeX hacking that would require
336% is currently beyond my ability.
337%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000338Note that a secondary prompt on a line by itself in an example means
339you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000340
Fred Drakeb7833d31998-09-11 16:21:55 +0000341\section{Using Python as a Calculator \label{calculator}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000342
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000343Let's try some simple Python commands. Start the interpreter and wait
Fred Drake8842e861998-02-13 07:16:30 +0000344for the primary prompt, \samp{>>> }. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000345
Fred Drakeb7833d31998-09-11 16:21:55 +0000346\subsection{Numbers \label{numbers}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000347
348The interpreter acts as a simple calculator: you can type an
349expression at it and it will write the value. Expression syntax is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000350straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/}
Fred Drakeee84d591999-03-10 17:25:30 +0000351work just like in most other languages (e.g., Pascal or C); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000352can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000353
Fred Drake8842e861998-02-13 07:16:30 +0000354\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000355>>> 2+2
3564
Guido van Rossum6938f061994-08-01 12:22:53 +0000357>>> # This is a comment
358... 2+2
3594
360>>> 2+2 # and a comment on the same line as code
3614
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000362>>> (50-5*6)/4
3635
Guido van Rossum6938f061994-08-01 12:22:53 +0000364>>> # Integer division returns the floor:
365... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003662
Guido van Rossum6938f061994-08-01 12:22:53 +0000367>>> 7/-3
368-3
Fred Drake8842e861998-02-13 07:16:30 +0000369\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000370
Fred Drakeee84d591999-03-10 17:25:30 +0000371Like in C, the equal sign (\character{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000372variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000373
Fred Drake8842e861998-02-13 07:16:30 +0000374\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000375>>> width = 20
376>>> height = 5*9
377>>> width * height
378900
Fred Drake8842e861998-02-13 07:16:30 +0000379\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000380%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000381A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000382
Fred Drake8842e861998-02-13 07:16:30 +0000383\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000384>>> x = y = z = 0 # Zero x, y and z
385>>> x
3860
387>>> y
3880
389>>> z
3900
Fred Drake8842e861998-02-13 07:16:30 +0000391\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000392%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000393There is full support for floating point; operators with mixed type
394operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000395
Fred Drake8842e861998-02-13 07:16:30 +0000396\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000397>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003983.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000399>>> 7.0 / 2
4003.5
Fred Drake8842e861998-02-13 07:16:30 +0000401\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000402%
403Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000404a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
405real component are written as \samp{(\var{real}+\var{imag}j)}, or can
406be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000407
Fred Drake8842e861998-02-13 07:16:30 +0000408\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000409>>> 1j * 1J
410(-1+0j)
411>>> 1j * complex(0,1)
412(-1+0j)
413>>> 3+1j*3
414(3+3j)
415>>> (3+1j)*3
416(9+3j)
417>>> (1+2j)/(1+1j)
418(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000419\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000420%
421Complex numbers are always represented as two floating point numbers,
422the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000423number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000424
Fred Drake8842e861998-02-13 07:16:30 +0000425\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000426>>> a=1.5+0.5j
427>>> a.real
4281.5
429>>> a.imag
4300.5
Fred Drake8842e861998-02-13 07:16:30 +0000431\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000432%
433The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000434(\function{float()}, \function{int()} and \function{long()}) don't
435work for complex numbers --- there is no one correct way to convert a
436complex number to a real number. Use \code{abs(\var{z})} to get its
437magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000438
Fred Drake8842e861998-02-13 07:16:30 +0000439\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000440>>> a=1.5+0.5j
441>>> float(a)
442Traceback (innermost last):
443 File "<stdin>", line 1, in ?
444TypeError: can't convert complex to float; use e.g. abs(z)
445>>> a.real
4461.5
447>>> abs(a)
4481.58113883008
Fred Drake8842e861998-02-13 07:16:30 +0000449\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000450%
451In interactive mode, the last printed expression is assigned to the
452variable \code{_}. This means that when you are using Python as a
453desk calculator, it is somewhat easier to continue calculations, for
454example:
455
456\begin{verbatim}
457>>> tax = 17.5 / 100
458>>> price = 3.50
459>>> price * tax
4600.6125
461>>> price + _
4624.1125
463>>> round(_, 2)
4644.11
465\end{verbatim}
466
467This variable should be treated as read-only by the user. Don't
468explicitly assign a value to it --- you would create an independent
469local variable with the same name masking the built-in variable with
470its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000471
Fred Drakeb7833d31998-09-11 16:21:55 +0000472\subsection{Strings \label{strings}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000473
Guido van Rossum02455691997-07-17 16:21:52 +0000474Besides numbers, Python can also manipulate strings, which can be
475expressed in several ways. They can be enclosed in single quotes or
476double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000477
Fred Drake8842e861998-02-13 07:16:30 +0000478\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000479>>> 'spam eggs'
480'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000481>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000482"doesn't"
483>>> "doesn't"
484"doesn't"
485>>> '"Yes," he said.'
486'"Yes," he said.'
487>>> "\"Yes,\" he said."
488'"Yes," he said.'
489>>> '"Isn\'t," she said.'
490'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000491\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000492
Fred Drake8842e861998-02-13 07:16:30 +0000493String literals can span multiple lines in several ways. Newlines can
494be escaped with backslashes, e.g.:
Guido van Rossum02455691997-07-17 16:21:52 +0000495
496\begin{verbatim}
497hello = "This is a rather long string containing\n\
498several lines of text just as you would do in C.\n\
499 Note that whitespace at the beginning of the line is\
500 significant.\n"
501print hello
502\end{verbatim}
503
504which would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000505
Guido van Rossum02455691997-07-17 16:21:52 +0000506\begin{verbatim}
507This is a rather long string containing
508several lines of text just as you would do in C.
509 Note that whitespace at the beginning of the line is significant.
510\end{verbatim}
511
512Or, strings can be surrounded in a pair of matching triple-quotes:
513\code{"""} or \code {'''}. End of lines do not need to be escaped
514when using triple-quotes, but they will be included in the string.
515
516\begin{verbatim}
517print """
518Usage: thingy [OPTIONS]
519 -h Display this usage message
520 -H hostname Hostname to connect to
521"""
522\end{verbatim}
523
524produces the following output:
525
Fred Drake8842e861998-02-13 07:16:30 +0000526\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000527Usage: thingy [OPTIONS]
528 -h Display this usage message
529 -H hostname Hostname to connect to
Fred Drake8842e861998-02-13 07:16:30 +0000530\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000531
Guido van Rossum02455691997-07-17 16:21:52 +0000532The interpreter prints the result of string operations in the same way
533as they are typed for input: inside quotes, and with quotes and other
534funny characters escaped by backslashes, to show the precise
535value. The string is enclosed in double quotes if the string contains
536a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000537quotes. (The \keyword{print} statement, described later, can be used
538to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000539
Fred Drakeeee08cd1997-12-04 15:43:15 +0000540Strings can be concatenated (glued together) with the \code{+}
541operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000542
Fred Drake8842e861998-02-13 07:16:30 +0000543\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000544>>> word = 'Help' + 'A'
545>>> word
546'HelpA'
547>>> '<' + word*5 + '>'
548'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000549\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000550
Guido van Rossum02455691997-07-17 16:21:52 +0000551Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000552the first line above could also have been written \samp{word = 'Help'
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000553'A'}; this only works with two literals, not with arbitrary string
554expressions:
555
556\begin{verbatim}
557>>> 'str' 'ing' # <- This is ok
558'string'
559>>> string.strip('str') + 'ing' # <- This is ok
560'string'
561>>> string.strip('str') 'ing' # <- This is invalid
562 File "<stdin>", line 1
563 string.strip('str') 'ing'
564 ^
565SyntaxError: invalid syntax
566\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000567
Fred Drakeee84d591999-03-10 17:25:30 +0000568Strings can be subscripted (indexed); like in C, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000569of a string has subscript (index) 0. There is no separate character
570type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000571substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000572separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000573
Fred Drake8842e861998-02-13 07:16:30 +0000574\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000575>>> word[4]
576'A'
577>>> word[0:2]
578'He'
579>>> word[2:4]
580'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000581\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000582
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000583Slice indices have useful defaults; an omitted first index defaults to
584zero, an omitted second index defaults to the size of the string being
585sliced.
586
Fred Drake8842e861998-02-13 07:16:30 +0000587\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000588>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000589'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000590>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000591'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000592\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000593
Fred Drakeeee08cd1997-12-04 15:43:15 +0000594Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
595equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000596
Fred Drake8842e861998-02-13 07:16:30 +0000597\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000598>>> word[:2] + word[2:]
599'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000600>>> word[:3] + word[3:]
601'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000602\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000603
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000604Degenerate slice indices are handled gracefully: an index that is too
605large is replaced by the string size, an upper bound smaller than the
606lower bound returns an empty string.
607
Fred Drake8842e861998-02-13 07:16:30 +0000608\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000609>>> word[1:100]
610'elpA'
611>>> word[10:]
612''
613>>> word[2:1]
614''
Fred Drake8842e861998-02-13 07:16:30 +0000615\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000616
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000617Indices may be negative numbers, to start counting from the right.
618For example:
619
Fred Drake8842e861998-02-13 07:16:30 +0000620\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000621>>> word[-1] # The last character
622'A'
623>>> word[-2] # The last-but-one character
624'p'
625>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000626'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000627>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000628'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000629\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000630
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000631But note that -0 is really the same as 0, so it does not count from
632the right!
633
Fred Drake8842e861998-02-13 07:16:30 +0000634\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000635>>> word[-0] # (since -0 equals 0)
636'H'
Fred Drake8842e861998-02-13 07:16:30 +0000637\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000638
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000639Out-of-range negative slice indices are truncated, but don't try this
640for single-element (non-slice) indices:
641
Fred Drake8842e861998-02-13 07:16:30 +0000642\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000643>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000644'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000645>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000646Traceback (innermost last):
647 File "<stdin>", line 1
648IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000649\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000650
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000651The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000652pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000653character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000654string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000655
Fred Drake8842e861998-02-13 07:16:30 +0000656\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000657 +---+---+---+---+---+
658 | H | e | l | p | A |
659 +---+---+---+---+---+
660 0 1 2 3 4 5
661-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000662\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000663
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000664The first row of numbers gives the position of the indices 0...5 in
665the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000666The slice from \var{i} to \var{j} consists of all characters between
667the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000668
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000669For nonnegative indices, the length of a slice is the difference of
670the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000671\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000672
Fred Drake8842e861998-02-13 07:16:30 +0000673The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000674
Fred Drake8842e861998-02-13 07:16:30 +0000675\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000676>>> s = 'supercalifragilisticexpialidocious'
677>>> len(s)
67834
Fred Drake8842e861998-02-13 07:16:30 +0000679\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000680
Fred Drakeb7833d31998-09-11 16:21:55 +0000681\subsection{Lists \label{lists}}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000682
Fred Drakeeee08cd1997-12-04 15:43:15 +0000683Python knows a number of \emph{compound} data types, used to group
684together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000685can be written as a list of comma-separated values (items) between
686square brackets. List items need not all have the same type.
687
Fred Drake8842e861998-02-13 07:16:30 +0000688\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000689>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000690>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000691['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000692\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000693
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000694Like string indices, list indices start at 0, and lists can be sliced,
695concatenated and so on:
696
Fred Drake8842e861998-02-13 07:16:30 +0000697\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000698>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000699'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000700>>> a[3]
7011234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000702>>> a[-2]
703100
704>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000705['eggs', 100]
706>>> a[:2] + ['bacon', 2*2]
707['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000708>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000709['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000710\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000711
Fred Drakeeee08cd1997-12-04 15:43:15 +0000712Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000713individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000714
Fred Drake8842e861998-02-13 07:16:30 +0000715\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000716>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000717['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000718>>> a[2] = a[2] + 23
719>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000720['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000721\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000722
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000723Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000724of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000725
Fred Drake8842e861998-02-13 07:16:30 +0000726\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000727>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000728... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000729>>> a
730[1, 12, 123, 1234]
731>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000732... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000733>>> a
734[123, 1234]
735>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000736... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000737>>> a
738[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000739>>> a[:0] = a # Insert (a copy of) itself at the beginning
740>>> a
741[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000742\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000743
Fred Drake8842e861998-02-13 07:16:30 +0000744The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000745
Fred Drake8842e861998-02-13 07:16:30 +0000746\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000747>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007488
Fred Drake8842e861998-02-13 07:16:30 +0000749\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000750
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000751It is possible to nest lists (create lists containing other lists),
752for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000753
Fred Drake8842e861998-02-13 07:16:30 +0000754\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000755>>> q = [2, 3]
756>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000757>>> len(p)
7583
759>>> p[1]
760[2, 3]
761>>> p[1][0]
7622
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000763>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000764>>> p
765[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000766>>> q
767[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000768\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000769
Fred Drakeeee08cd1997-12-04 15:43:15 +0000770Note that in the last example, \code{p[1]} and \code{q} really refer to
771the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000772
Fred Drakeb7833d31998-09-11 16:21:55 +0000773\section{First Steps Towards Programming \label{firstSteps}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000774
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000775Of course, we can use Python for more complicated tasks than adding
776two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000777subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000778
Fred Drake8842e861998-02-13 07:16:30 +0000779\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000780>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000781... # the sum of two elements defines the next
782... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000783>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000784... print b
785... a, b = b, a+b
786...
7871
7881
7892
7903
7915
7928
Fred Drake8842e861998-02-13 07:16:30 +0000793\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000794
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000795This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000796
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000797\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000798
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000799\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000800The first line contains a \emph{multiple assignment}: the variables
801\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000802last line this is used again, demonstrating that the expressions on
803the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000804assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000805
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000806\item
Fred Drake8842e861998-02-13 07:16:30 +0000807The \keyword{while} loop executes as long as the condition (here:
Fred Drakeee84d591999-03-10 17:25:30 +0000808\code{b < 10}) remains true. In Python, like in C, any non-zero
Fred Drake8842e861998-02-13 07:16:30 +0000809integer value is true; zero is false. The condition may also be a
810string or list value, in fact any sequence; anything with a non-zero
811length is true, empty sequences are false. The test used in the
812example is a simple comparison. The standard comparison operators are
Fred Drakeee84d591999-03-10 17:25:30 +0000813written the same as in C: \code{<}, \code{>}, \code{==}, \code{<=},
Fred Drake8842e861998-02-13 07:16:30 +0000814\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000815
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000816\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000817The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000818way of grouping statements. Python does not (yet!) provide an
819intelligent input line editing facility, so you have to type a tab or
820space(s) for each indented line. In practice you will prepare more
821complicated input for Python with a text editor; most text editors have
822an auto-indent facility. When a compound statement is entered
823interactively, it must be followed by a blank line to indicate
824completion (since the parser cannot guess when you have typed the last
825line).
826
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000827\item
Fred Drake8842e861998-02-13 07:16:30 +0000828The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000829given. It differs from just writing the expression you want to write
830(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000831multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000832and a space is inserted between items, so you can format things nicely,
833like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000834
Fred Drake8842e861998-02-13 07:16:30 +0000835\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000836>>> i = 256*256
837>>> print 'The value of i is', i
838The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000839\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000840
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000841A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000842
Fred Drake8842e861998-02-13 07:16:30 +0000843\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000844>>> a, b = 0, 1
845>>> while b < 1000:
846... print b,
847... a, b = b, a+b
848...
8491 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000850\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000851
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000852Note that the interpreter inserts a newline before it prints the next
853prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000854
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000855\end{itemize}
856
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000857
Fred Drakeb7833d31998-09-11 16:21:55 +0000858\chapter{More Control Flow Tools \label{moreControl}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000859
Fred Drake8842e861998-02-13 07:16:30 +0000860Besides the \keyword{while} statement just introduced, Python knows
861the usual control flow statements known from other languages, with
862some twists.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000863
Fred Drakeb7833d31998-09-11 16:21:55 +0000864\section{\keyword{if} Statements \label{if}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000865
Fred Drake8842e861998-02-13 07:16:30 +0000866Perhaps the most well-known statement type is the \keyword{if}
867statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000868
Fred Drake8842e861998-02-13 07:16:30 +0000869\begin{verbatim}
Guido van Rossume51aa5b1999-01-06 23:14:14 +0000870>>> # [Code which sets 'x' to a value...]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000871>>> if x < 0:
872... x = 0
873... print 'Negative changed to zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000874... elif x == 0:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000875... print 'Zero'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000876... elif x == 1:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000877... print 'Single'
878... else:
879... print 'More'
880...
Fred Drake8842e861998-02-13 07:16:30 +0000881\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000882
Fred Drake8842e861998-02-13 07:16:30 +0000883There can be zero or more \keyword{elif} parts, and the \keyword{else}
884part is optional. The keyword `\keyword{elif}' is short for `else
885if', and is useful to avoid excessive indentation. An
886\keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif}
887\ldots\ sequence is a substitute for the \emph{switch} or
888% ^^^^
889% Weird spacings happen here if the wrapping of the source text
890% gets changed in the wrong way.
891\emph{case} statements found in other languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000892
Fred Drakeb7833d31998-09-11 16:21:55 +0000893
894\section{\keyword{for} Statements \label{for}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000895
Fred Drakef790b161998-11-30 20:37:24 +0000896The \keyword{for}\stindex{for} statement in Python differs a bit from
Fred Drakeee84d591999-03-10 17:25:30 +0000897what you may be used to in C or Pascal. Rather than always
Fred Drakef790b161998-11-30 20:37:24 +0000898iterating over an arithmetic progression of numbers (like in Pascal),
899or giving the user the ability to define both the iteration step and
Fred Drakeee84d591999-03-10 17:25:30 +0000900halting condition (as C), Python's \keyword{for}\stindex{for}
Fred Drakef790b161998-11-30 20:37:24 +0000901statement iterates over the items of any sequence (e.g., a list or a
902string), in the order that they appear in the sequence. For example
903(no pun intended):
904% One suggestion was to give a real C example here, but that may only
905% serve to confuse non-C programmers.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000906
Fred Drake8842e861998-02-13 07:16:30 +0000907\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000908>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000909... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000910>>> for x in a:
911... print x, len(x)
912...
913cat 3
914window 6
915defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000916\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000917
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000918It is not safe to modify the sequence being iterated over in the loop
919(this can only happen for mutable sequence types, i.e., lists). If
920you need to modify the list you are iterating over, e.g., duplicate
921selected items, you must iterate over a copy. The slice notation
922makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000923
Fred Drake8842e861998-02-13 07:16:30 +0000924\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000925>>> for x in a[:]: # make a slice copy of the entire list
926... if len(x) > 6: a.insert(0, x)
927...
928>>> a
929['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000930\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000931
Fred Drakeb7833d31998-09-11 16:21:55 +0000932
933\section{The \function{range()} Function \label{range}}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000934
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000935If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000936function \function{range()} comes in handy. It generates lists
937containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000938
Fred Drake8842e861998-02-13 07:16:30 +0000939\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000940>>> range(10)
941[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000942\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000943
Fred Drake8842e861998-02-13 07:16:30 +0000944The given end point is never part of the generated list;
945\code{range(10)} generates a list of 10 values, exactly the legal
946indices for items of a sequence of length 10. It is possible to let
947the range start at another number, or to specify a different increment
948(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000949
Fred Drake8842e861998-02-13 07:16:30 +0000950\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000951>>> range(5, 10)
952[5, 6, 7, 8, 9]
953>>> range(0, 10, 3)
954[0, 3, 6, 9]
955>>> range(-10, -100, -30)
956[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000957\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000958
Fred Drake8842e861998-02-13 07:16:30 +0000959To iterate over the indices of a sequence, combine \function{range()}
960and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000961
Fred Drake8842e861998-02-13 07:16:30 +0000962\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000963>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000964>>> for i in range(len(a)):
965... print i, a[i]
966...
9670 Mary
9681 had
9692 a
9703 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009714 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000972\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000973
Fred Drake391564f1998-04-01 23:11:56 +0000974\section{\keyword{break} and \keyword{continue} Statements, and
Fred Drakeb7833d31998-09-11 16:21:55 +0000975 \keyword{else} Clauses on Loops
976 \label{break}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000977
Fred Drakeee84d591999-03-10 17:25:30 +0000978The \keyword{break} statement, like in C, breaks out of the smallest
Fred Drake8842e861998-02-13 07:16:30 +0000979enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000980
Fred Drakeee84d591999-03-10 17:25:30 +0000981The \keyword{continue} statement, also borrowed from C, continues
Fred Drake8842e861998-02-13 07:16:30 +0000982with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000983
Fred Drake8842e861998-02-13 07:16:30 +0000984Loop statements may have an \code{else} clause; it is executed when
985the loop terminates through exhaustion of the list (with
986\keyword{for}) or when the condition becomes false (with
987\keyword{while}), but not when the loop is terminated by a
988\keyword{break} statement. This is exemplified by the following loop,
989which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000990
Fred Drake8842e861998-02-13 07:16:30 +0000991\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000992>>> for n in range(2, 10):
993... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000994... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000995... print n, 'equals', x, '*', n/x
996... break
997... else:
998... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000999...
Guido van Rossum2292b8e1991-01-23 16:31:24 +000010002 is a prime number
10013 is a prime number
10024 equals 2 * 2
10035 is a prime number
10046 equals 2 * 3
10057 is a prime number
10068 equals 2 * 4
10079 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +00001008\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001009
Fred Drakeb7833d31998-09-11 16:21:55 +00001010\section{\keyword{pass} Statements \label{pass}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001011
Fred Drake8842e861998-02-13 07:16:30 +00001012The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001013It can be used when a statement is required syntactically but the
1014program requires no action.
1015For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001016
Fred Drake8842e861998-02-13 07:16:30 +00001017\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001018>>> while 1:
1019... pass # Busy-wait for keyboard interrupt
1020...
Fred Drake8842e861998-02-13 07:16:30 +00001021\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001022
Fred Drakeb7833d31998-09-11 16:21:55 +00001023\section{Defining Functions \label{functions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001024
1025We can create a function that writes the Fibonacci series to an
1026arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001027
Fred Drake8842e861998-02-13 07:16:30 +00001028\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001029>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001030... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001031... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001032... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001033... print b,
1034... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001035...
1036>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001037... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010381 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001039\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001040
Fred Drake8842e861998-02-13 07:16:30 +00001041The keyword \keyword{def} introduces a function \emph{definition}. It
1042must be followed by the function name and the parenthesized list of
1043formal parameters. The statements that form the body of the function
1044start at the next line, indented by a tab stop. The first statement
1045of the function body can optionally be a string literal; this string
1046literal is the function's documentation string, or \dfn{docstring}.
1047There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001048documentation, or to let the user interactively browse through code;
1049it's good practice to include docstrings in code that you write, so
1050try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001051
Fred Drakeeee08cd1997-12-04 15:43:15 +00001052The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001053for the local variables of the function. More precisely, all variable
1054assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001055whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001056in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001057Thus, global variables cannot be directly assigned a value within a
1058function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001059they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001060
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001061The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001062the local symbol table of the called function when it is called; thus,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001063arguments are passed using \emph{call by value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001064\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001065 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001066 description, since if a mutable object is passed, the caller
1067 will see any changes the callee makes to it (e.g., items
1068 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001069}
1070When a function calls another function, a new local symbol table is
1071created for that call.
1072
Fred Drake8842e861998-02-13 07:16:30 +00001073A function definition introduces the function name in the current
1074symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001075has a type that is recognized by the interpreter as a user-defined
1076function. This value can be assigned to another name which can then
1077also be used as a function. This serves as a general renaming
1078mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001079
Fred Drake8842e861998-02-13 07:16:30 +00001080\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001081>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001082<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001083>>> f = fib
1084>>> f(100)
10851 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001086\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001087
Fred Drakeeee08cd1997-12-04 15:43:15 +00001088You might object that \code{fib} is not a function but a procedure. In
Fred Drakeee84d591999-03-10 17:25:30 +00001089Python, like in C, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001090value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001091albeit a rather boring one. This value is called \code{None} (it's a
1092built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001093the interpreter if it would be the only value written. You can see it
1094if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001095
Fred Drake8842e861998-02-13 07:16:30 +00001096\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001097>>> print fib(0)
1098None
Fred Drake8842e861998-02-13 07:16:30 +00001099\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001100
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001101It is simple to write a function that returns a list of the numbers of
1102the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001103
Fred Drake8842e861998-02-13 07:16:30 +00001104\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001105>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001106... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001107... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001108... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001109... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001110... result.append(b) # see below
1111... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001112... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001113...
1114>>> f100 = fib2(100) # call it
1115>>> f100 # write the result
1116[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001117\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001118%
Guido van Rossum4410c751991-06-04 20:22:18 +00001119This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001120
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001121\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001122
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001123\item
Fred Drake8842e861998-02-13 07:16:30 +00001124The \keyword{return} statement returns with a value from a function.
1125\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001126the middle of a procedure (falling off the end also returns from a
1127procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001128
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001129\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001130The statement \code{result.append(b)} calls a \emph{method} of the list
1131object \code{result}. A method is a function that `belongs' to an
1132object and is named \code{obj.methodname}, where \code{obj} is some
1133object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001134of a method that is defined by the object's type. Different types
1135define different methods. Methods of different types may have the
1136same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001137own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001138in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001139The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001140list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001141example it is equivalent to \samp{result = result + [b]}, but more
1142efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001143
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001144\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001145
Fred Drakeb7833d31998-09-11 16:21:55 +00001146\section{More on Defining Functions \label{defining}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001147
Guido van Rossum02455691997-07-17 16:21:52 +00001148It is also possible to define functions with a variable number of
1149arguments. There are three forms, which can be combined.
1150
Fred Drakeb7833d31998-09-11 16:21:55 +00001151\subsection{Default Argument Values \label{defaultArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001152
1153The most useful form is to specify a default value for one or more
1154arguments. This creates a function that can be called with fewer
1155arguments than it is defined, e.g.
1156
1157\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001158def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1159 while 1:
1160 ok = raw_input(prompt)
1161 if ok in ('y', 'ye', 'yes'): return 1
1162 if ok in ('n', 'no', 'nop', 'nope'): return 0
1163 retries = retries - 1
1164 if retries < 0: raise IOError, 'refusenik user'
1165 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001166\end{verbatim}
1167
1168This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001169\code{ask_ok('Do you really want to quit?')} or like this:
1170\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001171
1172The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001173in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001174
1175\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001176i = 5
1177def f(arg = i): print arg
1178i = 6
1179f()
Guido van Rossum02455691997-07-17 16:21:52 +00001180\end{verbatim}
1181
Fred Drakeeee08cd1997-12-04 15:43:15 +00001182will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001183
Guido van Rossumaee5e261998-08-07 17:45:09 +00001184\strong{Important warning:} The default value is evaluated only once.
1185This makes a difference when the default is a mutable object such as a
1186list or dictionary. For example, the following function accumulates
1187the arguments passed to it on subsequent calls:
1188
1189\begin{verbatim}
1190def f(a, l = []):
1191 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001192 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001193print f(1)
1194print f(2)
1195print f(3)
1196\end{verbatim}
1197
1198This will print
1199
1200\begin{verbatim}
1201[1]
1202[1, 2]
1203[1, 2, 3]
1204\end{verbatim}
1205
1206If you don't want the default to be shared between subsequent calls,
1207you can write the function like this instead:
1208
1209\begin{verbatim}
1210def f(a, l = None):
1211 if l is None:
1212 l = []
1213 l.append(a)
Guido van Rossumc62cf361998-10-24 13:15:28 +00001214 return l
Guido van Rossumaee5e261998-08-07 17:45:09 +00001215\end{verbatim}
1216
Fred Drakeb7833d31998-09-11 16:21:55 +00001217\subsection{Keyword Arguments \label{keywordArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001218
1219Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001220keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001221instance, the following function:
1222
1223\begin{verbatim}
1224def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1225 print "-- This parrot wouldn't", action,
1226 print "if you put", voltage, "Volts through it."
1227 print "-- Lovely plumage, the", type
1228 print "-- It's", state, "!"
1229\end{verbatim}
1230
1231could be called in any of the following ways:
1232
1233\begin{verbatim}
1234parrot(1000)
1235parrot(action = 'VOOOOOM', voltage = 1000000)
1236parrot('a thousand', state = 'pushing up the daisies')
1237parrot('a million', 'bereft of life', 'jump')
1238\end{verbatim}
1239
1240but the following calls would all be invalid:
1241
1242\begin{verbatim}
1243parrot() # required argument missing
1244parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1245parrot(110, voltage=220) # duplicate value for argument
1246parrot(actor='John Cleese') # unknown keyword
1247\end{verbatim}
1248
1249In general, an argument list must have any positional arguments
1250followed by any keyword arguments, where the keywords must be chosen
1251from the formal parameter names. It's not important whether a formal
1252parameter has a default value or not. No argument must receive a
1253value more than once --- formal parameter names corresponding to
1254positional arguments cannot be used as keywords in the same calls.
1255
1256When a final formal parameter of the form \code{**\var{name}} is
1257present, it receives a dictionary containing all keyword arguments
1258whose keyword doesn't correspond to a formal parameter. This may be
1259combined with a formal parameter of the form \code{*\var{name}}
1260(described in the next subsection) which receives a tuple containing
1261the positional arguments beyond the formal parameter list.
1262(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1263example, if we define a function like this:
1264
1265\begin{verbatim}
1266def cheeseshop(kind, *arguments, **keywords):
1267 print "-- Do you have any", kind, '?'
1268 print "-- I'm sorry, we're all out of", kind
1269 for arg in arguments: print arg
1270 print '-'*40
1271 for kw in keywords.keys(): print kw, ':', keywords[kw]
1272\end{verbatim}
1273
1274It could be called like this:
1275
1276\begin{verbatim}
1277cheeseshop('Limburger', "It's very runny, sir.",
1278 "It's really very, VERY runny, sir.",
1279 client='John Cleese',
1280 shopkeeper='Michael Palin',
1281 sketch='Cheese Shop Sketch')
1282\end{verbatim}
1283
1284and of course it would print:
1285
1286\begin{verbatim}
1287-- Do you have any Limburger ?
1288-- I'm sorry, we're all out of Limburger
1289It's very runny, sir.
1290It's really very, VERY runny, sir.
1291----------------------------------------
1292client : John Cleese
1293shopkeeper : Michael Palin
1294sketch : Cheese Shop Sketch
1295\end{verbatim}
1296
Fred Drakeb7833d31998-09-11 16:21:55 +00001297\subsection{Arbitrary Argument Lists \label{arbitraryArgs}}
Guido van Rossum02455691997-07-17 16:21:52 +00001298
1299Finally, the least frequently used option is to specify that a
1300function can be called with an arbitrary number of arguments. These
1301arguments will be wrapped up in a tuple. Before the variable number
1302of arguments, zero or more normal arguments may occur.
1303
1304\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001305def fprintf(file, format, *args):
1306 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001307\end{verbatim}
1308
Fred Drakea594baf1998-04-03 05:16:31 +00001309
Fred Drakeb7833d31998-09-11 16:21:55 +00001310\subsection{Lambda Forms \label{lambda}}
Fred Drakea594baf1998-04-03 05:16:31 +00001311
1312By popular demand, a few features commonly found in functional
1313programming languages and Lisp have been added to Python. With the
1314\keyword{lambda} keyword, small anonymous functions can be created.
1315Here's a function that returns the sum of its two arguments:
1316\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1317objects are required. They are syntactically restricted to a single
1318expression. Semantically, they are just syntactic sugar for a normal
1319function definition. Like nested function definitions, lambda forms
1320cannot reference variables from the containing scope, but this can be
1321overcome through the judicious use of default argument values, e.g.
1322
1323\begin{verbatim}
1324def make_incrementor(n):
1325 return lambda x, incr=n: x+incr
1326\end{verbatim}
1327
Fred Drakeb7833d31998-09-11 16:21:55 +00001328\subsection{Documentation Strings \label{docstrings}}
Fred Drakea594baf1998-04-03 05:16:31 +00001329
1330There are emerging conventions about the content and formatting of
1331documentation strings.
1332
1333The first line should always be a short, concise summary of the
1334object's purpose. For brevity, it should not explicitly state the
1335object's name or type, since these are available by other means
1336(except if the name happens to be a verb describing a function's
1337operation). This line should begin with a capital letter and end with
1338a period.
1339
1340If there are more lines in the documentation string, the second line
1341should be blank, visually separating the summary from the rest of the
1342description. The following lines should be one of more of paragraphs
1343describing the objects calling conventions, its side effects, etc.
1344
1345The Python parser does not strip indentation from multi-line string
1346literals in Python, so tools that process documentation have to strip
1347indentation. This is done using the following convention. The first
1348non-blank line \emph{after} the first line of the string determines the
1349amount of indentation for the entire documentation string. (We can't
1350use the first line since it is generally adjacent to the string's
1351opening quotes so its indentation is not apparent in the string
1352literal.) Whitespace ``equivalent'' to this indentation is then
1353stripped from the start of all lines of the string. Lines that are
1354indented less should not occur, but if they occur all their leading
1355whitespace should be stripped. Equivalence of whitespace should be
1356tested after expansion of tabs (to 8 spaces, normally).
1357
1358
1359
Fred Drakeb7833d31998-09-11 16:21:55 +00001360\chapter{Data Structures \label{structures}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001361
1362This chapter describes some things you've learned about already in
1363more detail, and adds some new things as well.
1364
Fred Drakeb7833d31998-09-11 16:21:55 +00001365\section{More on Lists \label{moreLists}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001366
1367The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001368of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001369
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001370\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001371
Fred Drakeeee08cd1997-12-04 15:43:15 +00001372\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001373Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001374the element before which to insert, so \code{a.insert(0, x)} inserts at
1375the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1376\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001377
Fred Drakeeee08cd1997-12-04 15:43:15 +00001378\item[\code{append(x)}]
1379Equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001380
Fred Drakeeee08cd1997-12-04 15:43:15 +00001381\item[\code{index(x)}]
1382Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001383It is an error if there is no such item.
1384
Fred Drakeeee08cd1997-12-04 15:43:15 +00001385\item[\code{remove(x)}]
1386Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001387It is an error if there is no such item.
1388
Fred Drakeeee08cd1997-12-04 15:43:15 +00001389\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001390Sort the items of the list, in place.
1391
Fred Drakeeee08cd1997-12-04 15:43:15 +00001392\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001393Reverse the elements of the list, in place.
1394
Fred Drakeeee08cd1997-12-04 15:43:15 +00001395\item[\code{count(x)}]
1396Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001397
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001398\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001399
1400An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001401
Fred Drake8842e861998-02-13 07:16:30 +00001402\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001403>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001404>>> print a.count(333), a.count(66.6), a.count('x')
14052 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001406>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001407>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001408>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001409[66.6, 333, -1, 333, 1, 1234.5, 333]
1410>>> a.index(333)
14111
1412>>> a.remove(333)
1413>>> a
1414[66.6, -1, 333, 1, 1234.5, 333]
1415>>> a.reverse()
1416>>> a
1417[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001418>>> a.sort()
1419>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001420[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001421\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001422
Fred Drakeb7833d31998-09-11 16:21:55 +00001423\subsection{Functional Programming Tools \label{functional}}
Guido van Rossum02455691997-07-17 16:21:52 +00001424
1425There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001426lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001427
Fred Drake8842e861998-02-13 07:16:30 +00001428\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1429the same type, if possible) consisting of those items from the
1430sequence for which \code{\var{function}(\var{item})} is true. For
1431example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001432
1433\begin{verbatim}
Fred Drakeee84d591999-03-10 17:25:30 +00001434>>> def f(x): return x % 2 != 0 and x % 3 != 0
Fred Drake8842e861998-02-13 07:16:30 +00001435...
1436>>> filter(f, range(2, 25))
1437[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001438\end{verbatim}
1439
Fred Drake8842e861998-02-13 07:16:30 +00001440\samp{map(\var{function}, \var{sequence})} calls
1441\code{\var{function}(\var{item})} for each of the sequence's items and
1442returns a list of the return values. For example, to compute some
1443cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001444
1445\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001446>>> def cube(x): return x*x*x
1447...
1448>>> map(cube, range(1, 11))
1449[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001450\end{verbatim}
1451
1452More than one sequence may be passed; the function must then have as
1453many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001454corresponding item from each sequence (or \code{None} if some sequence
1455is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001456a function returning its argument(s) is substituted.
1457
1458Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001459\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1460turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001461
1462\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001463>>> seq = range(8)
1464>>> def square(x): return x*x
1465...
1466>>> map(None, seq, map(square, seq))
1467[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001468\end{verbatim}
1469
Fred Drake8842e861998-02-13 07:16:30 +00001470\samp{reduce(\var{func}, \var{sequence})} returns a single value
1471constructed by calling the binary function \var{func} on the first two
1472items of the sequence, then on the result and the next item, and so
1473on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001474
1475\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001476>>> def add(x,y): return x+y
1477...
1478>>> reduce(add, range(1, 11))
147955
Guido van Rossum02455691997-07-17 16:21:52 +00001480\end{verbatim}
1481
1482If there's only one item in the sequence, its value is returned; if
1483the sequence is empty, an exception is raised.
1484
1485A third argument can be passed to indicate the starting value. In this
1486case the starting value is returned for an empty sequence, and the
1487function is first applied to the starting value and the first sequence
1488item, then to the result and the next item, and so on. For example,
1489
1490\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001491>>> def sum(seq):
1492... def add(x,y): return x+y
1493... return reduce(add, seq, 0)
1494...
1495>>> sum(range(1, 11))
149655
1497>>> sum([])
14980
Guido van Rossum02455691997-07-17 16:21:52 +00001499\end{verbatim}
1500
Fred Drakeb7833d31998-09-11 16:21:55 +00001501\section{The \keyword{del} statement \label{del}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001502
1503There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001504of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001505remove slices from a list (which we did earlier by assignment of an
1506empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001507
Fred Drake8842e861998-02-13 07:16:30 +00001508\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001509>>> a
1510[-1, 1, 66.6, 333, 333, 1234.5]
1511>>> del a[0]
1512>>> a
1513[1, 66.6, 333, 333, 1234.5]
1514>>> del a[2:4]
1515>>> a
1516[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001517\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001518
1519\keyword{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001520
Fred Drake8842e861998-02-13 07:16:30 +00001521\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001522>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001523\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001524
Fred Drakeeee08cd1997-12-04 15:43:15 +00001525Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001526another value is assigned to it). We'll find other uses for
1527\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001528
Fred Drakeb7833d31998-09-11 16:21:55 +00001529\section{Tuples and Sequences \label{tuples}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001530
1531We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001532indexing and slicing operations. They are two examples of
1533\emph{sequence} data types. Since Python is an evolving language,
1534other sequence data types may be added. There is also another
1535standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001536
1537A tuple consists of a number of values separated by commas, for
1538instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001539
Fred Drake8842e861998-02-13 07:16:30 +00001540\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001541>>> t = 12345, 54321, 'hello!'
1542>>> t[0]
154312345
1544>>> t
1545(12345, 54321, 'hello!')
1546>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001547... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001548>>> u
1549((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001550\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001551
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001552As you see, on output tuples are alway enclosed in parentheses, so
1553that nested tuples are interpreted correctly; they may be input with
1554or without surrounding parentheses, although often parentheses are
1555necessary anyway (if the tuple is part of a larger expression).
1556
1557Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1558from a database, etc. Tuples, like strings, are immutable: it is not
1559possible to assign to the individual items of a tuple (you can
1560simulate much of the same effect with slicing and concatenation,
1561though).
1562
1563A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001564items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001565tuples are constructed by an empty pair of parentheses; a tuple with
1566one item is constructed by following a value with a comma
1567(it is not sufficient to enclose a single value in parentheses).
1568Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001569
Fred Drake8842e861998-02-13 07:16:30 +00001570\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001571>>> empty = ()
1572>>> singleton = 'hello', # <-- note trailing comma
1573>>> len(empty)
15740
1575>>> len(singleton)
15761
1577>>> singleton
1578('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001579\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001580
Fred Drakeeee08cd1997-12-04 15:43:15 +00001581The statement \code{t = 12345, 54321, 'hello!'} is an example of
1582\emph{tuple packing}: the values \code{12345}, \code{54321} and
1583\code{'hello!'} are packed together in a tuple. The reverse operation
1584is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001585
Fred Drake8842e861998-02-13 07:16:30 +00001586\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001587>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001588\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001589
Fred Drakeeee08cd1997-12-04 15:43:15 +00001590This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001591unpacking requires that the list of variables on the left has the same
1592number of elements as the length of the tuple. Note that multiple
1593assignment is really just a combination of tuple packing and tuple
1594unpacking!
1595
Guido van Rossumaee5e261998-08-07 17:45:09 +00001596% XXX This is no longer necessary!
Fred Drakeeee08cd1997-12-04 15:43:15 +00001597Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001598unpacking}. This is supported by enclosing the list of variables in
1599square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001600
Fred Drake8842e861998-02-13 07:16:30 +00001601\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001602>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001603>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001604\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001605
Guido van Rossumaee5e261998-08-07 17:45:09 +00001606% XXX Add a bit on the difference between tuples and lists.
1607% XXX Also explain that a tuple can *contain* a mutable object!
1608
Fred Drakeb7833d31998-09-11 16:21:55 +00001609\section{Dictionaries \label{dictionaries}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001610
Fred Drakeeee08cd1997-12-04 15:43:15 +00001611Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001612Dictionaries are sometimes found in other languages as ``associative
1613memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001614indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001615which can be any non-mutable type; strings and numbers can always be
1616keys. Tuples can be used as keys if they contain only strings,
1617numbers, or tuples. You can't use lists as keys, since lists can be
1618modified in place using their \code{append()} method.
1619
Guido van Rossum6938f061994-08-01 12:22:53 +00001620It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001621\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001622(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001623A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001624Placing a comma-separated list of key:value pairs within the
1625braces adds initial key:value pairs to the dictionary; this is also the
1626way dictionaries are written on output.
1627
1628The main operations on a dictionary are storing a value with some key
1629and extracting the value given the key. It is also possible to delete
1630a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001631with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001632If you store using a key that is already in use, the old value
1633associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001634value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001635
Fred Drakeeee08cd1997-12-04 15:43:15 +00001636The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001637keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001638just apply the \code{sort()} method to the list of keys). To check
1639whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001640method of the dictionary.
1641
1642Here is a small example using a dictionary:
1643
Fred Drake8842e861998-02-13 07:16:30 +00001644\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001645>>> tel = {'jack': 4098, 'sape': 4139}
1646>>> tel['guido'] = 4127
1647>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001648{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001649>>> tel['jack']
16504098
1651>>> del tel['sape']
1652>>> tel['irv'] = 4127
1653>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001654{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001655>>> tel.keys()
1656['guido', 'irv', 'jack']
1657>>> tel.has_key('guido')
16581
Fred Drake8842e861998-02-13 07:16:30 +00001659\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001660
Fred Drakeb7833d31998-09-11 16:21:55 +00001661\section{More on Conditions \label{conditions}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001662
Fred Drakeeee08cd1997-12-04 15:43:15 +00001663The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001664contain other operators besides comparisons.
1665
Fred Drakeeee08cd1997-12-04 15:43:15 +00001666The comparison operators \code{in} and \code{not in} check whether a value
1667occurs (does not occur) in a sequence. The operators \code{is} and
1668\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001669only matters for mutable objects like lists. All comparison operators
1670have the same priority, which is lower than that of all numerical
1671operators.
1672
Fred Drakeeee08cd1997-12-04 15:43:15 +00001673Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a}
1674is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001675
Fred Drakeeee08cd1997-12-04 15:43:15 +00001676Comparisons may be combined by the Boolean operators \code{and} and
1677\code{or}, and the outcome of a comparison (or of any other Boolean
1678expression) may be negated with \code{not}. These all have lower
1679priorities than comparison operators again; between them, \code{not} has
1680the highest priority, and \code{or} the lowest, so that
1681\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 +00001682course, parentheses can be used to express the desired composition.
1683
Fred Drakeeee08cd1997-12-04 15:43:15 +00001684The Boolean operators \code{and} and \code{or} are so-called
1685\emph{shortcut} operators: their arguments are evaluated from left to
1686right, and evaluation stops as soon as the outcome is determined.
1687E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1688and B and C} does not evaluate the expression C. In general, the
1689return value of a shortcut operator, when used as a general value and
1690not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001691
1692It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001693expression to a variable. For example,
1694
Fred Drake8842e861998-02-13 07:16:30 +00001695\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001696>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1697>>> non_null = string1 or string2 or string3
1698>>> non_null
1699'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001700\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001701
Fred Drakeee84d591999-03-10 17:25:30 +00001702Note that in Python, unlike C, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001703
Fred Drakeb7833d31998-09-11 16:21:55 +00001704\section{Comparing Sequences and Other Types \label{comparing}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001705
1706Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001707sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001708first the first two items are compared, and if they differ this
1709determines the outcome of the comparison; if they are equal, the next
1710two items are compared, and so on, until either sequence is exhausted.
1711If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001712the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001713items of two sequences compare equal, the sequences are considered
1714equal. If one sequence is an initial subsequence of the other, the
1715shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001716strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001717examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001718
Fred Drake8842e861998-02-13 07:16:30 +00001719\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001720(1, 2, 3) < (1, 2, 4)
1721[1, 2, 3] < [1, 2, 4]
1722'ABC' < 'C' < 'Pascal' < 'Python'
1723(1, 2, 3, 4) < (1, 2, 4)
1724(1, 2) < (1, 2, -1)
1725(1, 2, 3) = (1.0, 2.0, 3.0)
1726(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001727\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001728
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001729Note that comparing objects of different types is legal. The outcome
1730is deterministic but arbitrary: the types are ordered by their name.
1731Thus, a list is always smaller than a string, a string is always
1732smaller than a tuple, etc. Mixed numeric types are compared according
1733to their numeric value, so 0 equals 0.0, etc.%
1734\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001735 The rules for comparing objects of different types should
1736 not be relied upon; they may change in a future version of
1737 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001738}
1739
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001740
Fred Drakeb7833d31998-09-11 16:21:55 +00001741\chapter{Modules \label{modules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001742
Guido van Rossum4410c751991-06-04 20:22:18 +00001743If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001744definitions you have made (functions and variables) are lost.
1745Therefore, if you want to write a somewhat longer program, you are
1746better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001747and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001748\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001749into several files for easier maintenance. You may also want to use a
1750handy function that you've written in several programs without copying
1751its definition into each program.
1752
Guido van Rossum4410c751991-06-04 20:22:18 +00001753To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001754them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001755Such a file is called a \emph{module}; definitions from a module can be
1756\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001757collection of variables that you have access to in a script
1758executed at the top level
1759and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001760
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001761A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001762file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001763a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001764the global variable \code{__name__}. For instance, use your favorite text
1765editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001766with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001767
Fred Drake8842e861998-02-13 07:16:30 +00001768\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001769# Fibonacci numbers module
1770
1771def fib(n): # write Fibonacci series up to n
1772 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001773 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001774 print b,
1775 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001776
1777def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001778 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001779 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001780 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001781 result.append(b)
1782 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001783 return result
Fred Drake8842e861998-02-13 07:16:30 +00001784\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001785
Guido van Rossum4410c751991-06-04 20:22:18 +00001786Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001787following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001788
Fred Drake8842e861998-02-13 07:16:30 +00001789\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001790>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001791\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001792
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001793This does not enter the names of the functions defined in
Fred Drakeeee08cd1997-12-04 15:43:15 +00001794\code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001795directly in the current symbol table; it only enters the module name
Fred Drakeeee08cd1997-12-04 15:43:15 +00001796\code{fibo}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001797there.
1798Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001799
Fred Drake8842e861998-02-13 07:16:30 +00001800\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001801>>> fibo.fib(1000)
18021 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1803>>> fibo.fib2(100)
1804[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001805>>> fibo.__name__
1806'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001807\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001808%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001809If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001810
Fred Drake8842e861998-02-13 07:16:30 +00001811\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001812>>> fib = fibo.fib
1813>>> fib(500)
18141 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001815\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001816
Guido van Rossum02455691997-07-17 16:21:52 +00001817
Fred Drakeb7833d31998-09-11 16:21:55 +00001818\section{More on Modules \label{moreModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001819
1820A module can contain executable statements as well as function
1821definitions.
1822These statements are intended to initialize the module.
1823They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001824\emph{first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001825time the module is imported somewhere.%
1826\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001827 In fact function definitions are also `statements' that are
1828 `executed'; the execution enters the function name in the
1829 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001830}
1831
1832Each module has its own private symbol table, which is used as the
1833global symbol table by all functions defined in the module.
1834Thus, the author of a module can use global variables in the module
1835without worrying about accidental clashes with a user's global
1836variables.
1837On the other hand, if you know what you are doing you can touch a
1838module's global variables with the same notation used to refer to its
1839functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001840\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001841
1842Modules can import other modules.
1843It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001844\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001845statements at the beginning of a module (or script, for that matter).
1846The imported module names are placed in the importing module's global
1847symbol table.
1848
1849There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001850\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001851statement that imports names from a module directly into the importing
1852module's symbol table.
1853For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001854
Fred Drake8842e861998-02-13 07:16:30 +00001855\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001856>>> from fibo import fib, fib2
1857>>> fib(500)
18581 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001859\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001860
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001861This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001862in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001863defined).
1864
1865There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001866
Fred Drake8842e861998-02-13 07:16:30 +00001867\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001868>>> from fibo import *
1869>>> fib(500)
18701 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001871\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001872
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001873This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001874(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001875
Fred Drakeb7833d31998-09-11 16:21:55 +00001876\subsection{The Module Search Path \label{searchPath}}
Guido van Rossum02455691997-07-17 16:21:52 +00001877
Guido van Rossumaee5e261998-08-07 17:45:09 +00001878% XXX Need to document that a lone .pyc/.pyo is acceptable too!
1879
Fred Drake391564f1998-04-01 23:11:56 +00001880\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00001881When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001882for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001883and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00001884the environment variable \envvar{PYTHONPATH}. This has the same syntax as
1885the shell variable \envvar{PATH}, i.e., a list of
1886directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001887is not found there, the search continues in an installation-dependent
Fred Drake391564f1998-04-01 23:11:56 +00001888default path; on \UNIX{}, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001889
1890Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001891variable \code{sys.path} which is initialized from the directory
1892containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00001893\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001894Python programs that know what they're doing to modify or replace the
1895module search path. See the section on Standard Modules later.
1896
1897\subsection{``Compiled'' Python files}
1898
1899As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001900use a lot of standard modules, if a file called \file{spam.pyc} exists
1901in the directory where \file{spam.py} is found, this is assumed to
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001902contain an already-``byte-compiled'' version of the module \module{spam}.
Fred Drake8842e861998-02-13 07:16:30 +00001903The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001904\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1905ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001906
Fred Drakeeee08cd1997-12-04 15:43:15 +00001907Normally, you don't need to do anything to create the \file{spam.pyc} file.
1908Whenever \file{spam.py} is successfully compiled, an attempt is made to
1909write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001910this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001911completely, the resulting \file{spam.pyc} file will be recognized as
1912invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001913file is platform independent, so a Python module directory can be
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001914shared by machines of different architectures.
Guido van Rossum02455691997-07-17 16:21:52 +00001915
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001916Some tips for experts:
1917
1918\begin{itemize}
1919
1920\item
1921When the Python interpreter is invoked with the \code{-O} flag,
1922optimized code is generated and stored in \file{.pyo} files.
1923The optimizer currently doesn't help much; it only removes
1924\keyword{assert} statements and \code{SET_LINENO} instructions.
1925When \code{-O} is used, \emph{all} bytecode is optimized; \code{.pyc}
1926files are ignored and \code{.py} files are compiled to optimized
1927bytecode.
1928
1929\item
Guido van Rossum6b86a421999-01-28 15:07:47 +00001930Passing two \code{-O} flags to the Python interpreter (\code{-OO})
1931will cause the bytecode compiler to perform optimizations that could
1932in some rare cases result in malfunctioning programs. Currently only
1933\code{__doc__} strings are removed from the bytecode, resulting in more
1934compact \file{.pyo} files. Since some programs may rely on having
1935these available, you should only use this option if you know what
1936you're doing.
1937
1938\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001939A program doesn't run any faster when it is read from a
1940\file{.pyc} or \file{.pyo} file than when it is read from a \file{.py}
1941file; the only thing that's faster about \file{.pyc} or \file{.pyo}
1942files is the speed with which they are loaded.
1943
1944\item
Guido van Rossum002f7aa1998-06-28 19:16:38 +00001945When a script is run by giving its name on the command line, the
1946bytecode for the script is never written to a \file{.pyc} or
1947\file{.pyo} file. Thus, the startup time of a script may be reduced
1948by moving most of its code to a module and having a small bootstrap
1949script that imports that module.
1950
1951\item
Guido van Rossum13c8ef61998-05-29 19:12:23 +00001952It is possible to have a file called \file{spam.pyc} (or
1953\file{spam.pyo} when \code{-O} is used) without a module
1954\file{spam.py} in the same module. This can be used to distribute
1955a library of Python code in a form that is moderately hard to reverse
1956engineer.
1957
1958\item
1959The module \module{compileall}\refstmodindex{compileall} can create
1960\file{.pyc} files (or \file{.pyo} files when \code{-O} is used) for
1961all modules in a directory.
1962
1963\end{itemize}
1964
Guido van Rossum02455691997-07-17 16:21:52 +00001965
Fred Drakeb7833d31998-09-11 16:21:55 +00001966\section{Standard Modules \label{standardModules}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001967
Guido van Rossum4410c751991-06-04 20:22:18 +00001968Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001969document, the \emph{Python Library Reference} (``Library Reference''
1970hereafter). Some modules are built into the interpreter; these
1971provide access to operations that are not part of the core of the
1972language but are nevertheless built in, either for efficiency or to
1973provide access to operating system primitives such as system calls.
1974The set of such modules is a configuration option; e.g., the
1975\module{amoeba} module is only provided on systems that somehow
1976support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00001977attention: \module{sys}\refstmodindex{sys}, which is built into every
Fred Drakeee84d591999-03-10 17:25:30 +00001978Python interpreter. The variables \code{sys.ps1} and
1979\code{sys.ps2} define the strings used as primary and secondary
1980prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001981
Fred Drake8842e861998-02-13 07:16:30 +00001982\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001983>>> import sys
1984>>> sys.ps1
1985'>>> '
1986>>> sys.ps2
1987'... '
1988>>> sys.ps1 = 'C> '
1989C> print 'Yuck!'
1990Yuck!
1991C>
Fred Drake8842e861998-02-13 07:16:30 +00001992\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001993
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001994These two variables are only defined if the interpreter is in
1995interactive mode.
1996
Fred Drakeee84d591999-03-10 17:25:30 +00001997The variable \code{sys.path} is a list of strings that determine the
1998interpreter's search path for modules. It is initialized to a default
1999path taken from the environment variable \envvar{PYTHONPATH}, or from
2000a built-in default if \envvar{PYTHONPATH} is not set. You can modify
2001it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002002
Fred Drake8842e861998-02-13 07:16:30 +00002003\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002004>>> import sys
2005>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00002006\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002007
Fred Drakeb7833d31998-09-11 16:21:55 +00002008\section{The \function{dir()} Function \label{dir}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002009
Fred Drake8842e861998-02-13 07:16:30 +00002010The built-in function \function{dir()} is used to find out which names
2011a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002012
Fred Drake8842e861998-02-13 07:16:30 +00002013\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002014>>> import fibo, sys
2015>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00002016['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002017>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00002018['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
2019'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
2020'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00002021\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002022
Fred Drake8842e861998-02-13 07:16:30 +00002023Without arguments, \function{dir()} lists the names you have defined
2024currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002025
Fred Drake8842e861998-02-13 07:16:30 +00002026\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002027>>> a = [1, 2, 3, 4, 5]
2028>>> import fibo, sys
2029>>> fib = fibo.fib
2030>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00002031['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00002032\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002033
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002034Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002035
Fred Drake8842e861998-02-13 07:16:30 +00002036\function{dir()} does not list the names of built-in functions and
2037variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00002038standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002039
Fred Drake8842e861998-02-13 07:16:30 +00002040\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00002041>>> import __builtin__
2042>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00002043['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
2044'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
2045'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
2046'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
2047'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
2048'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
2049'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
2050'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
2051'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00002052\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002053
Fred Drakeb7833d31998-09-11 16:21:55 +00002054\section{Packages \label{packages}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002055
2056Packages are a way of structuring Python's module namespace
Fred Drakeb7833d31998-09-11 16:21:55 +00002057by using ``dotted module names''. For example, the module name
2058\module{A.B} designates a submodule named \samp{B} in a package named
2059\samp{A}. Just like the use of modules saves the authors of different
2060modules from having to worry about each other's global variable names,
2061the use of dotted module names saves the authors of multi-module
2062packages like NumPy or PIL from having to worry about each other's
2063module names.
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002064
2065Suppose you want to design a collection of modules (a ``package'') for
2066the uniform handling of sound files and sound data. There are many
2067different sound file formats (usually recognized by their extension,
2068e.g. \file{.wav}, \file{.aiff}, \file{.au}), so you may need to create
2069and maintain a growing collection of modules for the conversion
2070between the various file formats. There are also many different
2071operations you might want to perform on sound data (e.g. mixing,
2072adding echo, applying an equalizer function, creating an artificial
2073stereo effect), so in addition you will be writing a never-ending
2074stream of modules to perform these operations. Here's a possible
2075structure for your package (expressed in terms of a hierarchical
2076filesystem):
2077
2078\begin{verbatim}
2079Sound/ Top-level package
2080 __init__.py Initialize the sound package
2081 Formats/ Subpackage for file format conversions
2082 __init__.py
2083 wavread.py
2084 wavwrite.py
2085 aiffread.py
2086 aiffwrite.py
2087 auread.py
2088 auwrite.py
2089 ...
2090 Effects/ Subpackage for sound effects
2091 __init__.py
2092 echo.py
2093 surround.py
2094 reverse.py
2095 ...
2096 Filters/ Subpackage for filters
2097 __init__.py
2098 equalizer.py
2099 vocoder.py
2100 karaoke.py
2101 ...
2102\end{verbatim}
2103The \file{__init__.py} files are required to make Python treat the
2104directories as containing packages; this is done to prevent
2105directories with a common name, such as \samp{string}, from
2106unintentionally hiding valid modules that occur later on the module
2107search path. In the simplest case, \file{__init__.py} can just be an
2108empty file, but it can also execute initialization code for the
2109package or set the \code{__all__} variable, described later.
2110
2111Users of the package can import individual modules from the
2112package, for example:
2113
2114\begin{verbatim}
2115import Sound.Effects.echo
2116\end{verbatim}
2117This loads the submodule \module{Sound.Effects.echo}. It must be referenced
2118with its full name, e.g.
2119
2120\begin{verbatim}
2121Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4)
2122\end{verbatim}
2123An alternative way of importing the submodule is:
2124
2125\begin{verbatim}
2126from Sound.Effects import echo
2127\end{verbatim}
2128This also loads the submodule \module{echo}, and makes it available without
2129its package prefix, so it can be used as follows:
2130
2131\begin{verbatim}
2132echo.echofilter(input, output, delay=0.7, atten=4)
2133\end{verbatim}
2134
2135Yet another variation is to import the desired function or variable directly:
2136
2137\begin{verbatim}
2138from Sound.Effects.echo import echofilter
2139\end{verbatim}
2140
2141Again, this loads the submodule \module{echo}, but this makes its function
2142echofilter directly available:
2143
2144\begin{verbatim}
2145echofilter(input, output, delay=0.7, atten=4)
2146\end{verbatim}
2147
2148Note that when using \code{from \var{package} import \var{item}}, the
2149item can be either a submodule (or subpackage) of the package, or some
2150other name defined in the package, like a function, class or
2151variable. The \code{import} statement first tests whether the item is
2152defined in the package; if not, it assumes it is a module and attempts
2153to load it. If it fails to find it, \exception{ImportError} is raised.
2154
2155Contrarily, when using syntax like \code{import
2156\var{item.subitem.subsubitem}}, each item except for the last must be
2157a package; the last item can be a module or a package but can't be a
2158class or function or variable defined in the previous item.
2159
Fred Drakeb7833d31998-09-11 16:21:55 +00002160\subsection{Importing * From a Package \label{pkg-import-star}}
Andrew M. Kuchling108943c1998-07-01 13:58:55 +00002161%The \code{__all__} Attribute
2162
2163Now what happens when the user writes \code{from Sound.Effects import
2164*}? Ideally, one would hope that this somehow goes out to the
2165filesystem, finds which submodules are present in the package, and
2166imports them all. Unfortunately, this operation does not work very
2167well on Mac and Windows platforms, where the filesystem does not
2168always have accurate information about the case of a filename! On
2169these platforms, there is no guaranteed way to know whether a file
2170\file{ECHO.PY} should be imported as a module \module{echo},
2171\module{Echo} or \module{ECHO}. (For example, Windows 95 has the
2172annoying practice of showing all file names with a capitalized first
2173letter.) The DOS 8+3 filename restriction adds another interesting
2174problem for long module names.
2175
2176The only solution is for the package author to provide an explicit
2177index of the package. The import statement uses the following
2178convention: if a package's \file{__init__.py} code defines a list named
2179\code{__all__}, it is taken to be the list of module names that should be imported
2180when \code{from \var{package} import *} is
2181encountered. It is up to the package author to keep this list
2182up-to-date when a new version of the package is released. Package
2183authors may also decide not to support it, if they don't see a use for
2184importing * from their package. For example, the file
2185\code{Sounds/Effects/__init__.py} could contain the following code:
2186
2187\begin{verbatim}
2188__all__ = ["echo", "surround", "reverse"]
2189\end{verbatim}
2190
2191This would mean that \code{from Sound.Effects import *} would
2192import the three named submodules of the \module{Sound} package.
2193
2194If \code{__all__} is not defined, the statement \code{from Sound.Effects
2195import *} does \emph{not} import all submodules from the package
2196\module{Sound.Effects} into the current namespace; it only ensures that the
2197package \module{Sound.Effects} has been imported (possibly running its
2198initialization code, \file{__init__.py}) and then imports whatever names are
2199defined in the package. This includes any names defined (and
2200submodules explicitly loaded) by \file{__init__.py}. It also includes any
2201submodules of the package that were explicitly loaded by previous
2202import statements, e.g.
2203
2204\begin{verbatim}
2205import Sound.Effects.echo
2206import Sound.Effects.surround
2207from Sound.Effects import *
2208\end{verbatim}
2209
2210
2211In this example, the echo and surround modules are imported in the
2212current namespace because they are defined in the \module{Sound.Effects}
2213package when the \code{from...import} statement is executed. (This also
2214works when \code{__all__} is defined.)
2215
2216Note that in general the practicing of importing * from a module or
2217package is frowned upon, since it often causes poorly readable code.
2218However, it is okay to use it to save typing in interactive sessions,
2219and certain modules are designed to export only names that follow
2220certain patterns.
2221
2222Remember, there is nothing wrong with using \code{from Package
2223import specific_submodule}! In fact, this is the
2224recommended notation unless the importing module needs to use
2225submodules with the same name from different packages.
2226
2227
2228\subsection{Intra-package References}
2229
2230The submodules often need to refer to each other. For example, the
2231\module{surround} module might use the \module{echo} module. In fact, such references
2232are so common that the \code{import} statement first looks in the
2233containing package before looking in the standard module search path.
2234Thus, the surround module can simply use \code{import echo} or
2235\code{from echo import echofilter}. If the imported module is not
2236found in the current package (the package of which the current module
2237is a submodule), the \code{import} statement looks for a top-level module
2238with the given name.
2239
2240When packages are structured into subpackages (as with the \module{Sound}
2241package in the example), there's no shortcut to refer to submodules of
2242sibling packages - the full name of the subpackage must be used. For
2243example, if the module \module{Sound.Filters.vocoder} needs to use the \module{echo}
2244module in the \module{Sound.Effects} package, it can use \code{from
2245Sound.Effects import echo}.
2246
2247%(One could design a notation to refer to parent packages, similar to
2248%the use of ".." to refer to the parent directory in Unix and Windows
2249%filesystems. In fact, the \module{ni} module, which was the
2250%ancestor of this package system, supported this using \code{__} for
2251%the package containing the current module,
2252%\code{__.__} for the parent package, and so on. This feature was dropped
2253%because of its awkwardness; since most packages will have a relative
2254%shallow substructure, this is no big loss.)
2255
2256
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002257
Fred Drakeb7833d31998-09-11 16:21:55 +00002258\chapter{Input and Output \label{io}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002259
Guido van Rossum02455691997-07-17 16:21:52 +00002260There are several ways to present the output of a program; data can be
2261printed in a human-readable form, or written to a file for future use.
2262This chapter will discuss some of the possibilities.
2263
Fred Drakeb7833d31998-09-11 16:21:55 +00002264
2265\section{Fancier Output Formatting \label{formatting}}
2266
Fred Drakeeee08cd1997-12-04 15:43:15 +00002267So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00002268statements} and the \keyword{print} statement. (A third way is using
2269the \method{write()} method of file objects; the standard output file
2270can be referenced as \code{sys.stdout}. See the Library Reference for
2271more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002272
2273Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00002274simply printing space-separated values. There are two ways to format
2275your output; the first way is to do all the string handling yourself;
2276using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00002277lay-out you can imagine. The standard module
2278\module{string}\refstmodindex{string} contains some useful operations
2279for padding strings to a given column width;
Guido van Rossum02455691997-07-17 16:21:52 +00002280these will be discussed shortly. The second way is to use the
2281\code{\%} operator with a string as the left argument. \code{\%}
Fred Drakeee84d591999-03-10 17:25:30 +00002282interprets the left argument as a C \cfunction{sprintf()}-style
Fred Drake8842e861998-02-13 07:16:30 +00002283format string to be applied to the right argument, and returns the
2284string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002285
2286One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00002287Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00002288the \function{repr()} function, or just write the value between
2289reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002290
Fred Drake8842e861998-02-13 07:16:30 +00002291\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002292>>> x = 10 * 3.14
2293>>> y = 200*200
2294>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2295>>> print s
2296The value of x is 31.4, and y is 40000...
2297>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00002298... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00002299>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002300>>> ps
2301'[31.4, 40000]'
2302>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00002303... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002304>>> hellos = `hello`
2305>>> print hellos
2306'hello, world\012'
2307>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002308... `x, y, ('spam', 'eggs')`
2309"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00002310\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002311
Guido van Rossum6938f061994-08-01 12:22:53 +00002312Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002313
Fred Drake8842e861998-02-13 07:16:30 +00002314\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002315>>> import string
2316>>> for x in range(1, 11):
2317... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
2318... # Note trailing comma on previous line
2319... print string.rjust(`x*x*x`, 4)
2320...
2321 1 1 1
2322 2 4 8
2323 3 9 27
2324 4 16 64
2325 5 25 125
2326 6 36 216
2327 7 49 343
2328 8 64 512
2329 9 81 729
233010 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002331>>> for x in range(1,11):
2332... print '%2d %3d %4d' % (x, x*x, x*x*x)
2333...
2334 1 1 1
2335 2 4 8
2336 3 9 27
2337 4 16 64
2338 5 25 125
2339 6 36 216
2340 7 49 343
2341 8 64 512
2342 9 81 729
234310 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002344\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002345
Fred Drake8842e861998-02-13 07:16:30 +00002346(Note that one space between each column was added by the way
2347\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002348
Fred Drake8842e861998-02-13 07:16:30 +00002349This example demonstrates the function \function{string.rjust()},
2350which right-justifies a string in a field of a given width by padding
2351it with spaces on the left. There are similar functions
2352\function{string.ljust()} and \function{string.center()}. These
2353functions do not write anything, they just return a new string. If
2354the input string is too long, they don't truncate it, but return it
2355unchanged; this will mess up your column lay-out but that's usually
2356better than the alternative, which would be lying about a value. (If
2357you really want truncation you can always add a slice operation, as in
2358\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002359
Fred Drake8842e861998-02-13 07:16:30 +00002360There is another function, \function{string.zfill()}, which pads a
2361numeric string on the left with zeros. It understands about plus and
2362minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002363
Fred Drake8842e861998-02-13 07:16:30 +00002364\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002365>>> string.zfill('12', 5)
2366'00012'
2367>>> string.zfill('-3.14', 7)
2368'-003.14'
2369>>> string.zfill('3.14159265359', 5)
2370'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002371\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002372%
2373Using the \code{\%} operator looks like this:
2374
2375\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002376>>> import math
2377>>> print 'The value of PI is approximately %5.3f.' % math.pi
2378The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002379\end{verbatim}
2380
2381If there is more than one format in the string you pass a tuple as
2382right operand, e.g.
2383
2384\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002385>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2386>>> for name, phone in table.items():
2387... print '%-10s ==> %10d' % (name, phone)
2388...
2389Jack ==> 4098
2390Dcab ==> 8637678
2391Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002392\end{verbatim}
2393
Fred Drakeee84d591999-03-10 17:25:30 +00002394Most formats work exactly as in C and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002395type; however, if you don't you get an exception, not a core dump.
Fred Drakedb70d061998-11-17 21:59:04 +00002396The \code{\%s} format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002397not a string object, it is converted to string using the
2398\function{str()} built-in function. Using \code{*} to pass the width
2399or precision in as a separate (integer) argument is supported. The
Fred Drakeee84d591999-03-10 17:25:30 +00002400C formats \code{\%n} and \code{\%p} are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002401
2402If you have a really long format string that you don't want to split
2403up, it would be nice if you could reference the variables to be
2404formatted by name instead of by position. This can be done by using
Fred Drakeee84d591999-03-10 17:25:30 +00002405an extension of C formats using the form \code{\%(name)format}, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002406
2407\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002408>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2409>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2410Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002411\end{verbatim}
2412
2413This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002414\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002415local variables.
2416
Fred Drakeb7833d31998-09-11 16:21:55 +00002417\section{Reading and Writing Files \label{files}}
Fred Drake6c2176e1998-02-26 21:47:54 +00002418
Guido van Rossum02455691997-07-17 16:21:52 +00002419% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002420\function{open()}\bifuncindex{open} returns a file
2421object\obindex{file}, and is most commonly used with two arguments:
2422\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002423
Fred Drake8842e861998-02-13 07:16:30 +00002424\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002425>>> f=open('/tmp/workfile', 'w')
2426>>> print f
2427<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002428\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002429
Guido van Rossum02455691997-07-17 16:21:52 +00002430The first argument is a string containing the filename. The second
2431argument is another string containing a few characters describing the
2432way in which the file will be used. \var{mode} can be \code{'r'} when
2433the file will only be read, \code{'w'} for only writing (an existing
2434file with the same name will be erased), and \code{'a'} opens the file
2435for appending; any data written to the file is automatically added to
2436the end. \code{'r+'} opens the file for both reading and writing.
2437The \var{mode} argument is optional; \code{'r'} will be assumed if
2438it's omitted.
2439
Fred Drake391564f1998-04-01 23:11:56 +00002440On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00002441mode opens the file in binary mode, so there are also modes like
2442\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2443distinction between text and binary files; the end-of-line characters
2444in text files are automatically altered slightly when data is read or
2445written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002446\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2447\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00002448writing such files. (Note that the precise semantics of text mode on
Fred Drakeee84d591999-03-10 17:25:30 +00002449the Macintosh depends on the underlying C library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00002450
Fred Drakeb7833d31998-09-11 16:21:55 +00002451\subsection{Methods of File Objects \label{fileMethods}}
Guido van Rossum02455691997-07-17 16:21:52 +00002452
2453The rest of the examples in this section will assume that a file
2454object called \code{f} has already been created.
2455
2456To read a file's contents, call \code{f.read(\var{size})}, which reads
2457some quantity of data and returns it as a string. \var{size} is an
2458optional numeric argument. When \var{size} is omitted or negative,
2459the entire contents of the file will be read and returned; it's your
2460problem if the file is twice as large as your machine's memory.
2461Otherwise, at most \var{size} bytes are read and returned. If the end
2462of the file has been reached, \code{f.read()} will return an empty
2463string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002464\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002465>>> f.read()
2466'This is the entire file.\012'
2467>>> f.read()
2468''
Fred Drake8842e861998-02-13 07:16:30 +00002469\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002470
Guido van Rossum02455691997-07-17 16:21:52 +00002471\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002472character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002473omitted on the last line of the file if the file doesn't end in a
2474newline. This makes the return value unambiguous; if
2475\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002476been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002477string containing only a single newline.
2478
Fred Drake8842e861998-02-13 07:16:30 +00002479\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002480>>> f.readline()
2481'This is the first line of the file.\012'
2482>>> f.readline()
2483'Second line of the file\012'
2484>>> f.readline()
2485''
Fred Drake8842e861998-02-13 07:16:30 +00002486\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002487
Fred Drakeeee08cd1997-12-04 15:43:15 +00002488\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002489a list containing all the lines of data in the file.
2490
Fred Drake8842e861998-02-13 07:16:30 +00002491\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002492>>> f.readlines()
2493['This is the first line of the file.\012', 'Second line of the file\012']
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.write(\var{string})} writes the contents of \var{string} to
2497the file, returning \code{None}.
2498
Fred Drake8842e861998-02-13 07:16:30 +00002499\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002500>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002501\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002502
Guido van Rossum02455691997-07-17 16:21:52 +00002503\code{f.tell()} returns an integer giving the file object's current
2504position in the file, measured in bytes from the beginning of the
2505file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002506\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002507computed from adding \var{offset} to a reference point; the reference
2508point is selected by the \var{from_what} argument. A \var{from_what}
2509value of 0 measures from the beginning of the file, 1 uses the current
2510file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002511\var{from_what} can be omitted and defaults to 0, using the beginning
2512of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002513
Fred Drake8842e861998-02-13 07:16:30 +00002514\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002515>>> f=open('/tmp/workfile', 'r+')
2516>>> f.write('0123456789abcdef')
2517>>> f.seek(5) # Go to the 5th byte in the file
2518>>> f.read(1)
2519'5'
2520>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2521>>> f.read(1)
2522'd'
Fred Drake8842e861998-02-13 07:16:30 +00002523\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002524
Guido van Rossum02455691997-07-17 16:21:52 +00002525When you're done with a file, call \code{f.close()} to close it and
2526free up any system resources taken up by the open file. After calling
2527\code{f.close()}, attempts to use the file object will automatically fail.
2528
Fred Drake8842e861998-02-13 07:16:30 +00002529\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002530>>> f.close()
2531>>> f.read()
2532Traceback (innermost last):
2533 File "<stdin>", line 1, in ?
2534ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002535\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002536
Fred Drake8842e861998-02-13 07:16:30 +00002537File objects have some additional methods, such as \method{isatty()}
2538and \method{truncate()} which are less frequently used; consult the
2539Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002540
Fred Drakeb7833d31998-09-11 16:21:55 +00002541\subsection{The \module{pickle} Module \label{pickle}}
Fred Drake391564f1998-04-01 23:11:56 +00002542\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00002543
2544Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002545bit more effort, since the \method{read()} method only returns
2546strings, which will have to be passed to a function like
2547\function{string.atoi()}, which takes a string like \code{'123'} and
2548returns its numeric value 123. However, when you want to save more
2549complex data types like lists, dictionaries, or class instances,
2550things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002551
2552Rather than have users be constantly writing and debugging code to
2553save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002554\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002555any Python object (even some forms of Python code!), and convert it to
2556a string representation; this process is called \dfn{pickling}.
2557Reconstructing the object from the string representation is called
2558\dfn{unpickling}. Between pickling and unpickling, the string
2559representing the object may have been stored in a file or data, or
2560sent over a network connection to some distant machine.
2561
2562If you have an object \code{x}, and a file object \code{f} that's been
2563opened for writing, the simplest way to pickle the object takes only
2564one line of code:
2565
Fred Drake8842e861998-02-13 07:16:30 +00002566\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002567pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002568\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002569
Fred Drake8842e861998-02-13 07:16:30 +00002570To unpickle the object again, if \code{f} is a file object which has
2571been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002572
Fred Drake8842e861998-02-13 07:16:30 +00002573\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002574x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002575\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002576
Guido van Rossum02455691997-07-17 16:21:52 +00002577(There are other variants of this, used when pickling many objects or
2578when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002579complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002580
Fred Drake8842e861998-02-13 07:16:30 +00002581\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002582stored and reused by other programs or by a future invocation of the
2583same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002584object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002585write Python extensions take care to ensure that new data types such
Fred Drake72389881998-04-13 01:31:10 +00002586as matrices can be properly pickled and unpickled.
Guido van Rossum02455691997-07-17 16:21:52 +00002587
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002588
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002589
Fred Drakeb7833d31998-09-11 16:21:55 +00002590\chapter{Errors and Exceptions \label{errors}}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002591
2592Until now error messages haven't been more than mentioned, but if you
2593have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002594(at least) two distinguishable kinds of errors: \emph{syntax errors}
2595and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002596
Fred Drakeb7833d31998-09-11 16:21:55 +00002597\section{Syntax Errors \label{syntaxErrors}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002598
2599Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002600kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002601
Fred Drake8842e861998-02-13 07:16:30 +00002602\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002603>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002604 File "<stdin>", line 1
2605 while 1 print 'Hello world'
2606 ^
2607SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002608\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002609
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002610The parser repeats the offending line and displays a little `arrow'
2611pointing at the earliest point in the line where the error was detected.
2612The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002613\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002614the arrow: in the example, the error is detected at the keyword
Fred Drake391564f1998-04-01 23:11:56 +00002615\keyword{print}, since a colon (\character{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002616File name and line number are printed so you know where to look in case
2617the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002618
Fred Drakeb7833d31998-09-11 16:21:55 +00002619\section{Exceptions \label{exceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002620
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002621Even if a statement or expression is syntactically correct, it may
2622cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002623Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002624not unconditionally fatal: you will soon learn how to handle them in
2625Python programs. Most exceptions are not handled by programs,
2626however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002627
Fred Drake8842e861998-02-13 07:16:30 +00002628\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002629>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002630Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002631 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002632ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002633>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002634Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002635 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002636NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002637>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002638Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002639 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002640TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002641\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002642
Guido van Rossumb2c65561993-05-12 08:53:36 +00002643The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002644Exceptions come in different types, and the type is printed as part of
2645the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002646\exception{ZeroDivisionError},
2647\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002648and
Fred Drake8842e861998-02-13 07:16:30 +00002649\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002650The string printed as the exception type is the name of the built-in
2651name for the exception that occurred. This is true for all built-in
2652exceptions, but need not be true for user-defined exceptions (although
2653it is a useful convention).
2654Standard exception names are built-in identifiers (not reserved
2655keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002656
Guido van Rossumb2c65561993-05-12 08:53:36 +00002657The rest of the line is a detail whose interpretation depends on the
2658exception type; its meaning is dependent on the exception type.
2659
2660The preceding part of the error message shows the context where the
2661exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002662In general it contains a stack backtrace listing source lines; however,
2663it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002664
Fred Drake8842e861998-02-13 07:16:30 +00002665The Library Reference lists the built-in exceptions and their
2666meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002667
Fred Drakeb7833d31998-09-11 16:21:55 +00002668\section{Handling Exceptions \label{handling}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002669
2670It is possible to write programs that handle selected exceptions.
2671Look at the following example, which prints a table of inverses of
2672some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002673
Fred Drake8842e861998-02-13 07:16:30 +00002674\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002675>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002676>>> for x in numbers:
2677... print x,
2678... try:
2679... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002680... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002681... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002682...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000026830.3333 3.00030003
26842.5 0.4
26850 *** has no inverse ***
268610 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002687\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002688
Fred Drake8842e861998-02-13 07:16:30 +00002689The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002690\begin{itemize}
2691\item
Fred Drake8842e861998-02-13 07:16:30 +00002692First, the \emph{try clause}
2693(the statement(s) between the \keyword{try} and \keyword{except}
2694keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002695\item
2696If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002697\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002698is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002699\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002700If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002701the rest of the clause is skipped. Then if its type matches the
2702exception named after the \keyword{except} keyword, the rest of the
2703try clause is skipped, the except clause is executed, and then
2704execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002705\item
2706If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002707except clause, it is passed on to outer \keyword{try} statements; if
2708no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002709and execution stops with a message as shown above.
2710\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002711A \keyword{try} statement may have more than one except clause, to
2712specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002713At most one handler will be executed.
2714Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002715clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002716An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002717e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002718
Fred Drake8842e861998-02-13 07:16:30 +00002719\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002720... except (RuntimeError, TypeError, NameError):
2721... pass
Fred Drake8842e861998-02-13 07:16:30 +00002722\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002723
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002724The last except clause may omit the exception name(s), to serve as a
2725wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002726Use this with extreme caution, since it is easy to mask a real
2727programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002728
Fred Drake8842e861998-02-13 07:16:30 +00002729The \keyword{try} \ldots\ \keyword{except} statement has an optional
2730\emph{else clause}, which must follow all except clauses. It is
2731useful to place code that must be executed if the try clause does not
2732raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002733
2734\begin{verbatim}
Guido van Rossuma4289a71998-07-07 20:18:06 +00002735for arg in sys.argv[1:]:
Fred Drake8842e861998-02-13 07:16:30 +00002736 try:
2737 f = open(arg, 'r')
2738 except IOError:
2739 print 'cannot open', arg
2740 else:
2741 print arg, 'has', len(f.readlines()), 'lines'
2742 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002743\end{verbatim}
2744
2745
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002746When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002747the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002748The presence and type of the argument depend on the exception type.
2749For exception types which have an argument, the except clause may
2750specify a variable after the exception name (or list) to receive the
2751argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002752
Fred Drake8842e861998-02-13 07:16:30 +00002753\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002754>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002755... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002756... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002757... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002758...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002759name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002760\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002761
Guido van Rossumb2c65561993-05-12 08:53:36 +00002762If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002763(`detail') of the message for unhandled exceptions.
2764
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002765Exception handlers don't just handle exceptions if they occur
2766immediately in the try clause, but also if they occur inside functions
2767that are called (even indirectly) in the try clause.
2768For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002769
Fred Drake8842e861998-02-13 07:16:30 +00002770\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002771>>> def this_fails():
2772... x = 1/0
2773...
2774>>> try:
2775... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002776... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002777... print 'Handling run-time error:', detail
2778...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002779Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002780\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002781
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002782
Fred Drakeb7833d31998-09-11 16:21:55 +00002783\section{Raising Exceptions \label{raising}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002784
Fred Drake8842e861998-02-13 07:16:30 +00002785The \keyword{raise} statement allows the programmer to force a
2786specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002787For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002788
Fred Drake8842e861998-02-13 07:16:30 +00002789\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002790>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002791Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002792 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002793NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002794\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002795
Fred Drake8842e861998-02-13 07:16:30 +00002796The first argument to \keyword{raise} names the exception to be
2797raised. The optional second argument specifies the exception's
2798argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002799
Guido van Rossum02455691997-07-17 16:21:52 +00002800
Fred Drakeb7833d31998-09-11 16:21:55 +00002801\section{User-defined Exceptions \label{userExceptions}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002802
2803Programs may name their own exceptions by assigning a string to a
2804variable.
2805For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002806
Fred Drake8842e861998-02-13 07:16:30 +00002807\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002808>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002809>>> try:
2810... raise my_exc, 2*2
2811... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002812... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002813...
Guido van Rossum6938f061994-08-01 12:22:53 +00002814My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002815>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002816Traceback (innermost last):
2817 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002818my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002819\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002820
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002821Many standard modules use this to report errors that may occur in
2822functions they define.
2823
Guido van Rossum02455691997-07-17 16:21:52 +00002824
Fred Drakeb7833d31998-09-11 16:21:55 +00002825\section{Defining Clean-up Actions \label{cleanup}}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002826
Fred Drake8842e861998-02-13 07:16:30 +00002827The \keyword{try} statement has another optional clause which is
2828intended to define clean-up actions that must be executed under all
2829circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002830
Fred Drake8842e861998-02-13 07:16:30 +00002831\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002832>>> try:
2833... raise KeyboardInterrupt
2834... finally:
2835... print 'Goodbye, world!'
2836...
2837Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002838Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002839 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002840KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002841\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002842
Fred Drake8842e861998-02-13 07:16:30 +00002843A \emph{finally clause} is executed whether or not an exception has
2844occurred in the try clause. When an exception has occurred, it is
2845re-raised after the finally clause is executed. The finally clause is
2846also executed ``on the way out'' when the \keyword{try} statement is
2847left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002848
Fred Drake8842e861998-02-13 07:16:30 +00002849A \keyword{try} statement must either have one or more except clauses
2850or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002851
Fred Drakeb7833d31998-09-11 16:21:55 +00002852\chapter{Classes \label{classes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002853
2854Python's class mechanism adds classes to the language with a minimum
2855of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002856found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002857do not put an absolute barrier between definition and user, but rather
2858rely on the politeness of the user not to ``break into the
2859definition.'' The most important features of classes are retained
2860with full power, however: the class inheritance mechanism allows
2861multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00002862base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002863same name. Objects can contain an arbitrary amount of private data.
2864
Guido van Rossum16d6e711994-08-08 12:30:22 +00002865In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002866\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002867no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002868shorthands for referencing the object's members from its methods: the
2869method function is declared with an explicit first argument
2870representing the object, which is provided implicitly by the call. As
2871in Smalltalk, classes themselves are objects, albeit in the wider
2872sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002873provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002874or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002875extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002876built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00002877subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002878
Fred Drakeb7833d31998-09-11 16:21:55 +00002879\section{A Word About Terminology \label{terminology}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002880
Fred Drake391564f1998-04-01 23:11:56 +00002881Lacking universally accepted terminology to talk about classes, I will
2882make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002883terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002884Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002885
2886I also have to warn you that there's a terminological pitfall for
2887object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002888necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2889unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00002890built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00002891exotic types like files aren't. However, \emph{all} Python types
2892share a little bit of common semantics that is best described by using
2893the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002894
2895Objects have individuality, and multiple names (in multiple scopes)
2896can be bound to the same object. This is known as aliasing in other
2897languages. This is usually not appreciated on a first glance at
2898Python, and can be safely ignored when dealing with immutable basic
2899types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002900(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002901objects such as lists, dictionaries, and most types representing
2902entities outside the program (files, windows, etc.). This is usually
2903used to the benefit of the program, since aliases behave like pointers
2904in some respects. For example, passing an object is cheap since only
2905a pointer is passed by the implementation; and if a function modifies
2906an object passed as an argument, the caller will see the change --- this
2907obviates the need for two different argument passing mechanisms as in
2908Pascal.
2909
2910
Fred Drakeb7833d31998-09-11 16:21:55 +00002911\section{Python Scopes and Name Spaces \label{scopes}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002912
2913Before introducing classes, I first have to tell you something about
2914Python's scope rules. Class definitions play some neat tricks with
2915name spaces, and you need to know how scopes and name spaces work to
2916fully understand what's going on. Incidentally, knowledge about this
2917subject is useful for any advanced Python programmer.
2918
2919Let's begin with some definitions.
2920
Fred Drakeeee08cd1997-12-04 15:43:15 +00002921A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002922spaces are currently implemented as Python dictionaries, but that's
2923normally not noticeable in any way (except for performance), and it
2924may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002925built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002926names); the global names in a module; and the local names in a
2927function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002928also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002929spaces is that there is absolutely no relation between names in
2930different name spaces; for instance, two different modules may both
2931define a function ``maximize'' without confusion --- users of the
2932modules must prefix it with the module name.
2933
Fred Drakeeee08cd1997-12-04 15:43:15 +00002934By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002935dot --- for example, in the expression \code{z.real}, \code{real} is
2936an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002937names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002938\code{modname.funcname}, \code{modname} is a module object and
2939\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002940be a straightforward mapping between the module's attributes and the
2941global names defined in the module: they share the same name space!%
2942\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002943 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002944 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002945 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002946 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002947 Obviously, using this violates the abstraction of name space
2948 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002949 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002950}
2951
2952Attributes may be read-only or writable. In the latter case,
2953assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002954you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drake391564f1998-04-01 23:11:56 +00002955also be deleted with the \keyword{del} statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002956\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002957
2958Name spaces are created at different moments and have different
2959lifetimes. The name space containing the built-in names is created
2960when the Python interpreter starts up, and is never deleted. The
2961global name space for a module is created when the module definition
2962is read in; normally, module name spaces also last until the
2963interpreter quits. The statements executed by the top-level
2964invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002965interactively, are considered part of a module called
2966\module{__main__}, so they have their own global name space. (The
2967built-in names actually also live in a module; this is called
2968\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002969
2970The local name space for a function is created when the function is
2971called, and deleted when the function returns or raises an exception
2972that is not handled within the function. (Actually, forgetting would
2973be a better way to describe what actually happens.) Of course,
2974recursive invocations each have their own local name space.
2975
Fred Drakeeee08cd1997-12-04 15:43:15 +00002976A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002977is directly accessible. ``Directly accessible'' here means that an
2978unqualified reference to a name attempts to find the name in the name
2979space.
2980
2981Although scopes are determined statically, they are used dynamically.
2982At any time during execution, exactly three nested scopes are in use
2983(i.e., exactly three name spaces are directly accessible): the
2984innermost scope, which is searched first, contains the local names,
2985the middle scope, searched next, contains the current module's global
2986names, and the outermost scope (searched last) is the name space
2987containing built-in names.
2988
2989Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00002990current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002991the same name space as the global scope: the module's name space.
2992Class definitions place yet another name space in the local scope.
2993
2994It is important to realize that scopes are determined textually: the
2995global scope of a function defined in a module is that module's name
2996space, no matter from where or by what alias the function is called.
2997On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00002998run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002999static name resolution, at ``compile'' time, so don't rely on dynamic
3000name resolution! (In fact, local variables are already determined
3001statically.)
3002
3003A special quirk of Python is that assignments always go into the
3004innermost scope. Assignments do not copy data --- they just
3005bind names to objects. The same is true for deletions: the statement
Fred Drake391564f1998-04-01 23:11:56 +00003006\samp{del x} removes the binding of \code{x} from the name space
3007referenced by the local scope. In fact, all operations that introduce
3008new names use the local scope: in particular, import statements and
3009function definitions bind the module or function name in the local
3010scope. (The \keyword{global} statement can be used to indicate that
3011particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003012
3013
Fred Drakeb7833d31998-09-11 16:21:55 +00003014\section{A First Look at Classes \label{firstClasses}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003015
3016Classes introduce a little bit of new syntax, three new object types,
3017and some new semantics.
3018
3019
Fred Drakeb7833d31998-09-11 16:21:55 +00003020\subsection{Class Definition Syntax \label{classDefinition}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003021
3022The simplest form of class definition looks like this:
3023
3024\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003025class ClassName:
3026 <statement-1>
3027 .
3028 .
3029 .
3030 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003031\end{verbatim}
3032
Fred Drake8842e861998-02-13 07:16:30 +00003033Class definitions, like function definitions (\keyword{def}
3034statements) must be executed before they have any effect. (You could
3035conceivably place a class definition in a branch of an \keyword{if}
3036statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003037
3038In practice, the statements inside a class definition will usually be
3039function definitions, but other statements are allowed, and sometimes
3040useful --- we'll come back to this later. The function definitions
3041inside a class normally have a peculiar form of argument list,
3042dictated by the calling conventions for methods --- again, this is
3043explained later.
3044
3045When a class definition is entered, a new name space is created, and
3046used as the local scope --- thus, all assignments to local variables
3047go into this new name space. In particular, function definitions bind
3048the name of the new function here.
3049
Fred Drakeeee08cd1997-12-04 15:43:15 +00003050When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003051object} is created. This is basically a wrapper around the contents
3052of the name space created by the class definition; we'll learn more
3053about class objects in the next section. The original local scope
3054(the one in effect just before the class definitions was entered) is
Fred Drakea594baf1998-04-03 05:16:31 +00003055reinstated, and the class object is bound here to the class name given
3056in the class definition header (\class{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003057
3058
Fred Drakeb7833d31998-09-11 16:21:55 +00003059\subsection{Class Objects \label{classObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003060
3061Class objects support two kinds of operations: attribute references
3062and instantiation.
3063
Fred Drakeeee08cd1997-12-04 15:43:15 +00003064\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00003065attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003066names are all the names that were in the class's name space when the
3067class object was created. So, if the class definition looked like
3068this:
3069
3070\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003071class MyClass:
3072 "A simple example class"
3073 i = 12345
3074 def f(x):
3075 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003076\end{verbatim}
3077
Fred Drake8842e861998-02-13 07:16:30 +00003078then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003079references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00003080Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00003081of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00003082attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00003083the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003084
Fred Drakeeee08cd1997-12-04 15:43:15 +00003085Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003086the class object is a parameterless function that returns a new
3087instance of the class. For example, (assuming the above class):
3088
3089\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003090x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003091\end{verbatim}
3092
Fred Drakeeee08cd1997-12-04 15:43:15 +00003093creates a new \emph{instance} of the class and assigns this object to
3094the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003095
3096
Fred Drakeb7833d31998-09-11 16:21:55 +00003097\subsection{Instance Objects \label{instanceObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003098
3099Now what can we do with instance objects? The only operations
3100understood by instance objects are attribute references. There are
3101two kinds of valid attribute names.
3102
Fred Drakeeee08cd1997-12-04 15:43:15 +00003103The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00003104``instance variables'' in Smalltalk, and to ``data members'' in
3105\Cpp{}. Data attributes need not be declared; like local variables,
3106they spring into existence when they are first assigned to. For
3107example, if \code{x} is the instance of \class{MyClass} created above,
3108the following piece of code will print the value \code{16}, without
3109leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003110
3111\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003112x.counter = 1
3113while x.counter < 10:
3114 x.counter = x.counter * 2
3115print x.counter
3116del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003117\end{verbatim}
3118
3119The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00003120are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003121object. (In Python, the term method is not unique to class instances:
3122other object types can have methods as well, e.g., list objects have
3123methods called append, insert, remove, sort, and so on. However,
3124below, we'll use the term method exclusively to mean methods of class
3125instance objects, unless explicitly stated otherwise.)
3126
3127Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00003128definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003129objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00003130example, \code{x.f} is a valid method reference, since
3131\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00003132\code{MyClass.i} is not. But \code{x.f} is not the same thing as
3133\code{MyClass.f} --- it is a \emph{method object}, not a function
Fred Drakea594baf1998-04-03 05:16:31 +00003134object.%
3135\obindex{method}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003136
3137
Fred Drakeb7833d31998-09-11 16:21:55 +00003138\subsection{Method Objects \label{methodObjects}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003139
3140Usually, a method is called immediately, e.g.:
3141
3142\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003143x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003144\end{verbatim}
3145
Fred Drake8842e861998-02-13 07:16:30 +00003146In our example, this will return the string \code{'hello world'}.
Fred Drakeee84d591999-03-10 17:25:30 +00003147However, it is not necessary to call a method right away:
3148\code{x.f} is a method object, and can be stored away and called at a
3149later time. For example:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003150
3151\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003152xf = x.f
3153while 1:
3154 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003155\end{verbatim}
3156
Fred Drake8842e861998-02-13 07:16:30 +00003157will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003158
3159What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00003160that \code{x.f()} was called without an argument above, even though
3161the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003162happened to the argument? Surely Python raises an exception when a
3163function that requires an argument is called without any --- even if
3164the argument isn't actually used...
3165
3166Actually, you may have guessed the answer: the special thing about
3167methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00003168function. In our example, the call \code{x.f()} is exactly equivalent
3169to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00003170\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003171with an argument list that is created by inserting the method's object
3172before the first argument.
3173
3174If you still don't understand how methods work, a look at the
3175implementation can perhaps clarify matters. When an instance
3176attribute is referenced that isn't a data attribute, its class is
3177searched. If the name denotes a valid class attribute that is a
3178function object, a method object is created by packing (pointers to)
3179the instance object and the function object just found together in an
3180abstract object: this is the method object. When the method object is
3181called with an argument list, it is unpacked again, a new argument
3182list is constructed from the instance object and the original argument
3183list, and the function object is called with this new argument list.
3184
3185
Fred Drakeb7833d31998-09-11 16:21:55 +00003186\section{Random Remarks \label{remarks}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003187
3188[These should perhaps be placed more carefully...]
3189
3190
3191Data attributes override method attributes with the same name; to
3192avoid accidental name conflicts, which may cause hard-to-find bugs in
3193large programs, it is wise to use some kind of convention that
3194minimizes the chance of conflicts, e.g., capitalize method names,
3195prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00003196an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003197
3198
3199Data attributes may be referenced by methods as well as by ordinary
3200users (``clients'') of an object. In other words, classes are not
3201usable to implement pure abstract data types. In fact, nothing in
3202Python makes it possible to enforce data hiding --- it is all based
3203upon convention. (On the other hand, the Python implementation,
Fred Drakeee84d591999-03-10 17:25:30 +00003204written in C, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003205access to an object if necessary; this can be used by extensions to
Fred Drakeee84d591999-03-10 17:25:30 +00003206Python written in C.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003207
3208
3209Clients should use data attributes with care --- clients may mess up
3210invariants maintained by the methods by stamping on their data
3211attributes. Note that clients may add data attributes of their own to
3212an instance object without affecting the validity of the methods, as
3213long as name conflicts are avoided --- again, a naming convention can
3214save a lot of headaches here.
3215
3216
3217There is no shorthand for referencing data attributes (or other
3218methods!) from within methods. I find that this actually increases
3219the readability of methods: there is no chance of confusing local
3220variables and instance variables when glancing through a method.
3221
3222
3223Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00003224\code{self}. This is nothing more than a convention: the name
3225\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003226however, that by not following the convention your code may be less
3227readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00003228a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003229convention.)
3230
3231
3232Any function object that is a class attribute defines a method for
3233instances of that class. It is not necessary that the function
3234definition is textually enclosed in the class definition: assigning a
3235function object to a local variable in the class is also ok. For
3236example:
3237
3238\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003239# Function defined outside the class
3240def f1(self, x, y):
3241 return min(x, x+y)
3242
3243class C:
3244 f = f1
3245 def g(self):
3246 return 'hello world'
3247 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003248\end{verbatim}
3249
Fred Drake8842e861998-02-13 07:16:30 +00003250Now \code{f}, \code{g} and \code{h} are all attributes of class
3251\class{C} that refer to function objects, and consequently they are all
3252methods of instances of \class{C} --- \code{h} being exactly equivalent
3253to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003254the reader of a program.
3255
3256
3257Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00003258\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003259
3260\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003261class Bag:
3262 def empty(self):
3263 self.data = []
3264 def add(self, x):
3265 self.data.append(x)
3266 def addtwice(self, x):
3267 self.add(x)
3268 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003269\end{verbatim}
3270
3271
3272The instantiation operation (``calling'' a class object) creates an
3273empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00003274state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00003275\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003276
Guido van Rossum6938f061994-08-01 12:22:53 +00003277\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003278 def __init__(self):
3279 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00003280\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003281
Fred Drake8842e861998-02-13 07:16:30 +00003282When a class defines an \method{__init__()} method, class
3283instantiation automatically invokes \method{__init__()} for the
3284newly-created class instance. So in the \class{Bag} example, a new
3285and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003286
Guido van Rossum6938f061994-08-01 12:22:53 +00003287\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003288x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00003289\end{verbatim}
3290
Fred Drake8842e861998-02-13 07:16:30 +00003291Of course, the \method{__init__()} method may have arguments for
3292greater flexibility. In that case, arguments given to the class
3293instantiation operator are passed on to \method{__init__()}. For
3294example,
Guido van Rossum6938f061994-08-01 12:22:53 +00003295
Fred Drake8842e861998-02-13 07:16:30 +00003296\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00003297>>> class Complex:
3298... def __init__(self, realpart, imagpart):
3299... self.r = realpart
3300... self.i = imagpart
3301...
3302>>> x = Complex(3.0,-4.5)
3303>>> x.r, x.i
3304(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00003305\end{verbatim}
3306
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003307Methods may reference global names in the same way as ordinary
3308functions. The global scope associated with a method is the module
3309containing the class definition. (The class itself is never used as a
3310global scope!) While one rarely encounters a good reason for using
3311global data in a method, there are many legitimate uses of the global
3312scope: for one thing, functions and modules imported into the global
3313scope can be used by methods, as well as functions and classes defined
3314in it. Usually, the class containing the method is itself defined in
3315this global scope, and in the next section we'll find some good
3316reasons why a method would want to reference its own class!
3317
3318
Fred Drakeb7833d31998-09-11 16:21:55 +00003319\section{Inheritance \label{inheritance}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003320
3321Of course, a language feature would not be worthy of the name ``class''
3322without supporting inheritance. The syntax for a derived class
3323definition looks as follows:
3324
3325\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003326class DerivedClassName(BaseClassName):
3327 <statement-1>
3328 .
3329 .
3330 .
3331 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003332\end{verbatim}
3333
Fred Drake8842e861998-02-13 07:16:30 +00003334The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003335the derived class definition. Instead of a base class name, an
3336expression is also allowed. This is useful when the base class is
3337defined in another module, e.g.,
3338
3339\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003340class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003341\end{verbatim}
3342
3343Execution of a derived class definition proceeds the same as for a
3344base class. When the class object is constructed, the base class is
3345remembered. This is used for resolving attribute references: if a
3346requested attribute is not found in the class, it is searched in the
3347base class. This rule is applied recursively if the base class itself
3348is derived from some other class.
3349
3350There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00003351\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003352references are resolved as follows: the corresponding class attribute
3353is searched, descending down the chain of base classes if necessary,
3354and the method reference is valid if this yields a function object.
3355
3356Derived classes may override methods of their base classes. Because
3357methods have no special privileges when calling other methods of the
3358same object, a method of a base class that calls another method
3359defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003360a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003361in Python are ``virtual functions''.)
3362
3363An overriding method in a derived class may in fact want to extend
3364rather than simply replace the base class method of the same name.
3365There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003366call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003367occasionally useful to clients as well. (Note that this only works if
3368the base class is defined or imported directly in the global scope.)
3369
3370
Fred Drakeb7833d31998-09-11 16:21:55 +00003371\subsection{Multiple Inheritance \label{multiple}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003372
Guido van Rossum6938f061994-08-01 12:22:53 +00003373Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003374class definition with multiple base classes looks as follows:
3375
3376\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003377class DerivedClassName(Base1, Base2, Base3):
3378 <statement-1>
3379 .
3380 .
3381 .
3382 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003383\end{verbatim}
3384
3385The only rule necessary to explain the semantics is the resolution
3386rule used for class attribute references. This is depth-first,
3387left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003388\class{DerivedClassName}, it is searched in \class{Base1}, then
3389(recursively) in the base classes of \class{Base1}, and only if it is
3390not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003391
Fred Drake8842e861998-02-13 07:16:30 +00003392(To some people breadth first --- searching \class{Base2} and
3393\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003394natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003395attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003396one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003397a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003398rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003399\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003400
3401It is clear that indiscriminate use of multiple inheritance is a
3402maintenance nightmare, given the reliance in Python on conventions to
3403avoid accidental name conflicts. A well-known problem with multiple
3404inheritance is a class derived from two classes that happen to have a
3405common base class. While it is easy enough to figure out what happens
3406in this case (the instance will have a single copy of ``instance
3407variables'' or data attributes used by the common base class), it is
3408not clear that these semantics are in any way useful.
3409
3410
Fred Drakeb7833d31998-09-11 16:21:55 +00003411\section{Private Variables \label{private}}
Guido van Rossum02455691997-07-17 16:21:52 +00003412
Fred Drakea594baf1998-04-03 05:16:31 +00003413There is limited support for class-private
Guido van Rossum02455691997-07-17 16:21:52 +00003414identifiers. Any identifier of the form \code{__spam} (at least two
3415leading underscores, at most one trailing underscore) is now textually
3416replaced with \code{_classname__spam}, where \code{classname} is the
3417current class name with leading underscore(s) stripped. This mangling
3418is done without regard of the syntactic position of the identifier, so
3419it can be used to define class-private instance and class variables,
3420methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003421private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003422may occur when the mangled name would be longer than 255 characters.
3423Outside classes, or when the class name consists of only underscores,
3424no mangling occurs.
3425
3426Name mangling is intended to give classes an easy way to define
3427``private'' instance variables and methods, without having to worry
3428about instance variables defined by derived classes, or mucking with
3429instance variables by code outside the class. Note that the mangling
3430rules are designed mostly to avoid accidents; it still is possible for
3431a determined soul to access or modify a variable that is considered
3432private. This can even be useful, e.g. for the debugger, and that's
3433one reason why this loophole is not closed. (Buglet: derivation of a
3434class with the same name as the base class makes use of private
3435variables of the base class possible.)
3436
3437Notice that code passed to \code{exec}, \code{eval()} or
3438\code{evalfile()} does not consider the classname of the invoking
3439class to be the current class; this is similar to the effect of the
3440\code{global} statement, the effect of which is likewise restricted to
3441code that is byte-compiled together. The same restriction applies to
3442\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3443when referencing \code{__dict__} directly.
3444
3445Here's an example of a class that implements its own
3446\code{__getattr__} and \code{__setattr__} methods and stores all
3447attributes in a private variable, in a way that works in Python 1.4 as
3448well as in previous versions:
3449
3450\begin{verbatim}
3451class VirtualAttributes:
3452 __vdict = None
3453 __vdict_name = locals().keys()[0]
3454
3455 def __init__(self):
3456 self.__dict__[self.__vdict_name] = {}
3457
3458 def __getattr__(self, name):
3459 return self.__vdict[name]
3460
3461 def __setattr__(self, name, value):
3462 self.__vdict[name] = value
3463\end{verbatim}
3464
Fred Drakeaf8a0151998-01-14 14:51:31 +00003465%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003466%potential problems, refrain from using identifiers starting with
3467%double underscore except for predefined uses like \code{__init__}. To
3468%use private names while maintaining future compatibility: refrain from
3469%using the same private name in classes related via subclassing; avoid
3470%explicit (manual) mangling/unmangling; and assume that at some point
3471%in the future, leading double underscore will revert to being just a
3472%naming convention. Discussion on extensive compile-time declarations
3473%are currently underway, and it is impossible to predict what solution
3474%will eventually be chosen for private names. Double leading
3475%underscore is still a candidate, of course --- just not the only one.
3476%It is placed in the distribution in the belief that it is useful, and
3477%so that widespread experience with its use can be gained. It will not
3478%be removed without providing a better solution and a migration path.
3479
Fred Drakeb7833d31998-09-11 16:21:55 +00003480\section{Odds and Ends \label{odds}}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003481
3482Sometimes it is useful to have a data type similar to the Pascal
Fred Drakeee84d591999-03-10 17:25:30 +00003483``record'' or C ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003484items. An empty class definition will do nicely, e.g.:
3485
3486\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003487class Employee:
3488 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003489
Fred Drake8842e861998-02-13 07:16:30 +00003490john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003491
Fred Drake8842e861998-02-13 07:16:30 +00003492# Fill the fields of the record
3493john.name = 'John Doe'
3494john.dept = 'computer lab'
3495john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003496\end{verbatim}
3497
3498
3499A piece of Python code that expects a particular abstract data type
3500can often be passed a class that emulates the methods of that data
3501type instead. For instance, if you have a function that formats some
3502data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003503\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00003504buffer instead, and pass it as an argument.% (Unfortunately, this
3505%technique has its limitations: a class can't define operations that
3506%are accessed by special syntax such as sequence subscripting or
3507%arithmetic operators, and assigning such a ``pseudo-file'' to
3508%\code{sys.stdin} will not cause the interpreter to read further input
3509%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003510
3511
Fred Drake8842e861998-02-13 07:16:30 +00003512Instance method objects have attributes, too: \code{m.im_self} is the
3513object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003514function object corresponding to the method.
3515
Fred Drakeb7833d31998-09-11 16:21:55 +00003516\subsection{Exceptions Can Be Classes \label{exceptionClasses}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003517
3518User-defined exceptions are no longer limited to being string objects
3519--- they can be identified by classes as well. Using this mechanism it
3520is possible to create extensible hierarchies of exceptions.
3521
3522There are two new valid (semantic) forms for the raise statement:
3523
3524\begin{verbatim}
3525raise Class, instance
3526
3527raise instance
3528\end{verbatim}
3529
Fred Drake8842e861998-02-13 07:16:30 +00003530In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003531or of a class derived from it. The second form is a shorthand for
3532
3533\begin{verbatim}
3534raise instance.__class__, instance
3535\end{verbatim}
3536
3537An except clause may list classes as well as string objects. A class
3538in an except clause is compatible with an exception if it is the same
3539class or a base class thereof (but not the other way around --- an
3540except clause listing a derived class is not compatible with a base
3541class). For example, the following code will print B, C, D in that
3542order:
3543
3544\begin{verbatim}
3545class B:
3546 pass
3547class C(B):
3548 pass
3549class D(C):
3550 pass
3551
3552for c in [B, C, D]:
3553 try:
3554 raise c()
3555 except D:
3556 print "D"
3557 except C:
3558 print "C"
3559 except B:
3560 print "B"
3561\end{verbatim}
3562
Fred Drakeee84d591999-03-10 17:25:30 +00003563Note that if the except clauses were reversed (with
3564\samp{except B} first), it would have printed B, B, B --- the first
3565matching except clause is triggered.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003566
3567When an error message is printed for an unhandled exception which is a
3568class, the class name is printed, then a colon and a space, and
3569finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003570\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003571
Guido van Rossum194e57c1995-02-15 15:51:38 +00003572
Fred Drakeb7833d31998-09-11 16:21:55 +00003573\chapter{What Now? \label{whatNow}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003574
Guido van Rossum02455691997-07-17 16:21:52 +00003575Hopefully reading this tutorial has reinforced your interest in using
3576Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003577
Guido van Rossum02455691997-07-17 16:21:52 +00003578You should read, or at least page through, the Library Reference,
3579which gives complete (though terse) reference material about types,
3580functions, and modules that can save you a lot of time when writing
3581Python programs. The standard Python distribution includes a
Fred Drakeee84d591999-03-10 17:25:30 +00003582\emph{lot} of code in both C and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003583\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3584numbers, parse command-line options, write CGI programs, compress
3585data, and a lot more; skimming through the Library Reference will give
3586you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003587
Fred Drakeca6567f1998-01-22 20:44:18 +00003588The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003589code, documentation, and pointers to Python-related pages around the
Fred Drake391564f1998-04-01 23:11:56 +00003590Web. This web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00003591world, such as Europe, Japan, and Australia; a mirror may be faster
3592than the main site, depending on your geographical location. A more
Fred Drakeca6567f1998-01-22 20:44:18 +00003593informal site is \url{http://starship.skyport.net}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003594bunch of Python-related personal home pages; many people have
3595downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003596
Guido van Rossum02455691997-07-17 16:21:52 +00003597For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00003598newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
3599list at \email{python-list@cwi.nl}. The newsgroup and mailing list
3600are gatewayed, so messages posted to one will automatically be
3601forwarded to the other. There are around 35--45 postings a day,
3602% Postings figure based on average of last six months activity as
3603% reported by www.findmail.com; Oct. '97 - Mar. '98: 7480 msgs / 182
3604% days = 41.1 msgs / day.
3605asking (and answering) questions, suggesting new features, and
3606announcing new modules. Before posting, be sure to check the list of
3607Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003608\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3609\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003610answers many of the questions that come up again and again, and may
3611already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003612
Guido van Rossum02455691997-07-17 16:21:52 +00003613You can support the Python community by joining the Python Software
3614Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003615organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003616information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003617
Guido van Rossum194e57c1995-02-15 15:51:38 +00003618
Fred Drakea594baf1998-04-03 05:16:31 +00003619\appendix
Guido van Rossum194e57c1995-02-15 15:51:38 +00003620
Fred Drakeb7833d31998-09-11 16:21:55 +00003621\chapter{Interactive Input Editing and History Substitution
3622 \label{interacting}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003623
Guido van Rossum02455691997-07-17 16:21:52 +00003624Some versions of the Python interpreter support editing of the current
3625input line and history substitution, similar to facilities found in
3626the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003627\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003628editing. This library has its own documentation which I won't
Fred Drakecc09e8d1998-12-28 21:21:36 +00003629duplicate here; however, the basics are easily explained. The
3630interactive editing and history described here are optionally
3631available in the \UNIX{} and CygWin versions of the interpreter.
3632
3633This chapter does \emph{not} document the editing facilities of Mark
3634Hammond's PythonWin package or the Tk-based environment, IDLE,
3635distributed with Python. The command line history recall which
3636operates within DOS boxes on NT and some other DOS and Windows flavors
3637is yet another beast.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003638
Fred Drakeb7833d31998-09-11 16:21:55 +00003639\section{Line Editing \label{lineEditing}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003640
Guido van Rossum02455691997-07-17 16:21:52 +00003641If supported, input line editing is active whenever the interpreter
3642prints a primary or secondary prompt. The current line can be edited
3643using the conventional Emacs control characters. The most important
3644of these are: C-A (Control-A) moves the cursor to the beginning of the
3645line, C-E to the end, C-B moves it one position to the left, C-F to
3646the right. Backspace erases the character to the left of the cursor,
3647C-D the character to its right. C-K kills (erases) the rest of the
3648line to the right of the cursor, C-Y yanks back the last killed
3649string. C-underscore undoes the last change you made; it can be
3650repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003651
Fred Drakeb7833d31998-09-11 16:21:55 +00003652\section{History Substitution \label{history}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003653
Guido van Rossum02455691997-07-17 16:21:52 +00003654History substitution works as follows. All non-empty input lines
3655issued are saved in a history buffer, and when a new prompt is given
3656you are positioned on a new line at the bottom of this buffer. C-P
3657moves one line up (back) in the history buffer, C-N moves one down.
3658Any line in the history buffer can be edited; an asterisk appears in
3659front of the prompt to mark a line as modified. Pressing the Return
3660key passes the current line to the interpreter. C-R starts an
3661incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003662
Fred Drakeb7833d31998-09-11 16:21:55 +00003663\section{Key Bindings \label{keyBindings}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003664
Guido van Rossum02455691997-07-17 16:21:52 +00003665The key bindings and some other parameters of the Readline library can
3666be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003667\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003668
Fred Drake8842e861998-02-13 07:16:30 +00003669\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003670key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003671\end{verbatim}
3672
Guido van Rossum02455691997-07-17 16:21:52 +00003673or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003674
Fred Drake8842e861998-02-13 07:16:30 +00003675\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003676"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003677\end{verbatim}
3678
Guido van Rossum02455691997-07-17 16:21:52 +00003679and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003680
Fred Drake8842e861998-02-13 07:16:30 +00003681\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003682set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003683\end{verbatim}
3684
Guido van Rossum02455691997-07-17 16:21:52 +00003685For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003686
Fred Drake8842e861998-02-13 07:16:30 +00003687\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003688# I prefer vi-style editing:
3689set editing-mode vi
3690# Edit using a single line:
3691set horizontal-scroll-mode On
3692# Rebind some keys:
3693Meta-h: backward-kill-word
3694"\C-u": universal-argument
3695"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003696\end{verbatim}
3697
Guido van Rossum02455691997-07-17 16:21:52 +00003698Note that the default binding for TAB in Python is to insert a TAB
3699instead of Readline's default filename completion function. If you
3700insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003701
Fred Drake8842e861998-02-13 07:16:30 +00003702\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003703TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003704\end{verbatim}
3705
Fred Drakeeee08cd1997-12-04 15:43:15 +00003706in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003707indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003708
Fred Drake72389881998-04-13 01:31:10 +00003709Automatic completion of variable and module names is optionally
3710available. To enable it in the interpreter's interactive mode, add
Fred Drakeee84d591999-03-10 17:25:30 +00003711the following to your \file{\$HOME/.pythonrc.py} file:% $ <- bow to font-lock
3712\indexii{.pythonrc.py}{file}
3713\refstmodindex{rlcompleter}
Fred Drake72389881998-04-13 01:31:10 +00003714\refbimodindex{readline}
3715
3716\begin{verbatim}
3717import rlcompleter, readline
3718readline.parse_and_bind('tab: complete')
3719\end{verbatim}
3720
3721This binds the TAB key to the completion function, so hitting the TAB
3722key twice suggests completions; it looks at Python statement names,
3723the current local variables, and the available module names. For
3724dotted expressions such as \code{string.a}, it will evaluate the the
3725expression up to the final \character{.} and then suggest completions
3726from the attributes of the resulting object. Note that this may
3727execute application-defined code if an object with a
3728\method{__getattr__()} method is part of the expression.
3729
3730
Fred Drakeb7833d31998-09-11 16:21:55 +00003731\section{Commentary \label{commentary}}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003732
Guido van Rossum02455691997-07-17 16:21:52 +00003733This facility is an enormous step forward compared to previous
3734versions of the interpreter; however, some wishes are left: It would
3735be nice if the proper indentation were suggested on continuation lines
3736(the parser knows if an indent token is required next). The
3737completion mechanism might use the interpreter's symbol table. A
3738command to check (or even suggest) matching parentheses, quotes etc.
3739would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003740
Fred Drake8842e861998-02-13 07:16:30 +00003741% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003742
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003743\end{document}