blob: f8b198daab9094cfadf4ae96893465303cf28db1 [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
Guido van Rossum16cd7f91994-10-06 10:29:26 +000017\input{copyright}
18
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000019\begin{abstract}
20
21\noindent
Guido van Rossumdccc2981997-12-30 04:40:25 +000022Python is an easy to learn, powerful programming language. It has
23efficient high-level data structures and a simple but effective
24approach to object-oriented programming. Python's elegant syntax and
25dynamic typing, together with its interpreted nature, make it an ideal
26language for scripting and rapid application development in many areas
27on most platforms.
28
29The Python interpreter and the extensive standard library are freely
30available in source or binary form for all major platforms from the
Fred Drakeca6567f1998-01-22 20:44:18 +000031Python web site, \url{http://www.python.org}, and can be freely
Guido van Rossumdccc2981997-12-30 04:40:25 +000032distributed. The same site also contains distributions of and
33pointers to many free third party Python modules, programs and tools,
34and additional documentation.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000035
Guido van Rossum4410c751991-06-04 20:22:18 +000036The Python interpreter is easily extended with new functions and data
Fred Drake3f205921998-01-13 18:56:38 +000037types implemented in \C{} or \Cpp{} (or other languages callable from \C{}).
Guido van Rossumdccc2981997-12-30 04:40:25 +000038Python is also suitable as an extension language for customizable
39applications.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000040
Guido van Rossum6fc178f1991-08-16 09:13:42 +000041This tutorial introduces the reader informally to the basic concepts
42and features of the Python language and system. It helps to have a
Guido van Rossumdccc2981997-12-30 04:40:25 +000043Python interpreter handy for hands-on experience, but all examples are
44self-contained, so the tutorial can be read off-line as well.
Guido van Rossum2292b8e1991-01-23 16:31:24 +000045
Guido van Rossumdccc2981997-12-30 04:40:25 +000046For a description of standard objects and modules, see the
47\emph{Python Library Reference} document. The \emph{Python Reference
48Manual} gives a more formal definition of the language. To write
Fred Drake3f205921998-01-13 18:56:38 +000049extensions in \C{} or \Cpp{}, read the \emph{Extending and Embedding} and
50\emph{Python/\C{} API} manuals. There are also several books covering
Guido van Rossumdccc2981997-12-30 04:40:25 +000051Python in depth.
52
53This tutorial does not attempt to be comprehensive and cover every
54single feature, or even every commonly used feature. Instead, it
55introduces many of Python's most noteworthy features, and will give
56you a good idea of the language's flavor and style. After reading it,
57you will be able to read and write Python modules and programs, and
58you will be ready to learn more about the various Python library
59modules described in the \emph{Python Library Reference}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000060
61\end{abstract}
62
Fred Drake4d4f9e71998-01-13 22:25:02 +000063\tableofcontents
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000064
Guido van Rossum5e0759d1992-08-07 16:06:24 +000065
Guido van Rossum6fc178f1991-08-16 09:13:42 +000066\chapter{Whetting Your Appetite}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000067
Fred Drake6c2176e1998-02-26 21:47:54 +000068\label{intro}
Guido van Rossum3a26dd81996-10-24 22:12:48 +000069
Guido van Rossum6fc178f1991-08-16 09:13:42 +000070If you ever wrote a large shell script, you probably know this
71feeling: you'd love to add yet another feature, but it's already so
72slow, and so big, and so complicated; or the feature involves a system
Fred Drake3f205921998-01-13 18:56:38 +000073call or other function that is only accessible from \C{} \ldots Usually
Guido van Rossum6fc178f1991-08-16 09:13:42 +000074the problem at hand isn't serious enough to warrant rewriting the
Fred Drake3f205921998-01-13 18:56:38 +000075script in \C{}; perhaps the problem requires variable-length strings or
Guido van Rossum02455691997-07-17 16:21:52 +000076other data types (like sorted lists of file names) that are easy in
Fred Drake3f205921998-01-13 18:56:38 +000077the shell but lots of work to implement in \C{}, or perhaps you're not
78sufficiently familiar with \C{}.
Guido van Rossum02455691997-07-17 16:21:52 +000079
Fred Drake3f205921998-01-13 18:56:38 +000080Another situation: perhaps you have to work with several \C{} libraries,
81and the usual \C{} write/compile/test/re-compile cycle is too slow. You
Guido van Rossum02455691997-07-17 16:21:52 +000082need to develop software more quickly. Possibly perhaps you've
83written a program that could use an extension language, and you don't
84want to design a language, write and debug an interpreter for it, then
85tie it into your application.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000086
Guido van Rossum6fc178f1991-08-16 09:13:42 +000087In such cases, Python may be just the language for you. Python is
88simple to use, but it is a real programming language, offering much
89more structure and support for large programs than the shell has. On
Fred Drake3f205921998-01-13 18:56:38 +000090the other hand, it also offers much more error checking than \C{}, and,
Fred Drakeeee08cd1997-12-04 15:43:15 +000091being a \emph{very-high-level language}, it has high-level data types
Guido van Rossum6fc178f1991-08-16 09:13:42 +000092built in, such as flexible arrays and dictionaries that would cost you
Fred Drake3f205921998-01-13 18:56:38 +000093days to implement efficiently in \C{}. Because of its more general data
Fred Drakeeee08cd1997-12-04 15:43:15 +000094types Python is applicable to a much larger problem domain than
95\emph{Awk} or even \emph{Perl}, yet many things are at least as easy
96in Python as in those languages.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000097
Guido van Rossum6fc178f1991-08-16 09:13:42 +000098Python allows you to split up your program in modules that can be
99reused in other Python programs. It comes with a large collection of
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000100standard modules that you can use as the basis of your programs --- or
101as examples to start learning to program in Python. There are also
102built-in modules that provide things like file I/O, system calls,
Guido van Rossum02455691997-07-17 16:21:52 +0000103sockets, and even interfaces to GUI toolkits like Tk.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000104
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000105Python is an interpreted language, which can save you considerable time
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000106during program development because no compilation and linking is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000107necessary. The interpreter can be used interactively, which makes it
108easy to experiment with features of the language, to write throw-away
109programs, or to test functions during bottom-up program development.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000110It is also a handy desk calculator.
111
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000112Python allows writing very compact and readable programs. Programs
Fred Drake3f205921998-01-13 18:56:38 +0000113written in Python are typically much shorter than equivalent \C{}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000114programs, for several reasons:
115\begin{itemize}
116\item
117the high-level data types allow you to express complex operations in a
118single statement;
119\item
120statement grouping is done by indentation instead of begin/end
121brackets;
122\item
123no variable or argument declarations are necessary.
124\end{itemize}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000125
Fred Drake3f205921998-01-13 18:56:38 +0000126Python is \emph{extensible}: if you know how to program in \C{} it is easy
Guido van Rossum02455691997-07-17 16:21:52 +0000127to add a new built-in function or module to the interpreter, either to
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000128perform critical operations at maximum speed, or to link Python
129programs to libraries that may only be available in binary form (such
130as a vendor-specific graphics library). Once you are really hooked,
Fred Drake3f205921998-01-13 18:56:38 +0000131you can link the Python interpreter into an application written in \C{}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000132and use it as an extension or command language for that application.
133
Guido van Rossum02455691997-07-17 16:21:52 +0000134By the way, the language is named after the BBC show ``Monty Python's
135Flying Circus'' and has nothing to do with nasty reptiles. Making
136references to Monty Python skits in documentation is not only allowed,
Guido van Rossumdccc2981997-12-30 04:40:25 +0000137it is encouraged!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000138
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000139\section{Where From Here}
Fred Drake6c2176e1998-02-26 21:47:54 +0000140\label{where}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000141
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000142Now that you are all excited about Python, you'll want to examine it
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000143in some more detail. Since the best way to learn a language is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000144using it, you are invited here to do so.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000145
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000146In the next chapter, the mechanics of using the interpreter are
147explained. This is rather mundane information, but essential for
148trying out the examples shown later.
149
Guido van Rossum4410c751991-06-04 20:22:18 +0000150The rest of the tutorial introduces various features of the Python
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000151language and system though examples, beginning with simple
152expressions, statements and data types, through functions and modules,
Guido van Rossum6938f061994-08-01 12:22:53 +0000153and finally touching upon advanced concepts like exceptions
154and user-defined classes.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000155
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000156\chapter{Using the Python Interpreter}
Fred Drake6c2176e1998-02-26 21:47:54 +0000157\label{using}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000158
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000159\section{Invoking the Interpreter}
Fred Drake6c2176e1998-02-26 21:47:54 +0000160\label{invoking}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000161
Fred Drakeeee08cd1997-12-04 15:43:15 +0000162The Python interpreter is usually installed as \file{/usr/local/bin/python}
163on those machines where it is available; putting \file{/usr/local/bin} in
Fred Drake6dc2aae1996-12-13 21:56:03 +0000164your \UNIX{} shell's search path makes it possible to start it by
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000165typing the command
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000166
Fred Drake8842e861998-02-13 07:16:30 +0000167\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000168python
Fred Drake8842e861998-02-13 07:16:30 +0000169\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000170
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000171to the shell. Since the choice of the directory where the interpreter
172lives is an installation option, other places are possible; check with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000173your local Python guru or system administrator. (E.g.,
174\file{/usr/local/python} is a popular alternative location.)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000175
Guido van Rossum02455691997-07-17 16:21:52 +0000176Typing an EOF character (Control-D on \UNIX{}, Control-Z or F6 on DOS
177or Windows) at the primary prompt causes the interpreter to exit with
178a zero exit status. If that doesn't work, you can exit the
Fred Drake8842e861998-02-13 07:16:30 +0000179interpreter by typing the following commands: \samp{import sys;
Guido van Rossum02455691997-07-17 16:21:52 +0000180sys.exit()}.
181
182The interpreter's line-editing features usually aren't very
Fred Drake3f205921998-01-13 18:56:38 +0000183sophisticated. On \UNIX{}, whoever installed the interpreter may have
Guido van Rossum02455691997-07-17 16:21:52 +0000184enabled support for the GNU readline library, which adds more
185elaborate interactive editing and history features. Perhaps the
186quickest check to see whether command line editing is supported is
187typing Control-P to the first Python prompt you get. If it beeps, you
188have command line editing; see Appendix A for an introduction to the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000189keys. If nothing appears to happen, or if \code{\^P} is echoed,
Guido van Rossum02455691997-07-17 16:21:52 +0000190command line editing isn't available; you'll only be able to use
191backspace to remove characters from the current line.
192
Fred Drake6dc2aae1996-12-13 21:56:03 +0000193The interpreter operates somewhat like the \UNIX{} shell: when called
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000194with standard input connected to a tty device, it reads and executes
195commands interactively; when called with a file name argument or with
Fred Drakeeee08cd1997-12-04 15:43:15 +0000196a file as standard input, it reads and executes a \emph{script} from
Guido van Rossum02455691997-07-17 16:21:52 +0000197that file.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000198
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000199A third way of starting the interpreter is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000200\samp{python -c command [arg] ...}, which
201executes the statement(s) in \code{command}, analogous to the shell's
202\code{-c} option. Since Python statements often contain spaces or other
203characters that are special to the shell, it is best to quote
204\code{command} in its entirety with double quotes.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000205
Fred Drakeeee08cd1997-12-04 15:43:15 +0000206Note that there is a difference between \samp{python file} and
207\samp{python <file}. In the latter case, input requests from the
208program, such as calls to \code{input()} and \code{raw_input()}, are
209satisfied from \emph{file}. Since this file has already been read
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000210until the end by the parser before the program starts executing, the
211program will encounter EOF immediately. In the former case (which is
212usually what you want) they are satisfied from whatever file or device
213is connected to standard input of the Python interpreter.
214
Guido van Rossumb2c65561993-05-12 08:53:36 +0000215When a script file is used, it is sometimes useful to be able to run
216the script and enter interactive mode afterwards. This can be done by
Fred Drakeeee08cd1997-12-04 15:43:15 +0000217passing \code{-i} before the script. (This does not work if the script
Guido van Rossumb2c65561993-05-12 08:53:36 +0000218is read from standard input, for the same reason as explained in the
219previous paragraph.)
220
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000221\subsection{Argument Passing}
Fred Drake6c2176e1998-02-26 21:47:54 +0000222\label{argPassing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000223
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000224When known to the interpreter, the script name and additional
Fred Drakeeee08cd1997-12-04 15:43:15 +0000225arguments thereafter are passed to the script in the variable
226\code{sys.argv}, which is a list of strings. Its length is at least
227one; when no script and no arguments are given, \code{sys.argv[0]} is
228an empty string. When the script name is given as \code{'-'} (meaning
229standard input), \code{sys.argv[0]} is set to \code{'-'}. When \code{-c
230command} is used, \code{sys.argv[0]} is set to \code{'-c'}. Options
231found after \code{-c command} are not consumed by the Python
232interpreter's option processing but left in \code{sys.argv} for the
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000233command to handle.
234
235\subsection{Interactive Mode}
Fred Drake6c2176e1998-02-26 21:47:54 +0000236\label{interactive}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000237
Guido van Rossumdd010801991-06-07 14:31:11 +0000238When commands are read from a tty, the interpreter is said to be in
Fred Drakeeee08cd1997-12-04 15:43:15 +0000239\emph{interactive mode}. In this mode it prompts for the next command
240with the \emph{primary prompt}, usually three greater-than signs
Fred Drake8842e861998-02-13 07:16:30 +0000241(\samp{>>> }); for continuation lines it prompts with the
Fred Drakeeee08cd1997-12-04 15:43:15 +0000242\emph{secondary prompt},
Fred Drake8842e861998-02-13 07:16:30 +0000243by default three dots (\samp{... }).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000244
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000245The interpreter prints a welcome message stating its version number
246and a copyright notice before printing the first prompt, e.g.:
247
Fred Drake8842e861998-02-13 07:16:30 +0000248\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000249python
Fred Drakeeee08cd1997-12-04 15:43:15 +0000250Python 1.5b1 (#1, Dec 3 1997, 00:02:06) [GCC 2.7.2.2] on sunos5
251Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000252>>>
Fred Drake8842e861998-02-13 07:16:30 +0000253\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000254
Fred Drakea594baf1998-04-03 05:16:31 +0000255\section{The Interpreter and Its Environment}
Fred Drake6c2176e1998-02-26 21:47:54 +0000256\label{interp}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000257
258\subsection{Error Handling}
Fred Drake6c2176e1998-02-26 21:47:54 +0000259\label{error}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000260
261When an error occurs, the interpreter prints an error
262message and a stack trace. In interactive mode, it then returns to
263the primary prompt; when input came from a file, it exits with a
264nonzero exit status after printing
Fred Drakeeee08cd1997-12-04 15:43:15 +0000265the stack trace. (Exceptions handled by an \code{except} clause in a
266\code{try} statement are not errors in this context.) Some errors are
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000267unconditionally fatal and cause an exit with a nonzero exit; this
268applies to internal inconsistencies and some cases of running out of
269memory. All error messages are written to the standard error stream;
270normal output from the executed commands is written to standard
271output.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000272
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000273Typing the interrupt character (usually Control-C or DEL) to the
274primary or secondary prompt cancels the input and returns to the
275primary prompt.%
276\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +0000277 A problem with the GNU Readline package may prevent this.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000278}
Fred Drakeeee08cd1997-12-04 15:43:15 +0000279Typing an interrupt while a command is executing raises the
280\code{KeyboardInterrupt} exception, which may be handled by a
281\code{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000282
Fred Drakea594baf1998-04-03 05:16:31 +0000283\subsection{Executable Python Scripts}
Fred Drake6c2176e1998-02-26 21:47:54 +0000284\label{scripts}
Guido van Rossum4410c751991-06-04 20:22:18 +0000285
Fred Drake6dc2aae1996-12-13 21:56:03 +0000286On BSD'ish \UNIX{} systems, Python scripts can be made directly
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000287executable, like shell scripts, by putting the line
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000288
Fred Drake8842e861998-02-13 07:16:30 +0000289\begin{verbatim}
Fred Drake9e63faa1997-10-15 14:37:24 +0000290#! /usr/bin/env python
Fred Drake8842e861998-02-13 07:16:30 +0000291\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000292
Fred Drake391564f1998-04-01 23:11:56 +0000293(assuming that the interpreter is on the user's \envvar{PATH}) at the
294beginning of the script and giving the file an executable mode. The
295\samp{\#!} must be the first two characters of the file.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000296
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000297\subsection{The Interactive Startup File}
Fred Drake6c2176e1998-02-26 21:47:54 +0000298\label{startup}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000299
Fred Drake8842e861998-02-13 07:16:30 +0000300% XXX This should probably be dumped in an appendix, since most people
301% don't use Python interactively in non-trivial ways.
Guido van Rossum02455691997-07-17 16:21:52 +0000302
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000303When you use Python interactively, it is frequently handy to have some
304standard commands executed every time the interpreter is started. You
Fred Drakeeee08cd1997-12-04 15:43:15 +0000305can do this by setting an environment variable named
Fred Drake391564f1998-04-01 23:11:56 +0000306\envvar{PYTHONSTARTUP} to the name of a file containing your start-up
Fred Drakeeee08cd1997-12-04 15:43:15 +0000307commands. This is similar to the \file{.profile} feature of the \UNIX{}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000308shells.
309
310This file is only read in interactive sessions, not when Python reads
Fred Drakeeee08cd1997-12-04 15:43:15 +0000311commands from a script, and not when \file{/dev/tty} is given as the
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000312explicit source of commands (which otherwise behaves like an
313interactive session). It is executed in the same name space where
314interactive commands are executed, so that objects that it defines or
315imports can be used without qualification in the interactive session.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000316You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in
Guido van Rossum7b3c8a11992-09-08 09:20:13 +0000317this file.
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000318
319If you want to read an additional start-up file from the current
Fred Drake72389881998-04-13 01:31:10 +0000320directory, you can program this in the global start-up file,
321e.g.\ \samp{execfile('.pythonrc')}\indexii{.pythonrc.py}{file}. If
322you want to use the startup file in a script, you must do this
323explicitly in the script:
Fred Drake8842e861998-02-13 07:16:30 +0000324
325\begin{verbatim}
326import os
Fred Drake72389881998-04-13 01:31:10 +0000327if os.path.isfile(os.environ['PYTHONSTARTUP']):
328 execfile(os.environ['PYTHONSTARTUP'])
Fred Drake8842e861998-02-13 07:16:30 +0000329\end{verbatim}
Guido van Rossum9a4e3fc1992-09-03 21:27:55 +0000330
Fred Drake72389881998-04-13 01:31:10 +0000331
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000332\chapter{An Informal Introduction to Python}
Fred Drake6c2176e1998-02-26 21:47:54 +0000333\label{informal}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000334
335In the following examples, input and output are distinguished by the
Fred Drake8842e861998-02-13 07:16:30 +0000336presence or absence of prompts (\samp{>>> } and \samp{... }): to repeat
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000337the example, you must type everything after the prompt, when the
338prompt appears; lines that do not begin with a prompt are output from
339the interpreter.%
Guido van Rossum02455691997-07-17 16:21:52 +0000340%\footnote{
341% I'd prefer to use different fonts to distinguish input
342% from output, but the amount of LaTeX hacking that would require
343% is currently beyond my ability.
344%}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000345Note that a secondary prompt on a line by itself in an example means
346you must type a blank line; this is used to end a multi-line command.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000347
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000348\section{Using Python as a Calculator}
Fred Drake6c2176e1998-02-26 21:47:54 +0000349\label{calculator}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000350
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000351Let's try some simple Python commands. Start the interpreter and wait
Fred Drake8842e861998-02-13 07:16:30 +0000352for the primary prompt, \samp{>>> }. (It shouldn't take long.)
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000353
354\subsection{Numbers}
Fred Drake6c2176e1998-02-26 21:47:54 +0000355\label{numbers}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000356
357The interpreter acts as a simple calculator: you can type an
358expression at it and it will write the value. Expression syntax is
Fred Drakeeee08cd1997-12-04 15:43:15 +0000359straightforward: the operators \code{+}, \code{-}, \code{*} and \code{/}
Fred Drake3f205921998-01-13 18:56:38 +0000360work just like in most other languages (e.g., Pascal or \C{}); parentheses
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000361can be used for grouping. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000362
Fred Drake8842e861998-02-13 07:16:30 +0000363\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000364>>> 2+2
3654
Guido van Rossum6938f061994-08-01 12:22:53 +0000366>>> # This is a comment
367... 2+2
3684
369>>> 2+2 # and a comment on the same line as code
3704
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000371>>> (50-5*6)/4
3725
Guido van Rossum6938f061994-08-01 12:22:53 +0000373>>> # Integer division returns the floor:
374... 7/3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003752
Guido van Rossum6938f061994-08-01 12:22:53 +0000376>>> 7/-3
377-3
Fred Drake8842e861998-02-13 07:16:30 +0000378\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000379
Fred Drake391564f1998-04-01 23:11:56 +0000380Like in \C{}, the equal sign (\character{=}) is used to assign a value to a
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000381variable. The value of an assignment is not written:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000382
Fred Drake8842e861998-02-13 07:16:30 +0000383\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000384>>> width = 20
385>>> height = 5*9
386>>> width * height
387900
Fred Drake8842e861998-02-13 07:16:30 +0000388\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000389%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000390A value can be assigned to several variables simultaneously:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000391
Fred Drake8842e861998-02-13 07:16:30 +0000392\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +0000393>>> x = y = z = 0 # Zero x, y and z
394>>> x
3950
396>>> y
3970
398>>> z
3990
Fred Drake8842e861998-02-13 07:16:30 +0000400\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000401%
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000402There is full support for floating point; operators with mixed type
403operands convert the integer operand to floating point:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000404
Fred Drake8842e861998-02-13 07:16:30 +0000405\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000406>>> 4 * 2.5 / 3.3
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00004073.0303030303
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000408>>> 7.0 / 2
4093.5
Fred Drake8842e861998-02-13 07:16:30 +0000410\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000411%
412Complex numbers are also supported; imaginary numbers are written with
Fred Drake8842e861998-02-13 07:16:30 +0000413a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero
414real component are written as \samp{(\var{real}+\var{imag}j)}, or can
415be created with the \samp{complex(\var{real}, \var{imag})} function.
Guido van Rossum02455691997-07-17 16:21:52 +0000416
Fred Drake8842e861998-02-13 07:16:30 +0000417\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000418>>> 1j * 1J
419(-1+0j)
420>>> 1j * complex(0,1)
421(-1+0j)
422>>> 3+1j*3
423(3+3j)
424>>> (3+1j)*3
425(9+3j)
426>>> (1+2j)/(1+1j)
427(1.5+0.5j)
Fred Drake8842e861998-02-13 07:16:30 +0000428\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000429%
430Complex numbers are always represented as two floating point numbers,
431the real and imaginary part. To extract these parts from a complex
Fred Drake8842e861998-02-13 07:16:30 +0000432number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}.
Guido van Rossum02455691997-07-17 16:21:52 +0000433
Fred Drake8842e861998-02-13 07:16:30 +0000434\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000435>>> a=1.5+0.5j
436>>> a.real
4371.5
438>>> a.imag
4390.5
Fred Drake8842e861998-02-13 07:16:30 +0000440\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000441%
442The conversion functions to floating point and integer
Fred Drake8842e861998-02-13 07:16:30 +0000443(\function{float()}, \function{int()} and \function{long()}) don't
444work for complex numbers --- there is no one correct way to convert a
445complex number to a real number. Use \code{abs(\var{z})} to get its
446magnitude (as a float) or \code{z.real} to get its real part.
Guido van Rossum02455691997-07-17 16:21:52 +0000447
Fred Drake8842e861998-02-13 07:16:30 +0000448\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000449>>> a=1.5+0.5j
450>>> float(a)
451Traceback (innermost last):
452 File "<stdin>", line 1, in ?
453TypeError: can't convert complex to float; use e.g. abs(z)
454>>> a.real
4551.5
456>>> abs(a)
4571.58113883008
Fred Drake8842e861998-02-13 07:16:30 +0000458\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000459%
460In interactive mode, the last printed expression is assigned to the
461variable \code{_}. This means that when you are using Python as a
462desk calculator, it is somewhat easier to continue calculations, for
463example:
464
465\begin{verbatim}
466>>> tax = 17.5 / 100
467>>> price = 3.50
468>>> price * tax
4690.6125
470>>> price + _
4714.1125
472>>> round(_, 2)
4734.11
474\end{verbatim}
475
476This variable should be treated as read-only by the user. Don't
477explicitly assign a value to it --- you would create an independent
478local variable with the same name masking the built-in variable with
479its magic behavior.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000480
481\subsection{Strings}
Fred Drake6c2176e1998-02-26 21:47:54 +0000482\label{strings}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000483
Guido van Rossum02455691997-07-17 16:21:52 +0000484Besides numbers, Python can also manipulate strings, which can be
485expressed in several ways. They can be enclosed in single quotes or
486double quotes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000487
Fred Drake8842e861998-02-13 07:16:30 +0000488\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000489>>> 'spam eggs'
490'spam eggs'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000491>>> 'doesn\'t'
Guido van Rossum6938f061994-08-01 12:22:53 +0000492"doesn't"
493>>> "doesn't"
494"doesn't"
495>>> '"Yes," he said.'
496'"Yes," he said.'
497>>> "\"Yes,\" he said."
498'"Yes," he said.'
499>>> '"Isn\'t," she said.'
500'"Isn\'t," she said.'
Fred Drake8842e861998-02-13 07:16:30 +0000501\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000502
Fred Drake8842e861998-02-13 07:16:30 +0000503String literals can span multiple lines in several ways. Newlines can
504be escaped with backslashes, e.g.:
Guido van Rossum02455691997-07-17 16:21:52 +0000505
506\begin{verbatim}
507hello = "This is a rather long string containing\n\
508several lines of text just as you would do in C.\n\
509 Note that whitespace at the beginning of the line is\
510 significant.\n"
511print hello
512\end{verbatim}
513
514which would print the following:
Fred Drake8842e861998-02-13 07:16:30 +0000515
Guido van Rossum02455691997-07-17 16:21:52 +0000516\begin{verbatim}
517This is a rather long string containing
518several lines of text just as you would do in C.
519 Note that whitespace at the beginning of the line is significant.
520\end{verbatim}
521
522Or, strings can be surrounded in a pair of matching triple-quotes:
523\code{"""} or \code {'''}. End of lines do not need to be escaped
524when using triple-quotes, but they will be included in the string.
525
526\begin{verbatim}
527print """
528Usage: thingy [OPTIONS]
529 -h Display this usage message
530 -H hostname Hostname to connect to
531"""
532\end{verbatim}
533
534produces the following output:
535
Fred Drake8842e861998-02-13 07:16:30 +0000536\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +0000537Usage: thingy [OPTIONS]
538 -h Display this usage message
539 -H hostname Hostname to connect to
Fred Drake8842e861998-02-13 07:16:30 +0000540\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000541
Guido van Rossum02455691997-07-17 16:21:52 +0000542The interpreter prints the result of string operations in the same way
543as they are typed for input: inside quotes, and with quotes and other
544funny characters escaped by backslashes, to show the precise
545value. The string is enclosed in double quotes if the string contains
546a single quote and no double quotes, else it's enclosed in single
Fred Drake8842e861998-02-13 07:16:30 +0000547quotes. (The \keyword{print} statement, described later, can be used
548to write strings without quotes or escapes.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000549
Fred Drakeeee08cd1997-12-04 15:43:15 +0000550Strings can be concatenated (glued together) with the \code{+}
551operator, and repeated with \code{*}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000552
Fred Drake8842e861998-02-13 07:16:30 +0000553\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000554>>> word = 'Help' + 'A'
555>>> word
556'HelpA'
557>>> '<' + word*5 + '>'
558'<HelpAHelpAHelpAHelpAHelpA>'
Fred Drake8842e861998-02-13 07:16:30 +0000559\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000560
Guido van Rossum02455691997-07-17 16:21:52 +0000561Two string literals next to each other are automatically concatenated;
Fred Drake8842e861998-02-13 07:16:30 +0000562the first line above could also have been written \samp{word = 'Help'
Guido van Rossum02455691997-07-17 16:21:52 +0000563'A'}; this only works with two literals, not with arbitrary string expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000564
Fred Drake3f205921998-01-13 18:56:38 +0000565Strings can be subscripted (indexed); like in \C{}, the first character
Guido van Rossum02455691997-07-17 16:21:52 +0000566of a string has subscript (index) 0. There is no separate character
567type; a character is simply a string of size one. Like in Icon,
Fred Drake8842e861998-02-13 07:16:30 +0000568substrings can be specified with the \emph{slice notation}: two indices
Guido van Rossum02455691997-07-17 16:21:52 +0000569separated by a colon.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000570
Fred Drake8842e861998-02-13 07:16:30 +0000571\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000572>>> word[4]
573'A'
574>>> word[0:2]
575'He'
576>>> word[2:4]
577'lp'
Fred Drake8842e861998-02-13 07:16:30 +0000578\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000579
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000580Slice indices have useful defaults; an omitted first index defaults to
581zero, an omitted second index defaults to the size of the string being
582sliced.
583
Fred Drake8842e861998-02-13 07:16:30 +0000584\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000585>>> word[:2] # The first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000586'He'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000587>>> word[2:] # All but the first two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000588'lpA'
Fred Drake8842e861998-02-13 07:16:30 +0000589\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000590
Fred Drakeeee08cd1997-12-04 15:43:15 +0000591Here's a useful invariant of slice operations: \code{s[:i] + s[i:]}
592equals \code{s}.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000593
Fred Drake8842e861998-02-13 07:16:30 +0000594\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000595>>> word[:2] + word[2:]
596'HelpA'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000597>>> word[:3] + word[3:]
598'HelpA'
Fred Drake8842e861998-02-13 07:16:30 +0000599\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000600
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000601Degenerate slice indices are handled gracefully: an index that is too
602large is replaced by the string size, an upper bound smaller than the
603lower bound returns an empty string.
604
Fred Drake8842e861998-02-13 07:16:30 +0000605\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000606>>> word[1:100]
607'elpA'
608>>> word[10:]
609''
610>>> word[2:1]
611''
Fred Drake8842e861998-02-13 07:16:30 +0000612\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000613
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000614Indices may be negative numbers, to start counting from the right.
615For example:
616
Fred Drake8842e861998-02-13 07:16:30 +0000617\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000618>>> word[-1] # The last character
619'A'
620>>> word[-2] # The last-but-one character
621'p'
622>>> word[-2:] # The last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000623'pA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000624>>> word[:-2] # All but the last two characters
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000625'Hel'
Fred Drake8842e861998-02-13 07:16:30 +0000626\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000627
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000628But note that -0 is really the same as 0, so it does not count from
629the right!
630
Fred Drake8842e861998-02-13 07:16:30 +0000631\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000632>>> word[-0] # (since -0 equals 0)
633'H'
Fred Drake8842e861998-02-13 07:16:30 +0000634\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000635
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000636Out-of-range negative slice indices are truncated, but don't try this
637for single-element (non-slice) indices:
638
Fred Drake8842e861998-02-13 07:16:30 +0000639\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000640>>> word[-100:]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000641'HelpA'
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000642>>> word[-10] # error
Guido van Rossum6938f061994-08-01 12:22:53 +0000643Traceback (innermost last):
644 File "<stdin>", line 1
645IndexError: string index out of range
Fred Drake8842e861998-02-13 07:16:30 +0000646\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000647
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000648The best way to remember how slices work is to think of the indices as
Fred Drakeeee08cd1997-12-04 15:43:15 +0000649pointing \emph{between} characters, with the left edge of the first
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000650character numbered 0. Then the right edge of the last character of a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000651string of \var{n} characters has index \var{n}, for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000652
Fred Drake8842e861998-02-13 07:16:30 +0000653\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000654 +---+---+---+---+---+
655 | H | e | l | p | A |
656 +---+---+---+---+---+
657 0 1 2 3 4 5
658-5 -4 -3 -2 -1
Fred Drake8842e861998-02-13 07:16:30 +0000659\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000660
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000661The first row of numbers gives the position of the indices 0...5 in
662the string; the second row gives the corresponding negative indices.
Fred Drakeeee08cd1997-12-04 15:43:15 +0000663The slice from \var{i} to \var{j} consists of all characters between
664the edges labeled \var{i} and \var{j}, respectively.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000665
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000666For nonnegative indices, the length of a slice is the difference of
667the indices, if both are within bounds, e.g., the length of
Fred Drakeeee08cd1997-12-04 15:43:15 +0000668\code{word[1:3]} is 2.
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000669
Fred Drake8842e861998-02-13 07:16:30 +0000670The built-in function \function{len()} returns the length of a string:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000671
Fred Drake8842e861998-02-13 07:16:30 +0000672\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000673>>> s = 'supercalifragilisticexpialidocious'
674>>> len(s)
67534
Fred Drake8842e861998-02-13 07:16:30 +0000676\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000677
678\subsection{Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +0000679\label{lists}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000680
Fred Drakeeee08cd1997-12-04 15:43:15 +0000681Python knows a number of \emph{compound} data types, used to group
682together other values. The most versatile is the \emph{list}, which
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000683can be written as a list of comma-separated values (items) between
684square brackets. List items need not all have the same type.
685
Fred Drake8842e861998-02-13 07:16:30 +0000686\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +0000687>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000688>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000689['spam', 'eggs', 100, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000690\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000691
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000692Like string indices, list indices start at 0, and lists can be sliced,
693concatenated and so on:
694
Fred Drake8842e861998-02-13 07:16:30 +0000695\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000696>>> a[0]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000697'spam'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000698>>> a[3]
6991234
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000700>>> a[-2]
701100
702>>> a[1:-1]
Guido van Rossume5f8b601995-01-04 19:12:49 +0000703['eggs', 100]
704>>> a[:2] + ['bacon', 2*2]
705['spam', 'eggs', 'bacon', 4]
Guido van Rossum4410c751991-06-04 20:22:18 +0000706>>> 3*a[:3] + ['Boe!']
Guido van Rossume5f8b601995-01-04 19:12:49 +0000707['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!']
Fred Drake8842e861998-02-13 07:16:30 +0000708\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000709
Fred Drakeeee08cd1997-12-04 15:43:15 +0000710Unlike strings, which are \emph{immutable}, it is possible to change
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000711individual elements of a list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000712
Fred Drake8842e861998-02-13 07:16:30 +0000713\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000714>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000715['spam', 'eggs', 100, 1234]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000716>>> a[2] = a[2] + 23
717>>> a
Guido van Rossume5f8b601995-01-04 19:12:49 +0000718['spam', 'eggs', 123, 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000719\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000720
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000721Assignment to slices is also possible, and this can even change the size
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000722of the list:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000723
Fred Drake8842e861998-02-13 07:16:30 +0000724\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000725>>> # Replace some items:
Guido van Rossum6938f061994-08-01 12:22:53 +0000726... a[0:2] = [1, 12]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000727>>> a
728[1, 12, 123, 1234]
729>>> # Remove some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000730... a[0:2] = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000731>>> a
732[123, 1234]
733>>> # Insert some:
Guido van Rossum6938f061994-08-01 12:22:53 +0000734... a[1:1] = ['bletch', 'xyzzy']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000735>>> a
736[123, 'bletch', 'xyzzy', 1234]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000737>>> a[:0] = a # Insert (a copy of) itself at the beginning
738>>> a
739[123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234]
Fred Drake8842e861998-02-13 07:16:30 +0000740\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000741
Fred Drake8842e861998-02-13 07:16:30 +0000742The built-in function \function{len()} also applies to lists:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000743
Fred Drake8842e861998-02-13 07:16:30 +0000744\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000745>>> len(a)
Guido van Rossuma8d754e1992-01-07 16:44:35 +00007468
Fred Drake8842e861998-02-13 07:16:30 +0000747\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000748
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000749It is possible to nest lists (create lists containing other lists),
750for example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000751
Fred Drake8842e861998-02-13 07:16:30 +0000752\begin{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000753>>> q = [2, 3]
754>>> p = [1, q, 4]
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000755>>> len(p)
7563
757>>> p[1]
758[2, 3]
759>>> p[1][0]
7602
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000761>>> p[1].append('xtra') # See section 5.1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000762>>> p
763[1, [2, 3, 'xtra'], 4]
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000764>>> q
765[2, 3, 'xtra']
Fred Drake8842e861998-02-13 07:16:30 +0000766\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000767
Fred Drakeeee08cd1997-12-04 15:43:15 +0000768Note that in the last example, \code{p[1]} and \code{q} really refer to
769the same object! We'll come back to \emph{object semantics} later.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000770
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000771\section{First Steps Towards Programming}
Fred Drake6c2176e1998-02-26 21:47:54 +0000772\label{firstSteps}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000773
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000774Of course, we can use Python for more complicated tasks than adding
775two and two together. For instance, we can write an initial
Fred Drakeeee08cd1997-12-04 15:43:15 +0000776subsequence of the \emph{Fibonacci} series as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000777
Fred Drake8842e861998-02-13 07:16:30 +0000778\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000779>>> # Fibonacci series:
Guido van Rossum6938f061994-08-01 12:22:53 +0000780... # the sum of two elements defines the next
781... a, b = 0, 1
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000782>>> while b < 10:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000783... print b
784... a, b = b, a+b
785...
7861
7871
7882
7893
7905
7918
Fred Drake8842e861998-02-13 07:16:30 +0000792\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000793
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000794This example introduces several new features.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000795
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000796\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000797
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000798\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000799The first line contains a \emph{multiple assignment}: the variables
800\code{a} and \code{b} simultaneously get the new values 0 and 1. On the
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000801last line this is used again, demonstrating that the expressions on
802the right-hand side are all evaluated first before any of the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000803assignments take place.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000804
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000805\item
Fred Drake8842e861998-02-13 07:16:30 +0000806The \keyword{while} loop executes as long as the condition (here:
807\code{b < 10}) remains true. In Python, like in \C{}, any non-zero
808integer value is true; zero is false. The condition may also be a
809string or list value, in fact any sequence; anything with a non-zero
810length is true, empty sequences are false. The test used in the
811example is a simple comparison. The standard comparison operators are
812written the same as in \C{}: \code{<}, \code{>}, \code{==}, \code{<=},
813\code{>=} and \code{!=}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000814
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000815\item
Fred Drakeeee08cd1997-12-04 15:43:15 +0000816The \emph{body} of the loop is \emph{indented}: indentation is Python's
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000817way of grouping statements. Python does not (yet!) provide an
818intelligent input line editing facility, so you have to type a tab or
819space(s) for each indented line. In practice you will prepare more
820complicated input for Python with a text editor; most text editors have
821an auto-indent facility. When a compound statement is entered
822interactively, it must be followed by a blank line to indicate
823completion (since the parser cannot guess when you have typed the last
824line).
825
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000826\item
Fred Drake8842e861998-02-13 07:16:30 +0000827The \keyword{print} statement writes the value of the expression(s) it is
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000828given. It differs from just writing the expression you want to write
829(as we did earlier in the calculator examples) in the way it handles
Guido van Rossum16cd7f91994-10-06 10:29:26 +0000830multiple expressions and strings. Strings are printed without quotes,
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000831and a space is inserted between items, so you can format things nicely,
832like this:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000833
Fred Drake8842e861998-02-13 07:16:30 +0000834\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000835>>> i = 256*256
836>>> print 'The value of i is', i
837The value of i is 65536
Fred Drake8842e861998-02-13 07:16:30 +0000838\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000839
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000840A trailing comma avoids the newline after the output:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000841
Fred Drake8842e861998-02-13 07:16:30 +0000842\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000843>>> a, b = 0, 1
844>>> while b < 1000:
845... print b,
846... a, b = b, a+b
847...
8481 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
Fred Drake8842e861998-02-13 07:16:30 +0000849\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000850
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000851Note that the interpreter inserts a newline before it prints the next
852prompt if the last line was not completed.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000853
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000854\end{itemize}
855
Guido van Rossum5e0759d1992-08-07 16:06:24 +0000856
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000857\chapter{More Control Flow Tools}
Fred Drake6c2176e1998-02-26 21:47:54 +0000858\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 Drake391564f1998-04-01 23:11:56 +0000864\section{\keyword{if} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +0000865\label{if}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000866
Fred Drake8842e861998-02-13 07:16:30 +0000867Perhaps the most well-known statement type is the \keyword{if}
868statement. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000869
Fred Drake8842e861998-02-13 07:16:30 +0000870\begin{verbatim}
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 Drake391564f1998-04-01 23:11:56 +0000893\section{\keyword{for} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +0000894\label{for}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000895
Fred Drake8842e861998-02-13 07:16:30 +0000896The \keyword{for} statement in Python differs a bit from what you may be
Fred Drake3f205921998-01-13 18:56:38 +0000897used to in \C{} or Pascal. Rather than always iterating over an
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000898arithmetic progression of numbers (like in Pascal), or leaving the user
Fred Drake3f205921998-01-13 18:56:38 +0000899completely free in the iteration test and step (as \C{}), Python's
Fred Drake8842e861998-02-13 07:16:30 +0000900\keyword{for} statement iterates over the items of any sequence (e.g., a
Fred Drakeeee08cd1997-12-04 15:43:15 +0000901list or a string), in the order that they appear in the sequence. For
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000902example (no pun intended):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000903
Fred Drake8842e861998-02-13 07:16:30 +0000904\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000905>>> # Measure some strings:
Guido van Rossum6938f061994-08-01 12:22:53 +0000906... a = ['cat', 'window', 'defenestrate']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000907>>> for x in a:
908... print x, len(x)
909...
910cat 3
911window 6
912defenestrate 12
Fred Drake8842e861998-02-13 07:16:30 +0000913\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000914
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000915It is not safe to modify the sequence being iterated over in the loop
916(this can only happen for mutable sequence types, i.e., lists). If
917you need to modify the list you are iterating over, e.g., duplicate
918selected items, you must iterate over a copy. The slice notation
919makes this particularly convenient:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000920
Fred Drake8842e861998-02-13 07:16:30 +0000921\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000922>>> for x in a[:]: # make a slice copy of the entire list
923... if len(x) > 6: a.insert(0, x)
924...
925>>> a
926['defenestrate', 'cat', 'window', 'defenestrate']
Fred Drake8842e861998-02-13 07:16:30 +0000927\end{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000928
Fred Drakee7957181998-04-04 07:17:47 +0000929\section{The \function{range()} Function}
Fred Drake6c2176e1998-02-26 21:47:54 +0000930\label{range}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000931
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000932If you do need to iterate over a sequence of numbers, the built-in
Fred Drake8842e861998-02-13 07:16:30 +0000933function \function{range()} comes in handy. It generates lists
934containing arithmetic progressions, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000935
Fred Drake8842e861998-02-13 07:16:30 +0000936\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000937>>> range(10)
938[0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Fred Drake8842e861998-02-13 07:16:30 +0000939\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000940
Fred Drake8842e861998-02-13 07:16:30 +0000941The given end point is never part of the generated list;
942\code{range(10)} generates a list of 10 values, exactly the legal
943indices for items of a sequence of length 10. It is possible to let
944the range start at another number, or to specify a different increment
945(even negative):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000946
Fred Drake8842e861998-02-13 07:16:30 +0000947\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000948>>> range(5, 10)
949[5, 6, 7, 8, 9]
950>>> range(0, 10, 3)
951[0, 3, 6, 9]
952>>> range(-10, -100, -30)
953[-10, -40, -70]
Fred Drake8842e861998-02-13 07:16:30 +0000954\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +0000955
Fred Drake8842e861998-02-13 07:16:30 +0000956To iterate over the indices of a sequence, combine \function{range()}
957and \function{len()} as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000958
Fred Drake8842e861998-02-13 07:16:30 +0000959\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000960>>> a = ['Mary', 'had', 'a', 'little', 'lamb']
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000961>>> for i in range(len(a)):
962... print i, a[i]
963...
9640 Mary
9651 had
9662 a
9673 little
Guido van Rossum6fc178f1991-08-16 09:13:42 +00009684 lamb
Fred Drake8842e861998-02-13 07:16:30 +0000969\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000970
Fred Drake391564f1998-04-01 23:11:56 +0000971\section{\keyword{break} and \keyword{continue} Statements, and
972 \keyword{else} Clauses on Loops}
Fred Drake6c2176e1998-02-26 21:47:54 +0000973\label{break}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000974
Fred Drake8842e861998-02-13 07:16:30 +0000975The \keyword{break} statement, like in \C{}, breaks out of the smallest
976enclosing \keyword{for} or \keyword{while} loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000977
Fred Drake8842e861998-02-13 07:16:30 +0000978The \keyword{continue} statement, also borrowed from \C{}, continues
979with the next iteration of the loop.
Guido van Rossum6fc178f1991-08-16 09:13:42 +0000980
Fred Drake8842e861998-02-13 07:16:30 +0000981Loop statements may have an \code{else} clause; it is executed when
982the loop terminates through exhaustion of the list (with
983\keyword{for}) or when the condition becomes false (with
984\keyword{while}), but not when the loop is terminated by a
985\keyword{break} statement. This is exemplified by the following loop,
986which searches for prime numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000987
Fred Drake8842e861998-02-13 07:16:30 +0000988\begin{verbatim}
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000989>>> for n in range(2, 10):
990... for x in range(2, n):
Guido van Rossuma8d754e1992-01-07 16:44:35 +0000991... if n % x == 0:
Guido van Rossum2292b8e1991-01-23 16:31:24 +0000992... print n, 'equals', x, '*', n/x
993... break
994... else:
995... print n, 'is a prime number'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +0000996...
Guido van Rossum2292b8e1991-01-23 16:31:24 +00009972 is a prime number
9983 is a prime number
9994 equals 2 * 2
10005 is a prime number
10016 equals 2 * 3
10027 is a prime number
10038 equals 2 * 4
10049 equals 3 * 3
Fred Drake8842e861998-02-13 07:16:30 +00001005\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001006
Fred Drake391564f1998-04-01 23:11:56 +00001007\section{\keyword{pass} Statements}
Fred Drake6c2176e1998-02-26 21:47:54 +00001008\label{pass}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001009
Fred Drake8842e861998-02-13 07:16:30 +00001010The \keyword{pass} statement does nothing.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001011It can be used when a statement is required syntactically but the
1012program requires no action.
1013For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001014
Fred Drake8842e861998-02-13 07:16:30 +00001015\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001016>>> while 1:
1017... pass # Busy-wait for keyboard interrupt
1018...
Fred Drake8842e861998-02-13 07:16:30 +00001019\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001020
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001021\section{Defining Functions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001022\label{functions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001023
1024We can create a function that writes the Fibonacci series to an
1025arbitrary boundary:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001026
Fred Drake8842e861998-02-13 07:16:30 +00001027\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001028>>> def fib(n): # write Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001029... "Print a Fibonacci series up to n"
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001030... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001031... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001032... print b,
1033... a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001034...
1035>>> # Now call the function we just defined:
Guido van Rossum6938f061994-08-01 12:22:53 +00001036... fib(2000)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000010371 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597
Fred Drake8842e861998-02-13 07:16:30 +00001038\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001039
Fred Drake8842e861998-02-13 07:16:30 +00001040The keyword \keyword{def} introduces a function \emph{definition}. It
1041must be followed by the function name and the parenthesized list of
1042formal parameters. The statements that form the body of the function
1043start at the next line, indented by a tab stop. The first statement
1044of the function body can optionally be a string literal; this string
1045literal is the function's documentation string, or \dfn{docstring}.
1046There are tools which use docstrings to automatically produce printed
Guido van Rossum02455691997-07-17 16:21:52 +00001047documentation, or to let the user interactively browse through code;
1048it's good practice to include docstrings in code that you write, so
1049try to make a habit of it.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001050
Fred Drakeeee08cd1997-12-04 15:43:15 +00001051The \emph{execution} of a function introduces a new symbol table used
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001052for the local variables of the function. More precisely, all variable
1053assignments in a function store the value in the local symbol table;
Guido van Rossum02455691997-07-17 16:21:52 +00001054whereas variable references first look in the local symbol table, then
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001055in the global symbol table, and then in the table of built-in names.
Fred Drake8842e861998-02-13 07:16:30 +00001056Thus, global variables cannot be directly assigned a value within a
1057function (unless named in a \keyword{global} statement), although
Guido van Rossum6938f061994-08-01 12:22:53 +00001058they may be referenced.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001059
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001060The actual parameters (arguments) to a function call are introduced in
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001061the local symbol table of the called function when it is called; thus,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001062arguments are passed using \emph{call by value}.%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001063\footnote{
Fred Drakeeee08cd1997-12-04 15:43:15 +00001064 Actually, \emph{call by object reference} would be a better
Guido van Rossum6938f061994-08-01 12:22:53 +00001065 description, since if a mutable object is passed, the caller
1066 will see any changes the callee makes to it (e.g., items
1067 inserted into a list).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001068}
1069When a function calls another function, a new local symbol table is
1070created for that call.
1071
Fred Drake8842e861998-02-13 07:16:30 +00001072A function definition introduces the function name in the current
1073symbol table. The value of the function name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001074has a type that is recognized by the interpreter as a user-defined
1075function. This value can be assigned to another name which can then
1076also be used as a function. This serves as a general renaming
1077mechanism:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001078
Fred Drake8842e861998-02-13 07:16:30 +00001079\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001080>>> fib
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001081<function object at 10042ed0>
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001082>>> f = fib
1083>>> f(100)
10841 1 2 3 5 8 13 21 34 55 89
Fred Drake8842e861998-02-13 07:16:30 +00001085\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001086
Fred Drakeeee08cd1997-12-04 15:43:15 +00001087You might object that \code{fib} is not a function but a procedure. In
Fred Drake3f205921998-01-13 18:56:38 +00001088Python, like in \C{}, procedures are just functions that don't return a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001089value. In fact, technically speaking, procedures do return a value,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001090albeit a rather boring one. This value is called \code{None} (it's a
1091built-in name). Writing the value \code{None} is normally suppressed by
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001092the interpreter if it would be the only value written. You can see it
1093if you really want to:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001094
Fred Drake8842e861998-02-13 07:16:30 +00001095\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001096>>> print fib(0)
1097None
Fred Drake8842e861998-02-13 07:16:30 +00001098\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001099
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001100It is simple to write a function that returns a list of the numbers of
1101the Fibonacci series, instead of printing it:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001102
Fred Drake8842e861998-02-13 07:16:30 +00001103\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001104>>> def fib2(n): # return Fibonacci series up to n
Guido van Rossum02455691997-07-17 16:21:52 +00001105... "Return a list containing the Fibonacci series up to n"
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001106... result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001107... a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001108... while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001109... result.append(b) # see below
1110... a, b = b, a+b
Guido van Rossum2292b8e1991-01-23 16:31:24 +00001111... return result
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001112...
1113>>> f100 = fib2(100) # call it
1114>>> f100 # write the result
1115[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Fred Drake8842e861998-02-13 07:16:30 +00001116\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001117%
Guido van Rossum4410c751991-06-04 20:22:18 +00001118This example, as usual, demonstrates some new Python features:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001119
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001120\begin{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001121
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001122\item
Fred Drake8842e861998-02-13 07:16:30 +00001123The \keyword{return} statement returns with a value from a function.
1124\keyword{return} without an expression argument is used to return from
Fred Drakeeee08cd1997-12-04 15:43:15 +00001125the middle of a procedure (falling off the end also returns from a
1126procedure), in which case the \code{None} value is returned.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001127
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001128\item
Fred Drakeeee08cd1997-12-04 15:43:15 +00001129The statement \code{result.append(b)} calls a \emph{method} of the list
1130object \code{result}. A method is a function that `belongs' to an
1131object and is named \code{obj.methodname}, where \code{obj} is some
1132object (this may be an expression), and \code{methodname} is the name
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001133of a method that is defined by the object's type. Different types
1134define different methods. Methods of different types may have the
1135same name without causing ambiguity. (It is possible to define your
Fred Drakeeee08cd1997-12-04 15:43:15 +00001136own object types and methods, using \emph{classes}, as discussed later
Guido van Rossum6938f061994-08-01 12:22:53 +00001137in this tutorial.)
Fred Drake8842e861998-02-13 07:16:30 +00001138The method \method{append()} shown in the example, is defined for
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001139list objects; it adds a new element at the end of the list. In this
Fred Drake8842e861998-02-13 07:16:30 +00001140example it is equivalent to \samp{result = result + [b]}, but more
1141efficient.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001142
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001143\end{itemize}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001144
Guido van Rossum02455691997-07-17 16:21:52 +00001145\section{More on Defining Functions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001146\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
1151\subsection{Default Argument Values}
Fred Drake6c2176e1998-02-26 21:47:54 +00001152\label{defaultArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001153
1154The most useful form is to specify a default value for one or more
1155arguments. This creates a function that can be called with fewer
1156arguments than it is defined, e.g.
1157
1158\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001159def ask_ok(prompt, retries=4, complaint='Yes or no, please!'):
1160 while 1:
1161 ok = raw_input(prompt)
1162 if ok in ('y', 'ye', 'yes'): return 1
1163 if ok in ('n', 'no', 'nop', 'nope'): return 0
1164 retries = retries - 1
1165 if retries < 0: raise IOError, 'refusenik user'
1166 print complaint
Guido van Rossum02455691997-07-17 16:21:52 +00001167\end{verbatim}
1168
1169This function can be called either like this:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001170\code{ask_ok('Do you really want to quit?')} or like this:
1171\code{ask_ok('OK to overwrite the file?', 2)}.
Guido van Rossum02455691997-07-17 16:21:52 +00001172
1173The default values are evaluated at the point of function definition
Fred Drakeeee08cd1997-12-04 15:43:15 +00001174in the \emph{defining} scope, so that e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00001175
1176\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001177i = 5
1178def f(arg = i): print arg
1179i = 6
1180f()
Guido van Rossum02455691997-07-17 16:21:52 +00001181\end{verbatim}
1182
Fred Drakeeee08cd1997-12-04 15:43:15 +00001183will print \code{5}.
Guido van Rossum02455691997-07-17 16:21:52 +00001184
1185\subsection{Keyword Arguments}
Fred Drake6c2176e1998-02-26 21:47:54 +00001186\label{keywordArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001187
1188Functions can also be called using
Fred Drake8842e861998-02-13 07:16:30 +00001189keyword arguments of the form \samp{\var{keyword} = \var{value}}. For
Guido van Rossum02455691997-07-17 16:21:52 +00001190instance, the following function:
1191
1192\begin{verbatim}
1193def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'):
1194 print "-- This parrot wouldn't", action,
1195 print "if you put", voltage, "Volts through it."
1196 print "-- Lovely plumage, the", type
1197 print "-- It's", state, "!"
1198\end{verbatim}
1199
1200could be called in any of the following ways:
1201
1202\begin{verbatim}
1203parrot(1000)
1204parrot(action = 'VOOOOOM', voltage = 1000000)
1205parrot('a thousand', state = 'pushing up the daisies')
1206parrot('a million', 'bereft of life', 'jump')
1207\end{verbatim}
1208
1209but the following calls would all be invalid:
1210
1211\begin{verbatim}
1212parrot() # required argument missing
1213parrot(voltage=5.0, 'dead') # non-keyword argument following keyword
1214parrot(110, voltage=220) # duplicate value for argument
1215parrot(actor='John Cleese') # unknown keyword
1216\end{verbatim}
1217
1218In general, an argument list must have any positional arguments
1219followed by any keyword arguments, where the keywords must be chosen
1220from the formal parameter names. It's not important whether a formal
1221parameter has a default value or not. No argument must receive a
1222value more than once --- formal parameter names corresponding to
1223positional arguments cannot be used as keywords in the same calls.
1224
1225When a final formal parameter of the form \code{**\var{name}} is
1226present, it receives a dictionary containing all keyword arguments
1227whose keyword doesn't correspond to a formal parameter. This may be
1228combined with a formal parameter of the form \code{*\var{name}}
1229(described in the next subsection) which receives a tuple containing
1230the positional arguments beyond the formal parameter list.
1231(\code{*\var{name}} must occur before \code{**\var{name}}.) For
1232example, if we define a function like this:
1233
1234\begin{verbatim}
1235def cheeseshop(kind, *arguments, **keywords):
1236 print "-- Do you have any", kind, '?'
1237 print "-- I'm sorry, we're all out of", kind
1238 for arg in arguments: print arg
1239 print '-'*40
1240 for kw in keywords.keys(): print kw, ':', keywords[kw]
1241\end{verbatim}
1242
1243It could be called like this:
1244
1245\begin{verbatim}
1246cheeseshop('Limburger', "It's very runny, sir.",
1247 "It's really very, VERY runny, sir.",
1248 client='John Cleese',
1249 shopkeeper='Michael Palin',
1250 sketch='Cheese Shop Sketch')
1251\end{verbatim}
1252
1253and of course it would print:
1254
1255\begin{verbatim}
1256-- Do you have any Limburger ?
1257-- I'm sorry, we're all out of Limburger
1258It's very runny, sir.
1259It's really very, VERY runny, sir.
1260----------------------------------------
1261client : John Cleese
1262shopkeeper : Michael Palin
1263sketch : Cheese Shop Sketch
1264\end{verbatim}
1265
1266\subsection{Arbitrary Argument Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +00001267\label{arbitraryArgs}
Guido van Rossum02455691997-07-17 16:21:52 +00001268
1269Finally, the least frequently used option is to specify that a
1270function can be called with an arbitrary number of arguments. These
1271arguments will be wrapped up in a tuple. Before the variable number
1272of arguments, zero or more normal arguments may occur.
1273
1274\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001275def fprintf(file, format, *args):
1276 file.write(format % args)
Guido van Rossum02455691997-07-17 16:21:52 +00001277\end{verbatim}
1278
Fred Drakea594baf1998-04-03 05:16:31 +00001279
1280\subsection{Lambda Forms}
1281\label{lambda}
1282
1283By popular demand, a few features commonly found in functional
1284programming languages and Lisp have been added to Python. With the
1285\keyword{lambda} keyword, small anonymous functions can be created.
1286Here's a function that returns the sum of its two arguments:
1287\samp{lambda a, b: a+b}. Lambda forms can be used wherever function
1288objects are required. They are syntactically restricted to a single
1289expression. Semantically, they are just syntactic sugar for a normal
1290function definition. Like nested function definitions, lambda forms
1291cannot reference variables from the containing scope, but this can be
1292overcome through the judicious use of default argument values, e.g.
1293
1294\begin{verbatim}
1295def make_incrementor(n):
1296 return lambda x, incr=n: x+incr
1297\end{verbatim}
1298
1299\subsection{Documentation Strings}
1300\label{docstrings}
1301
1302There are emerging conventions about the content and formatting of
1303documentation strings.
1304
1305The first line should always be a short, concise summary of the
1306object's purpose. For brevity, it should not explicitly state the
1307object's name or type, since these are available by other means
1308(except if the name happens to be a verb describing a function's
1309operation). This line should begin with a capital letter and end with
1310a period.
1311
1312If there are more lines in the documentation string, the second line
1313should be blank, visually separating the summary from the rest of the
1314description. The following lines should be one of more of paragraphs
1315describing the objects calling conventions, its side effects, etc.
1316
1317The Python parser does not strip indentation from multi-line string
1318literals in Python, so tools that process documentation have to strip
1319indentation. This is done using the following convention. The first
1320non-blank line \emph{after} the first line of the string determines the
1321amount of indentation for the entire documentation string. (We can't
1322use the first line since it is generally adjacent to the string's
1323opening quotes so its indentation is not apparent in the string
1324literal.) Whitespace ``equivalent'' to this indentation is then
1325stripped from the start of all lines of the string. Lines that are
1326indented less should not occur, but if they occur all their leading
1327whitespace should be stripped. Equivalence of whitespace should be
1328tested after expansion of tabs (to 8 spaces, normally).
1329
1330
1331
Guido van Rossum02455691997-07-17 16:21:52 +00001332\chapter{Data Structures}
Fred Drake6c2176e1998-02-26 21:47:54 +00001333\label{structures}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001334
1335This chapter describes some things you've learned about already in
1336more detail, and adds some new things as well.
1337
1338\section{More on Lists}
Fred Drake6c2176e1998-02-26 21:47:54 +00001339\label{moreLists}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001340
1341The list data type has some more methods. Here are all of the methods
Fred Drakeed688541998-02-11 22:29:17 +00001342of list objects:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001343
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001344\begin{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001345
Fred Drakeeee08cd1997-12-04 15:43:15 +00001346\item[\code{insert(i, x)}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001347Insert an item at a given position. The first argument is the index of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001348the element before which to insert, so \code{a.insert(0, x)} inserts at
1349the front of the list, and \code{a.insert(len(a), x)} is equivalent to
1350\code{a.append(x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001351
Fred Drakeeee08cd1997-12-04 15:43:15 +00001352\item[\code{append(x)}]
1353Equivalent to \code{a.insert(len(a), x)}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001354
Fred Drakeeee08cd1997-12-04 15:43:15 +00001355\item[\code{index(x)}]
1356Return the index in the list of the first item whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001357It is an error if there is no such item.
1358
Fred Drakeeee08cd1997-12-04 15:43:15 +00001359\item[\code{remove(x)}]
1360Remove the first item from the list whose value is \code{x}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001361It is an error if there is no such item.
1362
Fred Drakeeee08cd1997-12-04 15:43:15 +00001363\item[\code{sort()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001364Sort the items of the list, in place.
1365
Fred Drakeeee08cd1997-12-04 15:43:15 +00001366\item[\code{reverse()}]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001367Reverse the elements of the list, in place.
1368
Fred Drakeeee08cd1997-12-04 15:43:15 +00001369\item[\code{count(x)}]
1370Return the number of times \code{x} appears in the list.
Guido van Rossum6938f061994-08-01 12:22:53 +00001371
Guido van Rossum7d9f8d71991-01-22 11:45:00 +00001372\end{description}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001373
1374An example that uses all list methods:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001375
Fred Drake8842e861998-02-13 07:16:30 +00001376\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001377>>> a = [66.6, 333, 333, 1, 1234.5]
Guido van Rossum6938f061994-08-01 12:22:53 +00001378>>> print a.count(333), a.count(66.6), a.count('x')
13792 1 0
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001380>>> a.insert(2, -1)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001381>>> a.append(333)
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001382>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001383[66.6, 333, -1, 333, 1, 1234.5, 333]
1384>>> a.index(333)
13851
1386>>> a.remove(333)
1387>>> a
1388[66.6, -1, 333, 1, 1234.5, 333]
1389>>> a.reverse()
1390>>> a
1391[333, 1234.5, 1, 333, -1, 66.6]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001392>>> a.sort()
1393>>> a
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001394[-1, 1, 66.6, 333, 333, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001395\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001396
Guido van Rossum02455691997-07-17 16:21:52 +00001397\subsection{Functional Programming Tools}
Fred Drake6c2176e1998-02-26 21:47:54 +00001398\label{functional}
Guido van Rossum02455691997-07-17 16:21:52 +00001399
1400There are three built-in functions that are very useful when used with
Fred Drake8842e861998-02-13 07:16:30 +00001401lists: \function{filter()}, \function{map()}, and \function{reduce()}.
Guido van Rossum02455691997-07-17 16:21:52 +00001402
Fred Drake8842e861998-02-13 07:16:30 +00001403\samp{filter(\var{function}, \var{sequence})} returns a sequence (of
1404the same type, if possible) consisting of those items from the
1405sequence for which \code{\var{function}(\var{item})} is true. For
1406example, to compute some primes:
Guido van Rossum02455691997-07-17 16:21:52 +00001407
1408\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001409>>> def f(x): return x%2 != 0 and x%3 != 0
1410...
1411>>> filter(f, range(2, 25))
1412[5, 7, 11, 13, 17, 19, 23]
Guido van Rossum02455691997-07-17 16:21:52 +00001413\end{verbatim}
1414
Fred Drake8842e861998-02-13 07:16:30 +00001415\samp{map(\var{function}, \var{sequence})} calls
1416\code{\var{function}(\var{item})} for each of the sequence's items and
1417returns a list of the return values. For example, to compute some
1418cubes:
Guido van Rossum02455691997-07-17 16:21:52 +00001419
1420\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001421>>> def cube(x): return x*x*x
1422...
1423>>> map(cube, range(1, 11))
1424[1, 8, 27, 64, 125, 216, 343, 512, 729, 1000]
Guido van Rossum02455691997-07-17 16:21:52 +00001425\end{verbatim}
1426
1427More than one sequence may be passed; the function must then have as
1428many arguments as there are sequences and is called with the
Fred Drake8842e861998-02-13 07:16:30 +00001429corresponding item from each sequence (or \code{None} if some sequence
1430is shorter than another). If \code{None} is passed for the function,
Guido van Rossum02455691997-07-17 16:21:52 +00001431a function returning its argument(s) is substituted.
1432
1433Combining these two special cases, we see that
Fred Drake8842e861998-02-13 07:16:30 +00001434\samp{map(None, \var{list1}, \var{list2})} is a convenient way of
1435turning a pair of lists into a list of pairs. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00001436
1437\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001438>>> seq = range(8)
1439>>> def square(x): return x*x
1440...
1441>>> map(None, seq, map(square, seq))
1442[(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)]
Guido van Rossum02455691997-07-17 16:21:52 +00001443\end{verbatim}
1444
Fred Drake8842e861998-02-13 07:16:30 +00001445\samp{reduce(\var{func}, \var{sequence})} returns a single value
1446constructed by calling the binary function \var{func} on the first two
1447items of the sequence, then on the result and the next item, and so
1448on. For example, to compute the sum of the numbers 1 through 10:
Guido van Rossum02455691997-07-17 16:21:52 +00001449
1450\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001451>>> def add(x,y): return x+y
1452...
1453>>> reduce(add, range(1, 11))
145455
Guido van Rossum02455691997-07-17 16:21:52 +00001455\end{verbatim}
1456
1457If there's only one item in the sequence, its value is returned; if
1458the sequence is empty, an exception is raised.
1459
1460A third argument can be passed to indicate the starting value. In this
1461case the starting value is returned for an empty sequence, and the
1462function is first applied to the starting value and the first sequence
1463item, then to the result and the next item, and so on. For example,
1464
1465\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00001466>>> def sum(seq):
1467... def add(x,y): return x+y
1468... return reduce(add, seq, 0)
1469...
1470>>> sum(range(1, 11))
147155
1472>>> sum([])
14730
Guido van Rossum02455691997-07-17 16:21:52 +00001474\end{verbatim}
1475
Fred Drakee7957181998-04-04 07:17:47 +00001476\section{The \keyword{del} statement}
Fred Drake6c2176e1998-02-26 21:47:54 +00001477\label{del}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001478
1479There is a way to remove an item from a list given its index instead
Fred Drakeeee08cd1997-12-04 15:43:15 +00001480of its value: the \code{del} statement. This can also be used to
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001481remove slices from a list (which we did earlier by assignment of an
1482empty list to the slice). For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001483
Fred Drake8842e861998-02-13 07:16:30 +00001484\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001485>>> a
1486[-1, 1, 66.6, 333, 333, 1234.5]
1487>>> del a[0]
1488>>> a
1489[1, 66.6, 333, 333, 1234.5]
1490>>> del a[2:4]
1491>>> a
1492[1, 66.6, 1234.5]
Fred Drake8842e861998-02-13 07:16:30 +00001493\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001494
1495\keyword{del} can also be used to delete entire variables:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001496
Fred Drake8842e861998-02-13 07:16:30 +00001497\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001498>>> del a
Fred Drake8842e861998-02-13 07:16:30 +00001499\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001500
Fred Drakeeee08cd1997-12-04 15:43:15 +00001501Referencing the name \code{a} hereafter is an error (at least until
Fred Drake6c2176e1998-02-26 21:47:54 +00001502another value is assigned to it). We'll find other uses for
1503\keyword{del} later.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001504
1505\section{Tuples and Sequences}
Fred Drake6c2176e1998-02-26 21:47:54 +00001506\label{tuples}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001507
1508We saw that lists and strings have many common properties, e.g.,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001509indexing and slicing operations. They are two examples of
1510\emph{sequence} data types. Since Python is an evolving language,
1511other sequence data types may be added. There is also another
1512standard sequence data type: the \emph{tuple}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001513
1514A tuple consists of a number of values separated by commas, for
1515instance:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001516
Fred Drake8842e861998-02-13 07:16:30 +00001517\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001518>>> t = 12345, 54321, 'hello!'
1519>>> t[0]
152012345
1521>>> t
1522(12345, 54321, 'hello!')
1523>>> # Tuples may be nested:
Guido van Rossum6938f061994-08-01 12:22:53 +00001524... u = t, (1, 2, 3, 4, 5)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001525>>> u
1526((12345, 54321, 'hello!'), (1, 2, 3, 4, 5))
Fred Drake8842e861998-02-13 07:16:30 +00001527\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001528
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001529As you see, on output tuples are alway enclosed in parentheses, so
1530that nested tuples are interpreted correctly; they may be input with
1531or without surrounding parentheses, although often parentheses are
1532necessary anyway (if the tuple is part of a larger expression).
1533
1534Tuples have many uses, e.g., (x, y) coordinate pairs, employee records
1535from a database, etc. Tuples, like strings, are immutable: it is not
1536possible to assign to the individual items of a tuple (you can
1537simulate much of the same effect with slicing and concatenation,
1538though).
1539
1540A special problem is the construction of tuples containing 0 or 1
Guido van Rossum6938f061994-08-01 12:22:53 +00001541items: the syntax has some extra quirks to accommodate these. Empty
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001542tuples are constructed by an empty pair of parentheses; a tuple with
1543one item is constructed by following a value with a comma
1544(it is not sufficient to enclose a single value in parentheses).
1545Ugly, but effective. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001546
Fred Drake8842e861998-02-13 07:16:30 +00001547\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001548>>> empty = ()
1549>>> singleton = 'hello', # <-- note trailing comma
1550>>> len(empty)
15510
1552>>> len(singleton)
15531
1554>>> singleton
1555('hello',)
Fred Drake8842e861998-02-13 07:16:30 +00001556\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001557
Fred Drakeeee08cd1997-12-04 15:43:15 +00001558The statement \code{t = 12345, 54321, 'hello!'} is an example of
1559\emph{tuple packing}: the values \code{12345}, \code{54321} and
1560\code{'hello!'} are packed together in a tuple. The reverse operation
1561is also possible, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001562
Fred Drake8842e861998-02-13 07:16:30 +00001563\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001564>>> x, y, z = t
Fred Drake8842e861998-02-13 07:16:30 +00001565\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001566
Fred Drakeeee08cd1997-12-04 15:43:15 +00001567This is called, appropriately enough, \emph{tuple unpacking}. Tuple
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001568unpacking requires that the list of variables on the left has the same
1569number of elements as the length of the tuple. Note that multiple
1570assignment is really just a combination of tuple packing and tuple
1571unpacking!
1572
Fred Drakeeee08cd1997-12-04 15:43:15 +00001573Occasionally, the corresponding operation on lists is useful: \emph{list
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001574unpacking}. This is supported by enclosing the list of variables in
1575square brackets:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001576
Fred Drake8842e861998-02-13 07:16:30 +00001577\begin{verbatim}
Guido van Rossume5f8b601995-01-04 19:12:49 +00001578>>> a = ['spam', 'eggs', 100, 1234]
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001579>>> [a1, a2, a3, a4] = a
Fred Drake8842e861998-02-13 07:16:30 +00001580\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001581
1582\section{Dictionaries}
Fred Drake6c2176e1998-02-26 21:47:54 +00001583\label{dictionaries}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001584
Fred Drakeeee08cd1997-12-04 15:43:15 +00001585Another useful data type built into Python is the \emph{dictionary}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001586Dictionaries are sometimes found in other languages as ``associative
1587memories'' or ``associative arrays''. Unlike sequences, which are
Fred Drakeeee08cd1997-12-04 15:43:15 +00001588indexed by a range of numbers, dictionaries are indexed by \emph{keys},
Guido van Rossum02455691997-07-17 16:21:52 +00001589which can be any non-mutable type; strings and numbers can always be
1590keys. Tuples can be used as keys if they contain only strings,
1591numbers, or tuples. You can't use lists as keys, since lists can be
1592modified in place using their \code{append()} method.
1593
Guido van Rossum6938f061994-08-01 12:22:53 +00001594It is best to think of a dictionary as an unordered set of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001595\emph{key:value} pairs, with the requirement that the keys are unique
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001596(within one dictionary).
Fred Drakeeee08cd1997-12-04 15:43:15 +00001597A pair of braces creates an empty dictionary: \code{\{\}}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001598Placing a comma-separated list of key:value pairs within the
1599braces adds initial key:value pairs to the dictionary; this is also the
1600way dictionaries are written on output.
1601
1602The main operations on a dictionary are storing a value with some key
1603and extracting the value given the key. It is also possible to delete
1604a key:value pair
Fred Drakeeee08cd1997-12-04 15:43:15 +00001605with \code{del}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001606If you store using a key that is already in use, the old value
1607associated with that key is forgotten. It is an error to extract a
Guido van Rossum6938f061994-08-01 12:22:53 +00001608value using a non-existent key.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001609
Fred Drakeeee08cd1997-12-04 15:43:15 +00001610The \code{keys()} method of a dictionary object returns a list of all the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001611keys used in the dictionary, in random order (if you want it sorted,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001612just apply the \code{sort()} method to the list of keys). To check
1613whether a single key is in the dictionary, use the \code{has_key()}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001614method of the dictionary.
1615
1616Here is a small example using a dictionary:
1617
Fred Drake8842e861998-02-13 07:16:30 +00001618\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001619>>> tel = {'jack': 4098, 'sape': 4139}
1620>>> tel['guido'] = 4127
1621>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001622{'sape': 4139, 'guido': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001623>>> tel['jack']
16244098
1625>>> del tel['sape']
1626>>> tel['irv'] = 4127
1627>>> tel
Guido van Rossum8f96f771991-11-12 15:45:03 +00001628{'guido': 4127, 'irv': 4127, 'jack': 4098}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001629>>> tel.keys()
1630['guido', 'irv', 'jack']
1631>>> tel.has_key('guido')
16321
Fred Drake8842e861998-02-13 07:16:30 +00001633\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001634
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001635\section{More on Conditions}
Fred Drake6c2176e1998-02-26 21:47:54 +00001636\label{conditions}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001637
Fred Drakeeee08cd1997-12-04 15:43:15 +00001638The conditions used in \code{while} and \code{if} statements above can
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001639contain other operators besides comparisons.
1640
Fred Drakeeee08cd1997-12-04 15:43:15 +00001641The comparison operators \code{in} and \code{not in} check whether a value
1642occurs (does not occur) in a sequence. The operators \code{is} and
1643\code{is not} compare whether two objects are really the same object; this
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001644only matters for mutable objects like lists. All comparison operators
1645have the same priority, which is lower than that of all numerical
1646operators.
1647
Fred Drakeeee08cd1997-12-04 15:43:15 +00001648Comparisons can be chained: e.g., \code{a < b == c} tests whether \code{a}
1649is less than \code{b} and moreover \code{b} equals \code{c}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001650
Fred Drakeeee08cd1997-12-04 15:43:15 +00001651Comparisons may be combined by the Boolean operators \code{and} and
1652\code{or}, and the outcome of a comparison (or of any other Boolean
1653expression) may be negated with \code{not}. These all have lower
1654priorities than comparison operators again; between them, \code{not} has
1655the highest priority, and \code{or} the lowest, so that
1656\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 +00001657course, parentheses can be used to express the desired composition.
1658
Fred Drakeeee08cd1997-12-04 15:43:15 +00001659The Boolean operators \code{and} and \code{or} are so-called
1660\emph{shortcut} operators: their arguments are evaluated from left to
1661right, and evaluation stops as soon as the outcome is determined.
1662E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A
1663and B and C} does not evaluate the expression C. In general, the
1664return value of a shortcut operator, when used as a general value and
1665not as a Boolean, is the last evaluated argument.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001666
1667It is possible to assign the result of a comparison or other Boolean
Guido van Rossum6938f061994-08-01 12:22:53 +00001668expression to a variable. For example,
1669
Fred Drake8842e861998-02-13 07:16:30 +00001670\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00001671>>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance'
1672>>> non_null = string1 or string2 or string3
1673>>> non_null
1674'Trondheim'
Fred Drake8842e861998-02-13 07:16:30 +00001675\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001676
Fred Drake3f205921998-01-13 18:56:38 +00001677Note that in Python, unlike \C{}, assignment cannot occur inside expressions.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001678
1679\section{Comparing Sequences and Other Types}
Fred Drake6c2176e1998-02-26 21:47:54 +00001680\label{comparing}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001681
1682Sequence objects may be compared to other objects with the same
Fred Drakeeee08cd1997-12-04 15:43:15 +00001683sequence type. The comparison uses \emph{lexicographical} ordering:
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001684first the first two items are compared, and if they differ this
1685determines the outcome of the comparison; if they are equal, the next
1686two items are compared, and so on, until either sequence is exhausted.
1687If two items to be compared are themselves sequences of the same type,
Guido van Rossum6938f061994-08-01 12:22:53 +00001688the lexicographical comparison is carried out recursively. If all
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001689items of two sequences compare equal, the sequences are considered
1690equal. If one sequence is an initial subsequence of the other, the
1691shorted sequence is the smaller one. Lexicographical ordering for
Guido van Rossum47b4c0f1995-03-15 11:25:32 +00001692strings uses the \ASCII{} ordering for individual characters. Some
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001693examples of comparisons between sequences with the same types:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001694
Fred Drake8842e861998-02-13 07:16:30 +00001695\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001696(1, 2, 3) < (1, 2, 4)
1697[1, 2, 3] < [1, 2, 4]
1698'ABC' < 'C' < 'Pascal' < 'Python'
1699(1, 2, 3, 4) < (1, 2, 4)
1700(1, 2) < (1, 2, -1)
1701(1, 2, 3) = (1.0, 2.0, 3.0)
1702(1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4)
Fred Drake8842e861998-02-13 07:16:30 +00001703\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001704
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001705Note that comparing objects of different types is legal. The outcome
1706is deterministic but arbitrary: the types are ordered by their name.
1707Thus, a list is always smaller than a string, a string is always
1708smaller than a tuple, etc. Mixed numeric types are compared according
1709to their numeric value, so 0 equals 0.0, etc.%
1710\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001711 The rules for comparing objects of different types should
1712 not be relied upon; they may change in a future version of
1713 the language.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001714}
1715
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001716
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001717\chapter{Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001718\label{modules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001719
Guido van Rossum4410c751991-06-04 20:22:18 +00001720If you quit from the Python interpreter and enter it again, the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001721definitions you have made (functions and variables) are lost.
1722Therefore, if you want to write a somewhat longer program, you are
1723better off using a text editor to prepare the input for the interpreter
Guido van Rossum16d6e711994-08-08 12:30:22 +00001724and running it with that file as input instead. This is known as creating a
Fred Drakeeee08cd1997-12-04 15:43:15 +00001725\emph{script}. As your program gets longer, you may want to split it
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001726into several files for easier maintenance. You may also want to use a
1727handy function that you've written in several programs without copying
1728its definition into each program.
1729
Guido van Rossum4410c751991-06-04 20:22:18 +00001730To support this, Python has a way to put definitions in a file and use
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001731them in a script or in an interactive instance of the interpreter.
Fred Drakeeee08cd1997-12-04 15:43:15 +00001732Such a file is called a \emph{module}; definitions from a module can be
1733\emph{imported} into other modules or into the \emph{main} module (the
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001734collection of variables that you have access to in a script
1735executed at the top level
1736and in calculator mode).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001737
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001738A module is a file containing Python definitions and statements. The
Fred Drakeeee08cd1997-12-04 15:43:15 +00001739file name is the module name with the suffix \file{.py} appended. Within
Guido van Rossum6938f061994-08-01 12:22:53 +00001740a module, the module's name (as a string) is available as the value of
Fred Drakeeee08cd1997-12-04 15:43:15 +00001741the global variable \code{__name__}. For instance, use your favorite text
1742editor to create a file called \file{fibo.py} in the current directory
Guido van Rossum6938f061994-08-01 12:22:53 +00001743with the following contents:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001744
Fred Drake8842e861998-02-13 07:16:30 +00001745\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001746# Fibonacci numbers module
1747
1748def fib(n): # write Fibonacci series up to n
1749 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001750 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001751 print b,
1752 a, b = b, a+b
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001753
1754def fib2(n): # return Fibonacci series up to n
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001755 result = []
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001756 a, b = 0, 1
Guido van Rossum16cd7f91994-10-06 10:29:26 +00001757 while b < n:
Fred Drakeeee08cd1997-12-04 15:43:15 +00001758 result.append(b)
1759 a, b = b, a+b
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001760 return result
Fred Drake8842e861998-02-13 07:16:30 +00001761\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001762
Guido van Rossum4410c751991-06-04 20:22:18 +00001763Now enter the Python interpreter and import this module with the
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001764following command:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001765
Fred Drake8842e861998-02-13 07:16:30 +00001766\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001767>>> import fibo
Fred Drake8842e861998-02-13 07:16:30 +00001768\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001769
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001770This does not enter the names of the functions defined in
Fred Drakeeee08cd1997-12-04 15:43:15 +00001771\code{fibo}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001772directly in the current symbol table; it only enters the module name
Fred Drakeeee08cd1997-12-04 15:43:15 +00001773\code{fibo}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001774there.
1775Using the module name you can access the functions:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001776
Fred Drake8842e861998-02-13 07:16:30 +00001777\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001778>>> fibo.fib(1000)
17791 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987
1780>>> fibo.fib2(100)
1781[1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Guido van Rossum6938f061994-08-01 12:22:53 +00001782>>> fibo.__name__
1783'fibo'
Fred Drake8842e861998-02-13 07:16:30 +00001784\end{verbatim}
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001785%
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001786If you intend to use a function often you can assign it to a local name:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001787
Fred Drake8842e861998-02-13 07:16:30 +00001788\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001789>>> fib = fibo.fib
1790>>> fib(500)
17911 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001792\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001793
Guido van Rossum02455691997-07-17 16:21:52 +00001794
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001795\section{More on Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001796\label{moreModules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001797
1798A module can contain executable statements as well as function
1799definitions.
1800These statements are intended to initialize the module.
1801They are executed only the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001802\emph{first}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001803time the module is imported somewhere.%
1804\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00001805 In fact function definitions are also `statements' that are
1806 `executed'; the execution enters the function name in the
1807 module's global symbol table.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001808}
1809
1810Each module has its own private symbol table, which is used as the
1811global symbol table by all functions defined in the module.
1812Thus, the author of a module can use global variables in the module
1813without worrying about accidental clashes with a user's global
1814variables.
1815On the other hand, if you know what you are doing you can touch a
1816module's global variables with the same notation used to refer to its
1817functions,
Fred Drakeeee08cd1997-12-04 15:43:15 +00001818\code{modname.itemname}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001819
1820Modules can import other modules.
1821It is customary but not required to place all
Fred Drakeeee08cd1997-12-04 15:43:15 +00001822\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001823statements at the beginning of a module (or script, for that matter).
1824The imported module names are placed in the importing module's global
1825symbol table.
1826
1827There is a variant of the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001828\code{import}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001829statement that imports names from a module directly into the importing
1830module's symbol table.
1831For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001832
Fred Drake8842e861998-02-13 07:16:30 +00001833\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001834>>> from fibo import fib, fib2
1835>>> fib(500)
18361 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001837\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001838
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001839This does not introduce the module name from which the imports are taken
Fred Drakeeee08cd1997-12-04 15:43:15 +00001840in the local symbol table (so in the example, \code{fibo} is not
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001841defined).
1842
1843There is even a variant to import all names that a module defines:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001844
Fred Drake8842e861998-02-13 07:16:30 +00001845\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001846>>> from fibo import *
1847>>> fib(500)
18481 1 2 3 5 8 13 21 34 55 89 144 233 377
Fred Drake8842e861998-02-13 07:16:30 +00001849\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001850
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001851This imports all names except those beginning with an underscore
Fred Drakeeee08cd1997-12-04 15:43:15 +00001852(\code{_}).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001853
Guido van Rossum02455691997-07-17 16:21:52 +00001854\subsection{The Module Search Path}
Fred Drake6c2176e1998-02-26 21:47:54 +00001855\label{searchPath}
Guido van Rossum02455691997-07-17 16:21:52 +00001856
Fred Drake391564f1998-04-01 23:11:56 +00001857\indexiii{module}{search}{path}
Fred Drake8842e861998-02-13 07:16:30 +00001858When a module named \module{spam} is imported, the interpreter searches
Fred Drakeeee08cd1997-12-04 15:43:15 +00001859for a file named \file{spam.py} in the current directory,
Guido van Rossum02455691997-07-17 16:21:52 +00001860and then in the list of directories specified by
Fred Drake391564f1998-04-01 23:11:56 +00001861the environment variable \envvar{PYTHONPATH}. This has the same syntax as
1862the shell variable \envvar{PATH}, i.e., a list of
1863directory names. When \envvar{PYTHONPATH} is not set, or when the file
Guido van Rossum02455691997-07-17 16:21:52 +00001864is not found there, the search continues in an installation-dependent
Fred Drake391564f1998-04-01 23:11:56 +00001865default path; on \UNIX{}, this is usually \file{.:/usr/local/lib/python}.
Guido van Rossum02455691997-07-17 16:21:52 +00001866
1867Actually, modules are searched in the list of directories given by the
Fred Drakeeee08cd1997-12-04 15:43:15 +00001868variable \code{sys.path} which is initialized from the directory
1869containing the input script (or the current directory),
Fred Drake391564f1998-04-01 23:11:56 +00001870\envvar{PYTHONPATH} and the installation-dependent default. This allows
Guido van Rossum02455691997-07-17 16:21:52 +00001871Python programs that know what they're doing to modify or replace the
1872module search path. See the section on Standard Modules later.
1873
1874\subsection{``Compiled'' Python files}
1875
1876As an important speed-up of the start-up time for short programs that
Fred Drakeeee08cd1997-12-04 15:43:15 +00001877use a lot of standard modules, if a file called \file{spam.pyc} exists
1878in the directory where \file{spam.py} is found, this is assumed to
Fred Drake8842e861998-02-13 07:16:30 +00001879contain an already-``compiled'' version of the module \module{spam}.
1880The modification time of the version of \file{spam.py} used to create
Fred Drakeeee08cd1997-12-04 15:43:15 +00001881\file{spam.pyc} is recorded in \file{spam.pyc}, and the file is
1882ignored if these don't match.
Guido van Rossum02455691997-07-17 16:21:52 +00001883
Fred Drakeeee08cd1997-12-04 15:43:15 +00001884Normally, you don't need to do anything to create the \file{spam.pyc} file.
1885Whenever \file{spam.py} is successfully compiled, an attempt is made to
1886write the compiled version to \file{spam.pyc}. It is not an error if
Guido van Rossum02455691997-07-17 16:21:52 +00001887this attempt fails; if for any reason the file is not written
Fred Drakeeee08cd1997-12-04 15:43:15 +00001888completely, the resulting \file{spam.pyc} file will be recognized as
1889invalid and thus ignored later. The contents of the \file{spam.pyc}
Guido van Rossum02455691997-07-17 16:21:52 +00001890file is platform independent, so a Python module directory can be
1891shared by machines of different architectures. (Tip for experts:
Fred Drake391564f1998-04-01 23:11:56 +00001892the module \module{compileall}\refstmodindex{compileall} creates
1893\file{.pyc} files for all modules.)
Guido van Rossum02455691997-07-17 16:21:52 +00001894
Fred Drake8842e861998-02-13 07:16:30 +00001895% XXX Should optimization with -O be covered here?
Guido van Rossum02455691997-07-17 16:21:52 +00001896
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001897\section{Standard Modules}
Fred Drake6c2176e1998-02-26 21:47:54 +00001898\label{standardModules}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001899
Guido van Rossum4410c751991-06-04 20:22:18 +00001900Python comes with a library of standard modules, described in a separate
Fred Drake8842e861998-02-13 07:16:30 +00001901document, the \emph{Python Library Reference} (``Library Reference''
1902hereafter). Some modules are built into the interpreter; these
1903provide access to operations that are not part of the core of the
1904language but are nevertheless built in, either for efficiency or to
1905provide access to operating system primitives such as system calls.
1906The set of such modules is a configuration option; e.g., the
1907\module{amoeba} module is only provided on systems that somehow
1908support Amoeba primitives. One particular module deserves some
Fred Drake391564f1998-04-01 23:11:56 +00001909attention: \module{sys}\refstmodindex{sys}, which is built into every
1910Python interpreter. The variables \code{sys.ps1} and \code{sys.ps2}
1911define the strings used as primary and secondary prompts:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001912
Fred Drake8842e861998-02-13 07:16:30 +00001913\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001914>>> import sys
1915>>> sys.ps1
1916'>>> '
1917>>> sys.ps2
1918'... '
1919>>> sys.ps1 = 'C> '
1920C> print 'Yuck!'
1921Yuck!
1922C>
Fred Drake8842e861998-02-13 07:16:30 +00001923\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001924
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001925These two variables are only defined if the interpreter is in
1926interactive mode.
1927
1928The variable
Fred Drakeeee08cd1997-12-04 15:43:15 +00001929\code{sys.path}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001930is a list of strings that determine the interpreter's search path for
1931modules.
1932It is initialized to a default path taken from the environment variable
Fred Drake391564f1998-04-01 23:11:56 +00001933\envvar{PYTHONPATH}, or from a built-in default if \envvar{PYTHONPATH}
1934is not set. You can modify it using standard list operations, e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001935
Fred Drake8842e861998-02-13 07:16:30 +00001936\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001937>>> import sys
1938>>> sys.path.append('/ufs/guido/lib/python')
Fred Drake8842e861998-02-13 07:16:30 +00001939\end{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001940
Fred Drakee7957181998-04-04 07:17:47 +00001941\section{The \function{dir()} Function}
Fred Drake6c2176e1998-02-26 21:47:54 +00001942\label{dir}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001943
Fred Drake8842e861998-02-13 07:16:30 +00001944The built-in function \function{dir()} is used to find out which names
1945a module defines. It returns a sorted list of strings:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001946
Fred Drake8842e861998-02-13 07:16:30 +00001947\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001948>>> import fibo, sys
1949>>> dir(fibo)
Guido van Rossum6938f061994-08-01 12:22:53 +00001950['__name__', 'fib', 'fib2']
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001951>>> dir(sys)
Guido van Rossum6938f061994-08-01 12:22:53 +00001952['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit',
1953'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace',
1954'stderr', 'stdin', 'stdout', 'version']
Fred Drake8842e861998-02-13 07:16:30 +00001955\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001956
Fred Drake8842e861998-02-13 07:16:30 +00001957Without arguments, \function{dir()} lists the names you have defined
1958currently:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001959
Fred Drake8842e861998-02-13 07:16:30 +00001960\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001961>>> a = [1, 2, 3, 4, 5]
1962>>> import fibo, sys
1963>>> fib = fibo.fib
1964>>> dir()
Guido van Rossum6938f061994-08-01 12:22:53 +00001965['__name__', 'a', 'fib', 'fibo', 'sys']
Fred Drake8842e861998-02-13 07:16:30 +00001966\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00001967
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001968Note that it lists all types of names: variables, modules, functions, etc.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00001969
Fred Drake8842e861998-02-13 07:16:30 +00001970\function{dir()} does not list the names of built-in functions and
1971variables. If you want a list of those, they are defined in the
Fred Drake391564f1998-04-01 23:11:56 +00001972standard module \module{__builtin__}\refbimodindex{__builtin__}:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00001973
Fred Drake8842e861998-02-13 07:16:30 +00001974\begin{verbatim}
Guido van Rossum4bd023f1993-10-27 13:49:20 +00001975>>> import __builtin__
1976>>> dir(__builtin__)
Guido van Rossum6938f061994-08-01 12:22:53 +00001977['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError',
1978'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt',
1979'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError',
1980'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError',
1981'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce',
1982'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float',
1983'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long',
1984'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input',
1985'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange']
Fred Drake8842e861998-02-13 07:16:30 +00001986\end{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001987
Guido van Rossum5e0759d1992-08-07 16:06:24 +00001988
Guido van Rossum02455691997-07-17 16:21:52 +00001989\chapter{Input and Output}
Fred Drake6c2176e1998-02-26 21:47:54 +00001990\label{io}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00001991
Guido van Rossum02455691997-07-17 16:21:52 +00001992There are several ways to present the output of a program; data can be
1993printed in a human-readable form, or written to a file for future use.
1994This chapter will discuss some of the possibilities.
1995
1996\section{Fancier Output Formatting}
Fred Drakeeee08cd1997-12-04 15:43:15 +00001997So far we've encountered two ways of writing values: \emph{expression
Fred Drake8842e861998-02-13 07:16:30 +00001998statements} and the \keyword{print} statement. (A third way is using
1999the \method{write()} method of file objects; the standard output file
2000can be referenced as \code{sys.stdout}. See the Library Reference for
2001more information on this.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002002
2003Often you'll want more control over the formatting of your output than
Guido van Rossum02455691997-07-17 16:21:52 +00002004simply printing space-separated values. There are two ways to format
2005your output; the first way is to do all the string handling yourself;
2006using string slicing and concatenation operations you can create any
Fred Drake391564f1998-04-01 23:11:56 +00002007lay-out you can imagine. The standard module
2008\module{string}\refstmodindex{string} contains some useful operations
2009for padding strings to a given column width;
Guido van Rossum02455691997-07-17 16:21:52 +00002010these will be discussed shortly. The second way is to use the
2011\code{\%} operator with a string as the left argument. \code{\%}
Fred Drake8842e861998-02-13 07:16:30 +00002012interprets the left argument as a \C{} \cfunction{sprintf()}-style
2013format string to be applied to the right argument, and returns the
2014string resulting from this formatting operation.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002015
2016One question remains, of course: how do you convert values to strings?
Guido van Rossum02455691997-07-17 16:21:52 +00002017Luckily, Python has a way to convert any value to a string: pass it to
Fred Drake8842e861998-02-13 07:16:30 +00002018the \function{repr()} function, or just write the value between
2019reverse quotes (\code{``}). Some examples:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002020
Fred Drake8842e861998-02-13 07:16:30 +00002021\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002022>>> x = 10 * 3.14
2023>>> y = 200*200
2024>>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...'
2025>>> print s
2026The value of x is 31.4, and y is 40000...
2027>>> # Reverse quotes work on other types besides numbers:
Guido van Rossum6938f061994-08-01 12:22:53 +00002028... p = [x, y]
Guido van Rossum02455691997-07-17 16:21:52 +00002029>>> ps = repr(p)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002030>>> ps
2031'[31.4, 40000]'
2032>>> # Converting a string adds string quotes and backslashes:
Guido van Rossum6938f061994-08-01 12:22:53 +00002033... hello = 'hello, world\n'
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002034>>> hellos = `hello`
2035>>> print hellos
2036'hello, world\012'
2037>>> # The argument of reverse quotes may be a tuple:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002038... `x, y, ('spam', 'eggs')`
2039"(31.4, 40000, ('spam', 'eggs'))"
Fred Drake8842e861998-02-13 07:16:30 +00002040\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002041
Guido van Rossum6938f061994-08-01 12:22:53 +00002042Here are two ways to write a table of squares and cubes:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002043
Fred Drake8842e861998-02-13 07:16:30 +00002044\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002045>>> import string
2046>>> for x in range(1, 11):
2047... print string.rjust(`x`, 2), string.rjust(`x*x`, 3),
2048... # Note trailing comma on previous line
2049... print string.rjust(`x*x*x`, 4)
2050...
2051 1 1 1
2052 2 4 8
2053 3 9 27
2054 4 16 64
2055 5 25 125
2056 6 36 216
2057 7 49 343
2058 8 64 512
2059 9 81 729
206010 100 1000
Guido van Rossum6938f061994-08-01 12:22:53 +00002061>>> for x in range(1,11):
2062... print '%2d %3d %4d' % (x, x*x, x*x*x)
2063...
2064 1 1 1
2065 2 4 8
2066 3 9 27
2067 4 16 64
2068 5 25 125
2069 6 36 216
2070 7 49 343
2071 8 64 512
2072 9 81 729
207310 100 1000
Fred Drake8842e861998-02-13 07:16:30 +00002074\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002075
Fred Drake8842e861998-02-13 07:16:30 +00002076(Note that one space between each column was added by the way
2077\keyword{print} works: it always adds spaces between its arguments.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002078
Fred Drake8842e861998-02-13 07:16:30 +00002079This example demonstrates the function \function{string.rjust()},
2080which right-justifies a string in a field of a given width by padding
2081it with spaces on the left. There are similar functions
2082\function{string.ljust()} and \function{string.center()}. These
2083functions do not write anything, they just return a new string. If
2084the input string is too long, they don't truncate it, but return it
2085unchanged; this will mess up your column lay-out but that's usually
2086better than the alternative, which would be lying about a value. (If
2087you really want truncation you can always add a slice operation, as in
2088\samp{string.ljust(x,~n)[0:n]}.)
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002089
Fred Drake8842e861998-02-13 07:16:30 +00002090There is another function, \function{string.zfill()}, which pads a
2091numeric string on the left with zeros. It understands about plus and
2092minus signs:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002093
Fred Drake8842e861998-02-13 07:16:30 +00002094\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002095>>> string.zfill('12', 5)
2096'00012'
2097>>> string.zfill('-3.14', 7)
2098'-003.14'
2099>>> string.zfill('3.14159265359', 5)
2100'3.14159265359'
Fred Drake8842e861998-02-13 07:16:30 +00002101\end{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002102%
2103Using the \code{\%} operator looks like this:
2104
2105\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002106>>> import math
2107>>> print 'The value of PI is approximately %5.3f.' % math.pi
2108The value of PI is approximately 3.142.
Guido van Rossum02455691997-07-17 16:21:52 +00002109\end{verbatim}
2110
2111If there is more than one format in the string you pass a tuple as
2112right operand, e.g.
2113
2114\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002115>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2116>>> for name, phone in table.items():
2117... print '%-10s ==> %10d' % (name, phone)
2118...
2119Jack ==> 4098
2120Dcab ==> 8637678
2121Sjoerd ==> 4127
Guido van Rossum02455691997-07-17 16:21:52 +00002122\end{verbatim}
2123
Fred Drake3f205921998-01-13 18:56:38 +00002124Most formats work exactly as in \C{} and require that you pass the proper
Guido van Rossum02455691997-07-17 16:21:52 +00002125type; however, if you don't you get an exception, not a core dump.
2126The \verb\%s\ format is more relaxed: if the corresponding argument is
Fred Drake8842e861998-02-13 07:16:30 +00002127not a string object, it is converted to string using the
2128\function{str()} built-in function. Using \code{*} to pass the width
2129or precision in as a separate (integer) argument is supported. The
2130\C{} formats \verb\%n\ and \verb\%p\ are not supported.
Guido van Rossum02455691997-07-17 16:21:52 +00002131
2132If you have a really long format string that you don't want to split
2133up, it would be nice if you could reference the variables to be
2134formatted by name instead of by position. This can be done by using
Fred Drake3f205921998-01-13 18:56:38 +00002135an extension of \C{} formats using the form \verb\%(name)format\, e.g.
Guido van Rossum02455691997-07-17 16:21:52 +00002136
2137\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002138>>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678}
2139>>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table
2140Jack: 4098; Sjoerd: 4127; Dcab: 8637678
Guido van Rossum02455691997-07-17 16:21:52 +00002141\end{verbatim}
2142
2143This is particularly useful in combination with the new built-in
Fred Drake8842e861998-02-13 07:16:30 +00002144\function{vars()} function, which returns a dictionary containing all
Guido van Rossum02455691997-07-17 16:21:52 +00002145local variables.
2146
2147\section{Reading and Writing Files}
Fred Drake6c2176e1998-02-26 21:47:54 +00002148\label{files}
2149
Guido van Rossum02455691997-07-17 16:21:52 +00002150% Opening files
Fred Drake391564f1998-04-01 23:11:56 +00002151\function{open()}\bifuncindex{open} returns a file
2152object\obindex{file}, and is most commonly used with two arguments:
2153\samp{open(\var{filename}, \var{mode})}.
Guido van Rossum02455691997-07-17 16:21:52 +00002154
Fred Drake8842e861998-02-13 07:16:30 +00002155\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002156>>> f=open('/tmp/workfile', 'w')
2157>>> print f
2158<open file '/tmp/workfile', mode 'w' at 80a0960>
Fred Drake8842e861998-02-13 07:16:30 +00002159\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002160
Guido van Rossum02455691997-07-17 16:21:52 +00002161The first argument is a string containing the filename. The second
2162argument is another string containing a few characters describing the
2163way in which the file will be used. \var{mode} can be \code{'r'} when
2164the file will only be read, \code{'w'} for only writing (an existing
2165file with the same name will be erased), and \code{'a'} opens the file
2166for appending; any data written to the file is automatically added to
2167the end. \code{'r+'} opens the file for both reading and writing.
2168The \var{mode} argument is optional; \code{'r'} will be assumed if
2169it's omitted.
2170
Fred Drake391564f1998-04-01 23:11:56 +00002171On Windows and the Macintosh, \code{'b'} appended to the
Guido van Rossum02455691997-07-17 16:21:52 +00002172mode opens the file in binary mode, so there are also modes like
2173\code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a
2174distinction between text and binary files; the end-of-line characters
2175in text files are automatically altered slightly when data is read or
2176written. This behind-the-scenes modification to file data is fine for
Fred Drake8842e861998-02-13 07:16:30 +00002177\ASCII{} text files, but it'll corrupt binary data like that in JPEGs or
2178\file{.EXE} files. Be very careful to use binary mode when reading and
Fred Drake391564f1998-04-01 23:11:56 +00002179writing such files. (Note that the precise semantics of text mode on
2180the Macintosh depends on the underlying \C{} library being used.)
Guido van Rossum02455691997-07-17 16:21:52 +00002181
Fred Drakea594baf1998-04-03 05:16:31 +00002182\subsection{Methods of File Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002183\label{fileMethods}
Guido van Rossum02455691997-07-17 16:21:52 +00002184
2185The rest of the examples in this section will assume that a file
2186object called \code{f} has already been created.
2187
2188To read a file's contents, call \code{f.read(\var{size})}, which reads
2189some quantity of data and returns it as a string. \var{size} is an
2190optional numeric argument. When \var{size} is omitted or negative,
2191the entire contents of the file will be read and returned; it's your
2192problem if the file is twice as large as your machine's memory.
2193Otherwise, at most \var{size} bytes are read and returned. If the end
2194of the file has been reached, \code{f.read()} will return an empty
2195string (\code {""}).
Fred Drake8842e861998-02-13 07:16:30 +00002196\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002197>>> f.read()
2198'This is the entire file.\012'
2199>>> f.read()
2200''
Fred Drake8842e861998-02-13 07:16:30 +00002201\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002202
Guido van Rossum02455691997-07-17 16:21:52 +00002203\code{f.readline()} reads a single line from the file; a newline
Fred Drake8842e861998-02-13 07:16:30 +00002204character (\code{\e n}) is left at the end of the string, and is only
Guido van Rossum02455691997-07-17 16:21:52 +00002205omitted on the last line of the file if the file doesn't end in a
2206newline. This makes the return value unambiguous; if
2207\code{f.readline()} returns an empty string, the end of the file has
Fred Drake8842e861998-02-13 07:16:30 +00002208been reached, while a blank line is represented by \code{'\e n'}, a
Guido van Rossum02455691997-07-17 16:21:52 +00002209string containing only a single newline.
2210
Fred Drake8842e861998-02-13 07:16:30 +00002211\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002212>>> f.readline()
2213'This is the first line of the file.\012'
2214>>> f.readline()
2215'Second line of the file\012'
2216>>> f.readline()
2217''
Fred Drake8842e861998-02-13 07:16:30 +00002218\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002219
Fred Drakeeee08cd1997-12-04 15:43:15 +00002220\code{f.readlines()} uses \code{f.readline()} repeatedly, and returns
Guido van Rossum02455691997-07-17 16:21:52 +00002221a list containing all the lines of data in the file.
2222
Fred Drake8842e861998-02-13 07:16:30 +00002223\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002224>>> f.readlines()
2225['This is the first line of the file.\012', 'Second line of the file\012']
Fred Drake8842e861998-02-13 07:16:30 +00002226\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002227
Guido van Rossum02455691997-07-17 16:21:52 +00002228\code{f.write(\var{string})} writes the contents of \var{string} to
2229the file, returning \code{None}.
2230
Fred Drake8842e861998-02-13 07:16:30 +00002231\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002232>>> f.write('This is a test\n')
Fred Drake8842e861998-02-13 07:16:30 +00002233\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002234
Guido van Rossum02455691997-07-17 16:21:52 +00002235\code{f.tell()} returns an integer giving the file object's current
2236position in the file, measured in bytes from the beginning of the
2237file. To change the file object's position, use
Fred Drake8842e861998-02-13 07:16:30 +00002238\samp{f.seek(\var{offset}, \var{from_what})}. The position is
Guido van Rossum02455691997-07-17 16:21:52 +00002239computed from adding \var{offset} to a reference point; the reference
2240point is selected by the \var{from_what} argument. A \var{from_what}
2241value of 0 measures from the beginning of the file, 1 uses the current
2242file position, and 2 uses the end of the file as the reference point.
Fred Drake8842e861998-02-13 07:16:30 +00002243\var{from_what} can be omitted and defaults to 0, using the beginning
2244of the file as the reference point.
Guido van Rossum02455691997-07-17 16:21:52 +00002245
Fred Drake8842e861998-02-13 07:16:30 +00002246\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002247>>> f=open('/tmp/workfile', 'r+')
2248>>> f.write('0123456789abcdef')
2249>>> f.seek(5) # Go to the 5th byte in the file
2250>>> f.read(1)
2251'5'
2252>>> f.seek(-3, 2) # Go to the 3rd byte before the end
2253>>> f.read(1)
2254'd'
Fred Drake8842e861998-02-13 07:16:30 +00002255\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002256
Guido van Rossum02455691997-07-17 16:21:52 +00002257When you're done with a file, call \code{f.close()} to close it and
2258free up any system resources taken up by the open file. After calling
2259\code{f.close()}, attempts to use the file object will automatically fail.
2260
Fred Drake8842e861998-02-13 07:16:30 +00002261\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002262>>> f.close()
2263>>> f.read()
2264Traceback (innermost last):
2265 File "<stdin>", line 1, in ?
2266ValueError: I/O operation on closed file
Fred Drake8842e861998-02-13 07:16:30 +00002267\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002268
Fred Drake8842e861998-02-13 07:16:30 +00002269File objects have some additional methods, such as \method{isatty()}
2270and \method{truncate()} which are less frequently used; consult the
2271Library Reference for a complete guide to file objects.
Guido van Rossum02455691997-07-17 16:21:52 +00002272
Fred Drakea594baf1998-04-03 05:16:31 +00002273\subsection{The \module{pickle} Module}
Fred Drake6c2176e1998-02-26 21:47:54 +00002274\label{pickle}
Fred Drake391564f1998-04-01 23:11:56 +00002275\refstmodindex{pickle}
Guido van Rossum02455691997-07-17 16:21:52 +00002276
2277Strings can easily be written to and read from a file. Numbers take a
Fred Drake8842e861998-02-13 07:16:30 +00002278bit more effort, since the \method{read()} method only returns
2279strings, which will have to be passed to a function like
2280\function{string.atoi()}, which takes a string like \code{'123'} and
2281returns its numeric value 123. However, when you want to save more
2282complex data types like lists, dictionaries, or class instances,
2283things get a lot more complicated.
Guido van Rossum02455691997-07-17 16:21:52 +00002284
2285Rather than have users be constantly writing and debugging code to
2286save complicated data types, Python provides a standard module called
Fred Drake8842e861998-02-13 07:16:30 +00002287\module{pickle}. This is an amazing module that can take almost
Guido van Rossum02455691997-07-17 16:21:52 +00002288any Python object (even some forms of Python code!), and convert it to
2289a string representation; this process is called \dfn{pickling}.
2290Reconstructing the object from the string representation is called
2291\dfn{unpickling}. Between pickling and unpickling, the string
2292representing the object may have been stored in a file or data, or
2293sent over a network connection to some distant machine.
2294
2295If you have an object \code{x}, and a file object \code{f} that's been
2296opened for writing, the simplest way to pickle the object takes only
2297one line of code:
2298
Fred Drake8842e861998-02-13 07:16:30 +00002299\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002300pickle.dump(x, f)
Fred Drake8842e861998-02-13 07:16:30 +00002301\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002302
Fred Drake8842e861998-02-13 07:16:30 +00002303To unpickle the object again, if \code{f} is a file object which has
2304been opened for reading:
Guido van Rossum02455691997-07-17 16:21:52 +00002305
Fred Drake8842e861998-02-13 07:16:30 +00002306\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00002307x = pickle.load(f)
Fred Drake8842e861998-02-13 07:16:30 +00002308\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002309
Guido van Rossum02455691997-07-17 16:21:52 +00002310(There are other variants of this, used when pickling many objects or
2311when you don't want to write the pickled data to a file; consult the
Fred Drake8842e861998-02-13 07:16:30 +00002312complete documentation for \module{pickle} in the Library Reference.)
Guido van Rossum02455691997-07-17 16:21:52 +00002313
Fred Drake8842e861998-02-13 07:16:30 +00002314\module{pickle} is the standard way to make Python objects which can be
Guido van Rossum02455691997-07-17 16:21:52 +00002315stored and reused by other programs or by a future invocation of the
2316same program; the technical term for this is a \dfn{persistent}
Fred Drake8842e861998-02-13 07:16:30 +00002317object. Because \module{pickle} is so widely used, many authors who
Guido van Rossum02455691997-07-17 16:21:52 +00002318write Python extensions take care to ensure that new data types such
Fred Drake72389881998-04-13 01:31:10 +00002319as matrices can be properly pickled and unpickled.
Guido van Rossum02455691997-07-17 16:21:52 +00002320
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002321
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002322
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002323\chapter{Errors and Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002324\label{errors}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002325
2326Until now error messages haven't been more than mentioned, but if you
2327have tried out the examples you have probably seen some. There are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002328(at least) two distinguishable kinds of errors: \emph{syntax errors}
2329and \emph{exceptions}.
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002330
2331\section{Syntax Errors}
Fred Drake6c2176e1998-02-26 21:47:54 +00002332\label{syntaxErrors}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002333
2334Syntax errors, also known as parsing errors, are perhaps the most common
Guido van Rossum4410c751991-06-04 20:22:18 +00002335kind of complaint you get while you are still learning Python:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002336
Fred Drake8842e861998-02-13 07:16:30 +00002337\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002338>>> while 1 print 'Hello world'
Guido van Rossum6938f061994-08-01 12:22:53 +00002339 File "<stdin>", line 1
2340 while 1 print 'Hello world'
2341 ^
2342SyntaxError: invalid syntax
Fred Drake8842e861998-02-13 07:16:30 +00002343\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002344
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002345The parser repeats the offending line and displays a little `arrow'
2346pointing at the earliest point in the line where the error was detected.
2347The error is caused by (or at least detected at) the token
Fred Drakeeee08cd1997-12-04 15:43:15 +00002348\emph{preceding}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002349the arrow: in the example, the error is detected at the keyword
Fred Drake391564f1998-04-01 23:11:56 +00002350\keyword{print}, since a colon (\character{:}) is missing before it.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002351File name and line number are printed so you know where to look in case
2352the input came from a script.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002353
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002354\section{Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002355\label{exceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002356
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002357Even if a statement or expression is syntactically correct, it may
2358cause an error when an attempt is made to execute it.
Fred Drakeeee08cd1997-12-04 15:43:15 +00002359Errors detected during execution are called \emph{exceptions} and are
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002360not unconditionally fatal: you will soon learn how to handle them in
2361Python programs. Most exceptions are not handled by programs,
2362however, and result in error messages as shown here:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002363
Fred Drake8842e861998-02-13 07:16:30 +00002364\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002365>>> 10 * (1/0)
Guido van Rossum3cbc16d1993-12-17 12:13:53 +00002366Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002367 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002368ZeroDivisionError: integer division or modulo
Guido van Rossume5f8b601995-01-04 19:12:49 +00002369>>> 4 + spam*3
Guido van Rossum6938f061994-08-01 12:22:53 +00002370Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002371 File "<stdin>", line 1
Guido van Rossume5f8b601995-01-04 19:12:49 +00002372NameError: spam
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002373>>> '2' + 2
Guido van Rossum6938f061994-08-01 12:22:53 +00002374Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002375 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002376TypeError: illegal argument type for built-in operation
Fred Drake8842e861998-02-13 07:16:30 +00002377\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002378
Guido van Rossumb2c65561993-05-12 08:53:36 +00002379The last line of the error message indicates what happened.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002380Exceptions come in different types, and the type is printed as part of
2381the message: the types in the example are
Fred Drake8842e861998-02-13 07:16:30 +00002382\exception{ZeroDivisionError},
2383\exception{NameError}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002384and
Fred Drake8842e861998-02-13 07:16:30 +00002385\exception{TypeError}.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002386The string printed as the exception type is the name of the built-in
2387name for the exception that occurred. This is true for all built-in
2388exceptions, but need not be true for user-defined exceptions (although
2389it is a useful convention).
2390Standard exception names are built-in identifiers (not reserved
2391keywords).
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002392
Guido van Rossumb2c65561993-05-12 08:53:36 +00002393The rest of the line is a detail whose interpretation depends on the
2394exception type; its meaning is dependent on the exception type.
2395
2396The preceding part of the error message shows the context where the
2397exception happened, in the form of a stack backtrace.
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002398In general it contains a stack backtrace listing source lines; however,
2399it will not display lines read from standard input.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002400
Fred Drake8842e861998-02-13 07:16:30 +00002401The Library Reference lists the built-in exceptions and their
2402meanings.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002403
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002404\section{Handling Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002405\label{handling}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002406
2407It is possible to write programs that handle selected exceptions.
2408Look at the following example, which prints a table of inverses of
2409some floating point numbers:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002410
Fred Drake8842e861998-02-13 07:16:30 +00002411\begin{verbatim}
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002412>>> numbers = [0.3333, 2.5, 0, 10]
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002413>>> for x in numbers:
2414... print x,
2415... try:
2416... print 1.0 / x
Guido van Rossumb2c65561993-05-12 08:53:36 +00002417... except ZeroDivisionError:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002418... print '*** has no inverse ***'
Guido van Rossum02455691997-07-17 16:21:52 +00002419...
Guido van Rossumd9bf55d1991-01-11 16:35:08 +000024200.3333 3.00030003
24212.5 0.4
24220 *** has no inverse ***
242310 0.1
Fred Drake8842e861998-02-13 07:16:30 +00002424\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002425
Fred Drake8842e861998-02-13 07:16:30 +00002426The \keyword{try} statement works as follows.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002427\begin{itemize}
2428\item
Fred Drake8842e861998-02-13 07:16:30 +00002429First, the \emph{try clause}
2430(the statement(s) between the \keyword{try} and \keyword{except}
2431keywords) is executed.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002432\item
2433If no exception occurs, the
Fred Drakeeee08cd1997-12-04 15:43:15 +00002434\emph{except\ clause}
Fred Drake8842e861998-02-13 07:16:30 +00002435is skipped and execution of the \keyword{try} statement is finished.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002436\item
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002437If an exception occurs during execution of the try clause,
Fred Drake8842e861998-02-13 07:16:30 +00002438the rest of the clause is skipped. Then if its type matches the
2439exception named after the \keyword{except} keyword, the rest of the
2440try clause is skipped, the except clause is executed, and then
2441execution continues after the \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002442\item
2443If an exception occurs which does not match the exception named in the
Fred Drake8842e861998-02-13 07:16:30 +00002444except clause, it is passed on to outer \keyword{try} statements; if
2445no handler is found, it is an \emph{unhandled exception}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002446and execution stops with a message as shown above.
2447\end{itemize}
Fred Drake8842e861998-02-13 07:16:30 +00002448A \keyword{try} statement may have more than one except clause, to
2449specify handlers for different exceptions.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002450At most one handler will be executed.
2451Handlers only handle exceptions that occur in the corresponding try
Fred Drake8842e861998-02-13 07:16:30 +00002452clause, not in other handlers of the same \keyword{try} statement.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002453An except clause may name multiple exceptions as a parenthesized list,
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002454e.g.:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002455
Fred Drake8842e861998-02-13 07:16:30 +00002456\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002457... except (RuntimeError, TypeError, NameError):
2458... pass
Fred Drake8842e861998-02-13 07:16:30 +00002459\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002460
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002461The last except clause may omit the exception name(s), to serve as a
2462wildcard.
Guido van Rossumb2c65561993-05-12 08:53:36 +00002463Use this with extreme caution, since it is easy to mask a real
2464programming error in this way!
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002465
Fred Drake8842e861998-02-13 07:16:30 +00002466The \keyword{try} \ldots\ \keyword{except} statement has an optional
2467\emph{else clause}, which must follow all except clauses. It is
2468useful to place code that must be executed if the try clause does not
2469raise an exception. For example:
Guido van Rossum02455691997-07-17 16:21:52 +00002470
2471\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002472for arg in sys.argv:
2473 try:
2474 f = open(arg, 'r')
2475 except IOError:
2476 print 'cannot open', arg
2477 else:
2478 print arg, 'has', len(f.readlines()), 'lines'
2479 f.close()
Guido van Rossum02455691997-07-17 16:21:52 +00002480\end{verbatim}
2481
2482
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002483When an exception occurs, it may have an associated value, also known as
Fred Drake8842e861998-02-13 07:16:30 +00002484the exceptions's \emph{argument}.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002485The presence and type of the argument depend on the exception type.
2486For exception types which have an argument, the except clause may
2487specify a variable after the exception name (or list) to receive the
2488argument's value, as follows:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002489
Fred Drake8842e861998-02-13 07:16:30 +00002490\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002491>>> try:
Guido van Rossume5f8b601995-01-04 19:12:49 +00002492... spam()
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002493... except NameError, x:
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002494... print 'name', x, 'undefined'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002495...
Guido van Rossume5f8b601995-01-04 19:12:49 +00002496name spam undefined
Fred Drake8842e861998-02-13 07:16:30 +00002497\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002498
Guido van Rossumb2c65561993-05-12 08:53:36 +00002499If an exception has an argument, it is printed as the last part
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002500(`detail') of the message for unhandled exceptions.
2501
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002502Exception handlers don't just handle exceptions if they occur
2503immediately in the try clause, but also if they occur inside functions
2504that are called (even indirectly) in the try clause.
2505For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002506
Fred Drake8842e861998-02-13 07:16:30 +00002507\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002508>>> def this_fails():
2509... x = 1/0
2510...
2511>>> try:
2512... this_fails()
Guido van Rossumb2c65561993-05-12 08:53:36 +00002513... except ZeroDivisionError, detail:
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002514... print 'Handling run-time error:', detail
2515...
Guido van Rossumb2c65561993-05-12 08:53:36 +00002516Handling run-time error: integer division or modulo
Fred Drake8842e861998-02-13 07:16:30 +00002517\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002518
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002519
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002520\section{Raising Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002521\label{raising}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002522
Fred Drake8842e861998-02-13 07:16:30 +00002523The \keyword{raise} statement allows the programmer to force a
2524specified exception to occur.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002525For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002526
Fred Drake8842e861998-02-13 07:16:30 +00002527\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002528>>> raise NameError, 'HiThere'
Guido van Rossum6938f061994-08-01 12:22:53 +00002529Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002530 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002531NameError: HiThere
Fred Drake8842e861998-02-13 07:16:30 +00002532\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002533
Fred Drake8842e861998-02-13 07:16:30 +00002534The first argument to \keyword{raise} names the exception to be
2535raised. The optional second argument specifies the exception's
2536argument.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002537
Guido van Rossum02455691997-07-17 16:21:52 +00002538
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002539\section{User-defined Exceptions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002540\label{userExceptions}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002541
2542Programs may name their own exceptions by assigning a string to a
2543variable.
2544For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002545
Fred Drake8842e861998-02-13 07:16:30 +00002546\begin{verbatim}
Guido van Rossumb2c65561993-05-12 08:53:36 +00002547>>> my_exc = 'my_exc'
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002548>>> try:
2549... raise my_exc, 2*2
2550... except my_exc, val:
Guido van Rossum67fa1601991-04-23 14:14:57 +00002551... print 'My exception occurred, value:', val
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002552...
Guido van Rossum6938f061994-08-01 12:22:53 +00002553My exception occurred, value: 4
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002554>>> raise my_exc, 1
Guido van Rossum6938f061994-08-01 12:22:53 +00002555Traceback (innermost last):
2556 File "<stdin>", line 1
Guido van Rossumb2c65561993-05-12 08:53:36 +00002557my_exc: 1
Fred Drake8842e861998-02-13 07:16:30 +00002558\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002559
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002560Many standard modules use this to report errors that may occur in
2561functions they define.
2562
Guido van Rossum02455691997-07-17 16:21:52 +00002563
Guido van Rossum6fc178f1991-08-16 09:13:42 +00002564\section{Defining Clean-up Actions}
Fred Drake6c2176e1998-02-26 21:47:54 +00002565\label{cleanup}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002566
Fred Drake8842e861998-02-13 07:16:30 +00002567The \keyword{try} statement has another optional clause which is
2568intended to define clean-up actions that must be executed under all
2569circumstances. For example:
Guido van Rossuma8d754e1992-01-07 16:44:35 +00002570
Fred Drake8842e861998-02-13 07:16:30 +00002571\begin{verbatim}
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002572>>> try:
2573... raise KeyboardInterrupt
2574... finally:
2575... print 'Goodbye, world!'
2576...
2577Goodbye, world!
Guido van Rossum6938f061994-08-01 12:22:53 +00002578Traceback (innermost last):
Guido van Rossum2292b8e1991-01-23 16:31:24 +00002579 File "<stdin>", line 2
Guido van Rossumb2c65561993-05-12 08:53:36 +00002580KeyboardInterrupt
Fred Drake8842e861998-02-13 07:16:30 +00002581\end{verbatim}
Fred Drake6c2176e1998-02-26 21:47:54 +00002582
Fred Drake8842e861998-02-13 07:16:30 +00002583A \emph{finally clause} is executed whether or not an exception has
2584occurred in the try clause. When an exception has occurred, it is
2585re-raised after the finally clause is executed. The finally clause is
2586also executed ``on the way out'' when the \keyword{try} statement is
2587left via a \keyword{break} or \keyword{return} statement.
Guido van Rossumda8c3fd1992-08-09 13:55:25 +00002588
Fred Drake8842e861998-02-13 07:16:30 +00002589A \keyword{try} statement must either have one or more except clauses
2590or one finally clause, but not both.
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00002591
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002592\chapter{Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00002593\label{classes}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002594
2595Python's class mechanism adds classes to the language with a minimum
2596of new syntax and semantics. It is a mixture of the class mechanisms
Guido van Rossum16d6e711994-08-08 12:30:22 +00002597found in \Cpp{} and Modula-3. As is true for modules, classes in Python
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002598do not put an absolute barrier between definition and user, but rather
2599rely on the politeness of the user not to ``break into the
2600definition.'' The most important features of classes are retained
2601with full power, however: the class inheritance mechanism allows
2602multiple base classes, a derived class can override any methods of its
Fred Drake391564f1998-04-01 23:11:56 +00002603base class or classes, a method can call the method of a base class with the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002604same name. Objects can contain an arbitrary amount of private data.
2605
Guido van Rossum16d6e711994-08-08 12:30:22 +00002606In \Cpp{} terminology, all class members (including the data members) are
Fred Drakeeee08cd1997-12-04 15:43:15 +00002607\emph{public}, and all member functions are \emph{virtual}. There are
Guido van Rossum6938f061994-08-01 12:22:53 +00002608no special constructors or destructors. As in Modula-3, there are no
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002609shorthands for referencing the object's members from its methods: the
2610method function is declared with an explicit first argument
2611representing the object, which is provided implicitly by the call. As
2612in Smalltalk, classes themselves are objects, albeit in the wider
2613sense of the word: in Python, all data types are objects. This
Guido van Rossum16d6e711994-08-08 12:30:22 +00002614provides semantics for importing and renaming. But, just like in \Cpp{}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002615or Modula-3, built-in types cannot be used as base classes for
Guido van Rossum16d6e711994-08-08 12:30:22 +00002616extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002617built-in operators with special syntax (arithmetic operators,
Fred Drake391564f1998-04-01 23:11:56 +00002618subscripting etc.) can be redefined for class instances.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002619
Fred Drakea594baf1998-04-03 05:16:31 +00002620\section{A Word About Terminology}
Fred Drake6c2176e1998-02-26 21:47:54 +00002621\label{terminology}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002622
Fred Drake391564f1998-04-01 23:11:56 +00002623Lacking universally accepted terminology to talk about classes, I will
2624make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002625terms, since its object-oriented semantics are closer to those of
Fred Drake8842e861998-02-13 07:16:30 +00002626Python than \Cpp{}, but I expect that few readers have heard of it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002627
2628I also have to warn you that there's a terminological pitfall for
2629object-oriented readers: the word ``object'' in Python does not
Fred Drake8842e861998-02-13 07:16:30 +00002630necessarily mean a class instance. Like \Cpp{} and Modula-3, and
2631unlike Smalltalk, not all types in Python are classes: the basic
Fred Drake391564f1998-04-01 23:11:56 +00002632built-in types like integers and lists are not, and even somewhat more
Fred Drake8842e861998-02-13 07:16:30 +00002633exotic types like files aren't. However, \emph{all} Python types
2634share a little bit of common semantics that is best described by using
2635the word object.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002636
2637Objects have individuality, and multiple names (in multiple scopes)
2638can be bound to the same object. This is known as aliasing in other
2639languages. This is usually not appreciated on a first glance at
2640Python, and can be safely ignored when dealing with immutable basic
2641types (numbers, strings, tuples). However, aliasing has an
Guido van Rossum6938f061994-08-01 12:22:53 +00002642(intended!) effect on the semantics of Python code involving mutable
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002643objects such as lists, dictionaries, and most types representing
2644entities outside the program (files, windows, etc.). This is usually
2645used to the benefit of the program, since aliases behave like pointers
2646in some respects. For example, passing an object is cheap since only
2647a pointer is passed by the implementation; and if a function modifies
2648an object passed as an argument, the caller will see the change --- this
2649obviates the need for two different argument passing mechanisms as in
2650Pascal.
2651
2652
Fred Drakea594baf1998-04-03 05:16:31 +00002653\section{Python Scopes and Name Spaces}
Fred Drake6c2176e1998-02-26 21:47:54 +00002654\label{scopes}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002655
2656Before introducing classes, I first have to tell you something about
2657Python's scope rules. Class definitions play some neat tricks with
2658name spaces, and you need to know how scopes and name spaces work to
2659fully understand what's going on. Incidentally, knowledge about this
2660subject is useful for any advanced Python programmer.
2661
2662Let's begin with some definitions.
2663
Fred Drakeeee08cd1997-12-04 15:43:15 +00002664A \emph{name space} is a mapping from names to objects. Most name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002665spaces are currently implemented as Python dictionaries, but that's
2666normally not noticeable in any way (except for performance), and it
2667may change in the future. Examples of name spaces are: the set of
Fred Drake8842e861998-02-13 07:16:30 +00002668built-in names (functions such as \function{abs()}, and built-in exception
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002669names); the global names in a module; and the local names in a
2670function invocation. In a sense the set of attributes of an object
Guido van Rossum16cd7f91994-10-06 10:29:26 +00002671also form a name space. The important thing to know about name
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002672spaces is that there is absolutely no relation between names in
2673different name spaces; for instance, two different modules may both
2674define a function ``maximize'' without confusion --- users of the
2675modules must prefix it with the module name.
2676
Fred Drakeeee08cd1997-12-04 15:43:15 +00002677By the way, I use the word \emph{attribute} for any name following a
Fred Drake8842e861998-02-13 07:16:30 +00002678dot --- for example, in the expression \code{z.real}, \code{real} is
2679an attribute of the object \code{z}. Strictly speaking, references to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002680names in modules are attribute references: in the expression
Fred Drake8842e861998-02-13 07:16:30 +00002681\code{modname.funcname}, \code{modname} is a module object and
2682\code{funcname} is an attribute of it. In this case there happens to
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002683be a straightforward mapping between the module's attributes and the
2684global names defined in the module: they share the same name space!%
2685\footnote{
Guido van Rossum6938f061994-08-01 12:22:53 +00002686 Except for one thing. Module objects have a secret read-only
Fred Drakeeee08cd1997-12-04 15:43:15 +00002687 attribute called \code{__dict__} which returns the dictionary
Guido van Rossum6938f061994-08-01 12:22:53 +00002688 used to implement the module's name space; the name
Fred Drakeeee08cd1997-12-04 15:43:15 +00002689 \code{__dict__} is an attribute but not a global name.
Guido van Rossum6938f061994-08-01 12:22:53 +00002690 Obviously, using this violates the abstraction of name space
2691 implementation, and should be restricted to things like
Fred Drake8842e861998-02-13 07:16:30 +00002692 post-mortem debuggers.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002693}
2694
2695Attributes may be read-only or writable. In the latter case,
2696assignment to attributes is possible. Module attributes are writable:
Fred Drake8842e861998-02-13 07:16:30 +00002697you can write \samp{modname.the_answer = 42}. Writable attributes may
Fred Drake391564f1998-04-01 23:11:56 +00002698also be deleted with the \keyword{del} statement, e.g.
Fred Drake8842e861998-02-13 07:16:30 +00002699\samp{del modname.the_answer}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002700
2701Name spaces are created at different moments and have different
2702lifetimes. The name space containing the built-in names is created
2703when the Python interpreter starts up, and is never deleted. The
2704global name space for a module is created when the module definition
2705is read in; normally, module name spaces also last until the
2706interpreter quits. The statements executed by the top-level
2707invocation of the interpreter, either read from a script file or
Fred Drake8842e861998-02-13 07:16:30 +00002708interactively, are considered part of a module called
2709\module{__main__}, so they have their own global name space. (The
2710built-in names actually also live in a module; this is called
2711\module{__builtin__}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002712
2713The local name space for a function is created when the function is
2714called, and deleted when the function returns or raises an exception
2715that is not handled within the function. (Actually, forgetting would
2716be a better way to describe what actually happens.) Of course,
2717recursive invocations each have their own local name space.
2718
Fred Drakeeee08cd1997-12-04 15:43:15 +00002719A \emph{scope} is a textual region of a Python program where a name space
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002720is directly accessible. ``Directly accessible'' here means that an
2721unqualified reference to a name attempts to find the name in the name
2722space.
2723
2724Although scopes are determined statically, they are used dynamically.
2725At any time during execution, exactly three nested scopes are in use
2726(i.e., exactly three name spaces are directly accessible): the
2727innermost scope, which is searched first, contains the local names,
2728the middle scope, searched next, contains the current module's global
2729names, and the outermost scope (searched last) is the name space
2730containing built-in names.
2731
2732Usually, the local scope references the local names of the (textually)
Guido van Rossum96628a91995-04-10 11:34:00 +00002733current function. Outside of functions, the local scope references
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002734the same name space as the global scope: the module's name space.
2735Class definitions place yet another name space in the local scope.
2736
2737It is important to realize that scopes are determined textually: the
2738global scope of a function defined in a module is that module's name
2739space, no matter from where or by what alias the function is called.
2740On the other hand, the actual search for names is done dynamically, at
Guido van Rossum96628a91995-04-10 11:34:00 +00002741run time --- however, the language definition is evolving towards
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002742static name resolution, at ``compile'' time, so don't rely on dynamic
2743name resolution! (In fact, local variables are already determined
2744statically.)
2745
2746A special quirk of Python is that assignments always go into the
2747innermost scope. Assignments do not copy data --- they just
2748bind names to objects. The same is true for deletions: the statement
Fred Drake391564f1998-04-01 23:11:56 +00002749\samp{del x} removes the binding of \code{x} from the name space
2750referenced by the local scope. In fact, all operations that introduce
2751new names use the local scope: in particular, import statements and
2752function definitions bind the module or function name in the local
2753scope. (The \keyword{global} statement can be used to indicate that
2754particular variables live in the global scope.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002755
2756
Fred Drakea594baf1998-04-03 05:16:31 +00002757\section{A First Look at Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00002758\label{firstClasses}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002759
2760Classes introduce a little bit of new syntax, three new object types,
2761and some new semantics.
2762
2763
Fred Drakea594baf1998-04-03 05:16:31 +00002764\subsection{Class Definition Syntax}
Fred Drake6c2176e1998-02-26 21:47:54 +00002765\label{classDefinition}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002766
2767The simplest form of class definition looks like this:
2768
2769\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002770class ClassName:
2771 <statement-1>
2772 .
2773 .
2774 .
2775 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002776\end{verbatim}
2777
Fred Drake8842e861998-02-13 07:16:30 +00002778Class definitions, like function definitions (\keyword{def}
2779statements) must be executed before they have any effect. (You could
2780conceivably place a class definition in a branch of an \keyword{if}
2781statement, or inside a function.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002782
2783In practice, the statements inside a class definition will usually be
2784function definitions, but other statements are allowed, and sometimes
2785useful --- we'll come back to this later. The function definitions
2786inside a class normally have a peculiar form of argument list,
2787dictated by the calling conventions for methods --- again, this is
2788explained later.
2789
2790When a class definition is entered, a new name space is created, and
2791used as the local scope --- thus, all assignments to local variables
2792go into this new name space. In particular, function definitions bind
2793the name of the new function here.
2794
Fred Drakeeee08cd1997-12-04 15:43:15 +00002795When a class definition is left normally (via the end), a \emph{class
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002796object} is created. This is basically a wrapper around the contents
2797of the name space created by the class definition; we'll learn more
2798about class objects in the next section. The original local scope
2799(the one in effect just before the class definitions was entered) is
Fred Drakea594baf1998-04-03 05:16:31 +00002800reinstated, and the class object is bound here to the class name given
2801in the class definition header (\class{ClassName} in the example).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002802
2803
Fred Drakea594baf1998-04-03 05:16:31 +00002804\subsection{Class Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002805\label{classObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002806
2807Class objects support two kinds of operations: attribute references
2808and instantiation.
2809
Fred Drakeeee08cd1997-12-04 15:43:15 +00002810\emph{Attribute references} use the standard syntax used for all
Fred Drake8842e861998-02-13 07:16:30 +00002811attribute references in Python: \code{obj.name}. Valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002812names are all the names that were in the class's name space when the
2813class object was created. So, if the class definition looked like
2814this:
2815
2816\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002817class MyClass:
2818 "A simple example class"
2819 i = 12345
2820 def f(x):
2821 return 'hello world'
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002822\end{verbatim}
2823
Fred Drake8842e861998-02-13 07:16:30 +00002824then \code{MyClass.i} and \code{MyClass.f} are valid attribute
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002825references, returning an integer and a function object, respectively.
Guido van Rossum02455691997-07-17 16:21:52 +00002826Class attributes can also be assigned to, so you can change the value
Fred Drake8842e861998-02-13 07:16:30 +00002827of \code{MyClass.i} by assignment. \code{__doc__} is also a valid
Guido van Rossum02455691997-07-17 16:21:52 +00002828attribute that's read-only, returning the docstring belonging to
Fred Drake8842e861998-02-13 07:16:30 +00002829the class: \code{"A simple example class"}).
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002830
Fred Drakeeee08cd1997-12-04 15:43:15 +00002831Class \emph{instantiation} uses function notation. Just pretend that
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002832the class object is a parameterless function that returns a new
2833instance of the class. For example, (assuming the above class):
2834
2835\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002836x = MyClass()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002837\end{verbatim}
2838
Fred Drakeeee08cd1997-12-04 15:43:15 +00002839creates a new \emph{instance} of the class and assigns this object to
2840the local variable \code{x}.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002841
2842
Fred Drakea594baf1998-04-03 05:16:31 +00002843\subsection{Instance Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002844\label{instanceObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002845
2846Now what can we do with instance objects? The only operations
2847understood by instance objects are attribute references. There are
2848two kinds of valid attribute names.
2849
Fred Drakeeee08cd1997-12-04 15:43:15 +00002850The first I'll call \emph{data attributes}. These correspond to
Fred Drake8842e861998-02-13 07:16:30 +00002851``instance variables'' in Smalltalk, and to ``data members'' in
2852\Cpp{}. Data attributes need not be declared; like local variables,
2853they spring into existence when they are first assigned to. For
2854example, if \code{x} is the instance of \class{MyClass} created above,
2855the following piece of code will print the value \code{16}, without
2856leaving a trace:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002857
2858\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002859x.counter = 1
2860while x.counter < 10:
2861 x.counter = x.counter * 2
2862print x.counter
2863del x.counter
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002864\end{verbatim}
2865
2866The second kind of attribute references understood by instance objects
Fred Drakeeee08cd1997-12-04 15:43:15 +00002867are \emph{methods}. A method is a function that ``belongs to'' an
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002868object. (In Python, the term method is not unique to class instances:
2869other object types can have methods as well, e.g., list objects have
2870methods called append, insert, remove, sort, and so on. However,
2871below, we'll use the term method exclusively to mean methods of class
2872instance objects, unless explicitly stated otherwise.)
2873
2874Valid method names of an instance object depend on its class. By
Fred Drake8842e861998-02-13 07:16:30 +00002875definition, all attributes of a class that are (user-defined) function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002876objects define corresponding methods of its instances. So in our
Fred Drakeeee08cd1997-12-04 15:43:15 +00002877example, \code{x.f} is a valid method reference, since
2878\code{MyClass.f} is a function, but \code{x.i} is not, since
Fred Drake8842e861998-02-13 07:16:30 +00002879\code{MyClass.i} is not. But \code{x.f} is not the same thing as
2880\code{MyClass.f} --- it is a \emph{method object}, not a function
Fred Drakea594baf1998-04-03 05:16:31 +00002881object.%
2882\obindex{method}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002883
2884
Fred Drakea594baf1998-04-03 05:16:31 +00002885\subsection{Method Objects}
Fred Drake6c2176e1998-02-26 21:47:54 +00002886\label{methodObjects}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002887
2888Usually, a method is called immediately, e.g.:
2889
2890\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002891x.f()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002892\end{verbatim}
2893
Fred Drake8842e861998-02-13 07:16:30 +00002894In our example, this will return the string \code{'hello world'}.
2895However, it is not necessary to call a method right away: \code{x.f}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002896is a method object, and can be stored away and called at a later
2897moment, for example:
2898
2899\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002900xf = x.f
2901while 1:
2902 print xf()
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002903\end{verbatim}
2904
Fred Drake8842e861998-02-13 07:16:30 +00002905will continue to print \samp{hello world} until the end of time.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002906
2907What exactly happens when a method is called? You may have noticed
Fred Drake8842e861998-02-13 07:16:30 +00002908that \code{x.f()} was called without an argument above, even though
2909the function definition for \method{f} specified an argument. What
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002910happened to the argument? Surely Python raises an exception when a
2911function that requires an argument is called without any --- even if
2912the argument isn't actually used...
2913
2914Actually, you may have guessed the answer: the special thing about
2915methods is that the object is passed as the first argument of the
Fred Drake8842e861998-02-13 07:16:30 +00002916function. In our example, the call \code{x.f()} is exactly equivalent
2917to \code{MyClass.f(x)}. In general, calling a method with a list of
Fred Drakeeee08cd1997-12-04 15:43:15 +00002918\var{n} arguments is equivalent to calling the corresponding function
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002919with an argument list that is created by inserting the method's object
2920before the first argument.
2921
2922If you still don't understand how methods work, a look at the
2923implementation can perhaps clarify matters. When an instance
2924attribute is referenced that isn't a data attribute, its class is
2925searched. If the name denotes a valid class attribute that is a
2926function object, a method object is created by packing (pointers to)
2927the instance object and the function object just found together in an
2928abstract object: this is the method object. When the method object is
2929called with an argument list, it is unpacked again, a new argument
2930list is constructed from the instance object and the original argument
2931list, and the function object is called with this new argument list.
2932
2933
Fred Drakea594baf1998-04-03 05:16:31 +00002934\section{Random Remarks}
Fred Drake6c2176e1998-02-26 21:47:54 +00002935\label{remarks}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002936
2937[These should perhaps be placed more carefully...]
2938
2939
2940Data attributes override method attributes with the same name; to
2941avoid accidental name conflicts, which may cause hard-to-find bugs in
2942large programs, it is wise to use some kind of convention that
2943minimizes the chance of conflicts, e.g., capitalize method names,
2944prefix data attribute names with a small unique string (perhaps just
Guido van Rossum6938f061994-08-01 12:22:53 +00002945an underscore), or use verbs for methods and nouns for data attributes.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002946
2947
2948Data attributes may be referenced by methods as well as by ordinary
2949users (``clients'') of an object. In other words, classes are not
2950usable to implement pure abstract data types. In fact, nothing in
2951Python makes it possible to enforce data hiding --- it is all based
2952upon convention. (On the other hand, the Python implementation,
Fred Drake3f205921998-01-13 18:56:38 +00002953written in \C{}, can completely hide implementation details and control
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002954access to an object if necessary; this can be used by extensions to
Fred Drake3f205921998-01-13 18:56:38 +00002955Python written in \C{}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002956
2957
2958Clients should use data attributes with care --- clients may mess up
2959invariants maintained by the methods by stamping on their data
2960attributes. Note that clients may add data attributes of their own to
2961an instance object without affecting the validity of the methods, as
2962long as name conflicts are avoided --- again, a naming convention can
2963save a lot of headaches here.
2964
2965
2966There is no shorthand for referencing data attributes (or other
2967methods!) from within methods. I find that this actually increases
2968the readability of methods: there is no chance of confusing local
2969variables and instance variables when glancing through a method.
2970
2971
2972Conventionally, the first argument of methods is often called
Fred Drake8842e861998-02-13 07:16:30 +00002973\code{self}. This is nothing more than a convention: the name
2974\code{self} has absolutely no special meaning to Python. (Note,
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002975however, that by not following the convention your code may be less
2976readable by other Python programmers, and it is also conceivable that
Fred Drakeeee08cd1997-12-04 15:43:15 +00002977a \emph{class browser} program be written which relies upon such a
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002978convention.)
2979
2980
2981Any function object that is a class attribute defines a method for
2982instances of that class. It is not necessary that the function
2983definition is textually enclosed in the class definition: assigning a
2984function object to a local variable in the class is also ok. For
2985example:
2986
2987\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00002988# Function defined outside the class
2989def f1(self, x, y):
2990 return min(x, x+y)
2991
2992class C:
2993 f = f1
2994 def g(self):
2995 return 'hello world'
2996 h = g
Guido van Rossum5e0759d1992-08-07 16:06:24 +00002997\end{verbatim}
2998
Fred Drake8842e861998-02-13 07:16:30 +00002999Now \code{f}, \code{g} and \code{h} are all attributes of class
3000\class{C} that refer to function objects, and consequently they are all
3001methods of instances of \class{C} --- \code{h} being exactly equivalent
3002to \code{g}. Note that this practice usually only serves to confuse
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003003the reader of a program.
3004
3005
3006Methods may call other methods by using method attributes of the
Fred Drake8842e861998-02-13 07:16:30 +00003007\code{self} argument, e.g.:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003008
3009\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003010class Bag:
3011 def empty(self):
3012 self.data = []
3013 def add(self, x):
3014 self.data.append(x)
3015 def addtwice(self, x):
3016 self.add(x)
3017 self.add(x)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003018\end{verbatim}
3019
3020
3021The instantiation operation (``calling'' a class object) creates an
3022empty object. Many classes like to create objects in a known initial
Guido van Rossumca3f6c81994-10-06 14:08:53 +00003023state. Therefore a class may define a special method named
Fred Drake8842e861998-02-13 07:16:30 +00003024\method{__init__()}, like this:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003025
Guido van Rossum6938f061994-08-01 12:22:53 +00003026\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003027 def __init__(self):
3028 self.empty()
Guido van Rossum6938f061994-08-01 12:22:53 +00003029\end{verbatim}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003030
Fred Drake8842e861998-02-13 07:16:30 +00003031When a class defines an \method{__init__()} method, class
3032instantiation automatically invokes \method{__init__()} for the
3033newly-created class instance. So in the \class{Bag} example, a new
3034and initialized instance can be obtained by:
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003035
Guido van Rossum6938f061994-08-01 12:22:53 +00003036\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003037x = Bag()
Guido van Rossum6938f061994-08-01 12:22:53 +00003038\end{verbatim}
3039
Fred Drake8842e861998-02-13 07:16:30 +00003040Of course, the \method{__init__()} method may have arguments for
3041greater flexibility. In that case, arguments given to the class
3042instantiation operator are passed on to \method{__init__()}. For
3043example,
Guido van Rossum6938f061994-08-01 12:22:53 +00003044
Fred Drake8842e861998-02-13 07:16:30 +00003045\begin{verbatim}
Guido van Rossum6938f061994-08-01 12:22:53 +00003046>>> class Complex:
3047... def __init__(self, realpart, imagpart):
3048... self.r = realpart
3049... self.i = imagpart
3050...
3051>>> x = Complex(3.0,-4.5)
3052>>> x.r, x.i
3053(3.0, -4.5)
Fred Drake8842e861998-02-13 07:16:30 +00003054\end{verbatim}
3055
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003056Methods may reference global names in the same way as ordinary
3057functions. The global scope associated with a method is the module
3058containing the class definition. (The class itself is never used as a
3059global scope!) While one rarely encounters a good reason for using
3060global data in a method, there are many legitimate uses of the global
3061scope: for one thing, functions and modules imported into the global
3062scope can be used by methods, as well as functions and classes defined
3063in it. Usually, the class containing the method is itself defined in
3064this global scope, and in the next section we'll find some good
3065reasons why a method would want to reference its own class!
3066
3067
3068\section{Inheritance}
Fred Drake6c2176e1998-02-26 21:47:54 +00003069\label{inheritance}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003070
3071Of course, a language feature would not be worthy of the name ``class''
3072without supporting inheritance. The syntax for a derived class
3073definition looks as follows:
3074
3075\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003076class DerivedClassName(BaseClassName):
3077 <statement-1>
3078 .
3079 .
3080 .
3081 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003082\end{verbatim}
3083
Fred Drake8842e861998-02-13 07:16:30 +00003084The name \class{BaseClassName} must be defined in a scope containing
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003085the derived class definition. Instead of a base class name, an
3086expression is also allowed. This is useful when the base class is
3087defined in another module, e.g.,
3088
3089\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003090class DerivedClassName(modname.BaseClassName):
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003091\end{verbatim}
3092
3093Execution of a derived class definition proceeds the same as for a
3094base class. When the class object is constructed, the base class is
3095remembered. This is used for resolving attribute references: if a
3096requested attribute is not found in the class, it is searched in the
3097base class. This rule is applied recursively if the base class itself
3098is derived from some other class.
3099
3100There's nothing special about instantiation of derived classes:
Fred Drake8842e861998-02-13 07:16:30 +00003101\code{DerivedClassName()} creates a new instance of the class. Method
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003102references are resolved as follows: the corresponding class attribute
3103is searched, descending down the chain of base classes if necessary,
3104and the method reference is valid if this yields a function object.
3105
3106Derived classes may override methods of their base classes. Because
3107methods have no special privileges when calling other methods of the
3108same object, a method of a base class that calls another method
3109defined in the same base class, may in fact end up calling a method of
Guido van Rossum16d6e711994-08-08 12:30:22 +00003110a derived class that overrides it. (For \Cpp{} programmers: all methods
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003111in Python are ``virtual functions''.)
3112
3113An overriding method in a derived class may in fact want to extend
3114rather than simply replace the base class method of the same name.
3115There is a simple way to call the base class method directly: just
Fred Drake8842e861998-02-13 07:16:30 +00003116call \samp{BaseClassName.methodname(self, arguments)}. This is
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003117occasionally useful to clients as well. (Note that this only works if
3118the base class is defined or imported directly in the global scope.)
3119
3120
Fred Drakea594baf1998-04-03 05:16:31 +00003121\subsection{Multiple Inheritance}
Fred Drake6c2176e1998-02-26 21:47:54 +00003122\label{multiple}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003123
Guido van Rossum6938f061994-08-01 12:22:53 +00003124Python supports a limited form of multiple inheritance as well. A
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003125class definition with multiple base classes looks as follows:
3126
3127\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003128class DerivedClassName(Base1, Base2, Base3):
3129 <statement-1>
3130 .
3131 .
3132 .
3133 <statement-N>
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003134\end{verbatim}
3135
3136The only rule necessary to explain the semantics is the resolution
3137rule used for class attribute references. This is depth-first,
3138left-to-right. Thus, if an attribute is not found in
Fred Drake8842e861998-02-13 07:16:30 +00003139\class{DerivedClassName}, it is searched in \class{Base1}, then
3140(recursively) in the base classes of \class{Base1}, and only if it is
3141not found there, it is searched in \class{Base2}, and so on.
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003142
Fred Drake8842e861998-02-13 07:16:30 +00003143(To some people breadth first --- searching \class{Base2} and
3144\class{Base3} before the base classes of \class{Base1} --- looks more
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003145natural. However, this would require you to know whether a particular
Fred Drake8842e861998-02-13 07:16:30 +00003146attribute of \class{Base1} is actually defined in \class{Base1} or in
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003147one of its base classes before you can figure out the consequences of
Fred Drake8842e861998-02-13 07:16:30 +00003148a name conflict with an attribute of \class{Base2}. The depth-first
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003149rule makes no differences between direct and inherited attributes of
Fred Drake8842e861998-02-13 07:16:30 +00003150\class{Base1}.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003151
3152It is clear that indiscriminate use of multiple inheritance is a
3153maintenance nightmare, given the reliance in Python on conventions to
3154avoid accidental name conflicts. A well-known problem with multiple
3155inheritance is a class derived from two classes that happen to have a
3156common base class. While it is easy enough to figure out what happens
3157in this case (the instance will have a single copy of ``instance
3158variables'' or data attributes used by the common base class), it is
3159not clear that these semantics are in any way useful.
3160
3161
Fred Drakea594baf1998-04-03 05:16:31 +00003162\section{Private Variables}
Fred Drake6c2176e1998-02-26 21:47:54 +00003163\label{private}
Guido van Rossum02455691997-07-17 16:21:52 +00003164
Fred Drakea594baf1998-04-03 05:16:31 +00003165There is limited support for class-private
Guido van Rossum02455691997-07-17 16:21:52 +00003166identifiers. Any identifier of the form \code{__spam} (at least two
3167leading underscores, at most one trailing underscore) is now textually
3168replaced with \code{_classname__spam}, where \code{classname} is the
3169current class name with leading underscore(s) stripped. This mangling
3170is done without regard of the syntactic position of the identifier, so
3171it can be used to define class-private instance and class variables,
3172methods, as well as globals, and even to store instance variables
Fred Drakeeee08cd1997-12-04 15:43:15 +00003173private to this class on instances of \emph{other} classes. Truncation
Guido van Rossum02455691997-07-17 16:21:52 +00003174may occur when the mangled name would be longer than 255 characters.
3175Outside classes, or when the class name consists of only underscores,
3176no mangling occurs.
3177
3178Name mangling is intended to give classes an easy way to define
3179``private'' instance variables and methods, without having to worry
3180about instance variables defined by derived classes, or mucking with
3181instance variables by code outside the class. Note that the mangling
3182rules are designed mostly to avoid accidents; it still is possible for
3183a determined soul to access or modify a variable that is considered
3184private. This can even be useful, e.g. for the debugger, and that's
3185one reason why this loophole is not closed. (Buglet: derivation of a
3186class with the same name as the base class makes use of private
3187variables of the base class possible.)
3188
3189Notice that code passed to \code{exec}, \code{eval()} or
3190\code{evalfile()} does not consider the classname of the invoking
3191class to be the current class; this is similar to the effect of the
3192\code{global} statement, the effect of which is likewise restricted to
3193code that is byte-compiled together. The same restriction applies to
3194\code{getattr()}, \code{setattr()} and \code{delattr()}, as well as
3195when referencing \code{__dict__} directly.
3196
3197Here's an example of a class that implements its own
3198\code{__getattr__} and \code{__setattr__} methods and stores all
3199attributes in a private variable, in a way that works in Python 1.4 as
3200well as in previous versions:
3201
3202\begin{verbatim}
3203class VirtualAttributes:
3204 __vdict = None
3205 __vdict_name = locals().keys()[0]
3206
3207 def __init__(self):
3208 self.__dict__[self.__vdict_name] = {}
3209
3210 def __getattr__(self, name):
3211 return self.__vdict[name]
3212
3213 def __setattr__(self, name, value):
3214 self.__vdict[name] = value
3215\end{verbatim}
3216
Fred Drakeaf8a0151998-01-14 14:51:31 +00003217%\emph{Warning: this is an experimental feature.} To avoid all
Guido van Rossum02455691997-07-17 16:21:52 +00003218%potential problems, refrain from using identifiers starting with
3219%double underscore except for predefined uses like \code{__init__}. To
3220%use private names while maintaining future compatibility: refrain from
3221%using the same private name in classes related via subclassing; avoid
3222%explicit (manual) mangling/unmangling; and assume that at some point
3223%in the future, leading double underscore will revert to being just a
3224%naming convention. Discussion on extensive compile-time declarations
3225%are currently underway, and it is impossible to predict what solution
3226%will eventually be chosen for private names. Double leading
3227%underscore is still a candidate, of course --- just not the only one.
3228%It is placed in the distribution in the belief that it is useful, and
3229%so that widespread experience with its use can be gained. It will not
3230%be removed without providing a better solution and a migration path.
3231
Fred Drakea594baf1998-04-03 05:16:31 +00003232\section{Odds and Ends}
Fred Drake6c2176e1998-02-26 21:47:54 +00003233\label{odds}
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003234
3235Sometimes it is useful to have a data type similar to the Pascal
Fred Drake3f205921998-01-13 18:56:38 +00003236``record'' or \C{} ``struct'', bundling together a couple of named data
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003237items. An empty class definition will do nicely, e.g.:
3238
3239\begin{verbatim}
Fred Drake8842e861998-02-13 07:16:30 +00003240class Employee:
3241 pass
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003242
Fred Drake8842e861998-02-13 07:16:30 +00003243john = Employee() # Create an empty employee record
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003244
Fred Drake8842e861998-02-13 07:16:30 +00003245# Fill the fields of the record
3246john.name = 'John Doe'
3247john.dept = 'computer lab'
3248john.salary = 1000
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003249\end{verbatim}
3250
3251
3252A piece of Python code that expects a particular abstract data type
3253can often be passed a class that emulates the methods of that data
3254type instead. For instance, if you have a function that formats some
3255data from a file object, you can define a class with methods
Fred Drake8842e861998-02-13 07:16:30 +00003256\method{read()} and \method{readline()} that gets the data from a string
Fred Drake391564f1998-04-01 23:11:56 +00003257buffer instead, and pass it as an argument.% (Unfortunately, this
3258%technique has its limitations: a class can't define operations that
3259%are accessed by special syntax such as sequence subscripting or
3260%arithmetic operators, and assigning such a ``pseudo-file'' to
3261%\code{sys.stdin} will not cause the interpreter to read further input
3262%from it.)
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003263
3264
Fred Drake8842e861998-02-13 07:16:30 +00003265Instance method objects have attributes, too: \code{m.im_self} is the
3266object of which the method is an instance, and \code{m.im_func} is the
Guido van Rossum5e0759d1992-08-07 16:06:24 +00003267function object corresponding to the method.
3268
Guido van Rossum02455691997-07-17 16:21:52 +00003269\subsection{Exceptions Can Be Classes}
Fred Drake6c2176e1998-02-26 21:47:54 +00003270\label{exceptionClasses}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003271
3272User-defined exceptions are no longer limited to being string objects
3273--- they can be identified by classes as well. Using this mechanism it
3274is possible to create extensible hierarchies of exceptions.
3275
3276There are two new valid (semantic) forms for the raise statement:
3277
3278\begin{verbatim}
3279raise Class, instance
3280
3281raise instance
3282\end{verbatim}
3283
Fred Drake8842e861998-02-13 07:16:30 +00003284In the first form, \code{instance} must be an instance of \class{Class}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003285or of a class derived from it. The second form is a shorthand for
3286
3287\begin{verbatim}
3288raise instance.__class__, instance
3289\end{verbatim}
3290
3291An except clause may list classes as well as string objects. A class
3292in an except clause is compatible with an exception if it is the same
3293class or a base class thereof (but not the other way around --- an
3294except clause listing a derived class is not compatible with a base
3295class). For example, the following code will print B, C, D in that
3296order:
3297
3298\begin{verbatim}
3299class B:
3300 pass
3301class C(B):
3302 pass
3303class D(C):
3304 pass
3305
3306for c in [B, C, D]:
3307 try:
3308 raise c()
3309 except D:
3310 print "D"
3311 except C:
3312 print "C"
3313 except B:
3314 print "B"
3315\end{verbatim}
3316
Fred Drake8842e861998-02-13 07:16:30 +00003317Note that if the except clauses were reversed (with \samp{except B}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003318first), it would have printed B, B, B --- the first matching except
3319clause is triggered.
3320
3321When an error message is printed for an unhandled exception which is a
3322class, the class name is printed, then a colon and a space, and
3323finally the instance converted to a string using the built-in function
Fred Drake8842e861998-02-13 07:16:30 +00003324\function{str()}.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003325
Guido van Rossum194e57c1995-02-15 15:51:38 +00003326
Guido van Rossum02455691997-07-17 16:21:52 +00003327\chapter{What Now?}
Fred Drake6c2176e1998-02-26 21:47:54 +00003328\label{whatNow}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003329
Guido van Rossum02455691997-07-17 16:21:52 +00003330Hopefully reading this tutorial has reinforced your interest in using
3331Python. Now what should you do?
Guido van Rossum194e57c1995-02-15 15:51:38 +00003332
Guido van Rossum02455691997-07-17 16:21:52 +00003333You should read, or at least page through, the Library Reference,
3334which gives complete (though terse) reference material about types,
3335functions, and modules that can save you a lot of time when writing
3336Python programs. The standard Python distribution includes a
Fred Drake3f205921998-01-13 18:56:38 +00003337\emph{lot} of code in both \C{} and Python; there are modules to read
Fred Drake8842e861998-02-13 07:16:30 +00003338\UNIX{} mailboxes, retrieve documents via HTTP, generate random
3339numbers, parse command-line options, write CGI programs, compress
3340data, and a lot more; skimming through the Library Reference will give
3341you an idea of what's available.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003342
Fred Drakeca6567f1998-01-22 20:44:18 +00003343The major Python Web site is \url{http://www.python.org}; it contains
Guido van Rossum02455691997-07-17 16:21:52 +00003344code, documentation, and pointers to Python-related pages around the
Fred Drake391564f1998-04-01 23:11:56 +00003345Web. This web site is mirrored in various places around the
Guido van Rossum02455691997-07-17 16:21:52 +00003346world, such as Europe, Japan, and Australia; a mirror may be faster
3347than the main site, depending on your geographical location. A more
Fred Drakeca6567f1998-01-22 20:44:18 +00003348informal site is \url{http://starship.skyport.net}, which contains a
Guido van Rossum02455691997-07-17 16:21:52 +00003349bunch of Python-related personal home pages; many people have
3350downloadable software here.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003351
Guido van Rossum02455691997-07-17 16:21:52 +00003352For Python-related questions and problem reports, you can post to the
Fred Drake391564f1998-04-01 23:11:56 +00003353newsgroup \newsgroup{comp.lang.python}, or send them to the mailing
3354list at \email{python-list@cwi.nl}. The newsgroup and mailing list
3355are gatewayed, so messages posted to one will automatically be
3356forwarded to the other. There are around 35--45 postings a day,
3357% Postings figure based on average of last six months activity as
3358% reported by www.findmail.com; Oct. '97 - Mar. '98: 7480 msgs / 182
3359% days = 41.1 msgs / day.
3360asking (and answering) questions, suggesting new features, and
3361announcing new modules. Before posting, be sure to check the list of
3362Frequently Asked Questions (also called the FAQ), at
Fred Drakeca6567f1998-01-22 20:44:18 +00003363\url{http://www.python.org/doc/FAQ.html}, or look for it in the
3364\file{Misc/} directory of the Python source distribution. The FAQ
Guido van Rossum02455691997-07-17 16:21:52 +00003365answers many of the questions that come up again and again, and may
3366already contain the solution for your problem.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003367
Guido van Rossum02455691997-07-17 16:21:52 +00003368You can support the Python community by joining the Python Software
3369Activity, which runs the python.org web, ftp and email servers, and
Fred Drakeca6567f1998-01-22 20:44:18 +00003370organizes Python workshops. See \url{http://www.python.org/psa/} for
Guido van Rossum02455691997-07-17 16:21:52 +00003371information on how to join.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003372
Guido van Rossum194e57c1995-02-15 15:51:38 +00003373
Fred Drakea594baf1998-04-03 05:16:31 +00003374\appendix
Guido van Rossum194e57c1995-02-15 15:51:38 +00003375
Fred Drakea594baf1998-04-03 05:16:31 +00003376\chapter{Interactive Input Editing and History Substitution}
Fred Drake6c2176e1998-02-26 21:47:54 +00003377\label{interacting}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003378
Guido van Rossum02455691997-07-17 16:21:52 +00003379Some versions of the Python interpreter support editing of the current
3380input line and history substitution, similar to facilities found in
3381the Korn shell and the GNU Bash shell. This is implemented using the
Fred Drakeeee08cd1997-12-04 15:43:15 +00003382\emph{GNU Readline} library, which supports Emacs-style and vi-style
Guido van Rossum02455691997-07-17 16:21:52 +00003383editing. This library has its own documentation which I won't
3384duplicate here; however, the basics are easily explained.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003385
Fred Drake8d486b11998-02-11 22:12:18 +00003386\section{Line Editing}
Fred Drake6c2176e1998-02-26 21:47:54 +00003387\label{lineEditing}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003388
Guido van Rossum02455691997-07-17 16:21:52 +00003389If supported, input line editing is active whenever the interpreter
3390prints a primary or secondary prompt. The current line can be edited
3391using the conventional Emacs control characters. The most important
3392of these are: C-A (Control-A) moves the cursor to the beginning of the
3393line, C-E to the end, C-B moves it one position to the left, C-F to
3394the right. Backspace erases the character to the left of the cursor,
3395C-D the character to its right. C-K kills (erases) the rest of the
3396line to the right of the cursor, C-Y yanks back the last killed
3397string. C-underscore undoes the last change you made; it can be
3398repeated for cumulative effect.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003399
Fred Drake8d486b11998-02-11 22:12:18 +00003400\section{History Substitution}
Fred Drake6c2176e1998-02-26 21:47:54 +00003401\label{history}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003402
Guido van Rossum02455691997-07-17 16:21:52 +00003403History substitution works as follows. All non-empty input lines
3404issued are saved in a history buffer, and when a new prompt is given
3405you are positioned on a new line at the bottom of this buffer. C-P
3406moves one line up (back) in the history buffer, C-N moves one down.
3407Any line in the history buffer can be edited; an asterisk appears in
3408front of the prompt to mark a line as modified. Pressing the Return
3409key passes the current line to the interpreter. C-R starts an
3410incremental reverse search; C-S starts a forward search.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003411
Fred Drake8d486b11998-02-11 22:12:18 +00003412\section{Key Bindings}
Fred Drake6c2176e1998-02-26 21:47:54 +00003413\label{keyBindings}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003414
Guido van Rossum02455691997-07-17 16:21:52 +00003415The key bindings and some other parameters of the Readline library can
3416be customized by placing commands in an initialization file called
Fred Drakeeee08cd1997-12-04 15:43:15 +00003417\file{\$HOME/.inputrc}. Key bindings have the form
Guido van Rossum194e57c1995-02-15 15:51:38 +00003418
Fred Drake8842e861998-02-13 07:16:30 +00003419\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003420key-name: function-name
Fred Drake8842e861998-02-13 07:16:30 +00003421\end{verbatim}
3422
Guido van Rossum02455691997-07-17 16:21:52 +00003423or
Guido van Rossum194e57c1995-02-15 15:51:38 +00003424
Fred Drake8842e861998-02-13 07:16:30 +00003425\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003426"string": function-name
Fred Drake8842e861998-02-13 07:16:30 +00003427\end{verbatim}
3428
Guido van Rossum02455691997-07-17 16:21:52 +00003429and options can be set with
Guido van Rossum194e57c1995-02-15 15:51:38 +00003430
Fred Drake8842e861998-02-13 07:16:30 +00003431\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003432set option-name value
Fred Drake8842e861998-02-13 07:16:30 +00003433\end{verbatim}
3434
Guido van Rossum02455691997-07-17 16:21:52 +00003435For example:
Guido van Rossum194e57c1995-02-15 15:51:38 +00003436
Fred Drake8842e861998-02-13 07:16:30 +00003437\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003438# I prefer vi-style editing:
3439set editing-mode vi
3440# Edit using a single line:
3441set horizontal-scroll-mode On
3442# Rebind some keys:
3443Meta-h: backward-kill-word
3444"\C-u": universal-argument
3445"\C-x\C-r": re-read-init-file
Fred Drake8842e861998-02-13 07:16:30 +00003446\end{verbatim}
3447
Guido van Rossum02455691997-07-17 16:21:52 +00003448Note that the default binding for TAB in Python is to insert a TAB
3449instead of Readline's default filename completion function. If you
3450insist, you can override this by putting
Guido van Rossum194e57c1995-02-15 15:51:38 +00003451
Fred Drake8842e861998-02-13 07:16:30 +00003452\begin{verbatim}
Guido van Rossum02455691997-07-17 16:21:52 +00003453TAB: complete
Fred Drake8842e861998-02-13 07:16:30 +00003454\end{verbatim}
3455
Fred Drakeeee08cd1997-12-04 15:43:15 +00003456in your \file{\$HOME/.inputrc}. (Of course, this makes it hard to type
Guido van Rossum02455691997-07-17 16:21:52 +00003457indented continuation lines...)
Guido van Rossum194e57c1995-02-15 15:51:38 +00003458
Fred Drake72389881998-04-13 01:31:10 +00003459Automatic completion of variable and module names is optionally
3460available. To enable it in the interpreter's interactive mode, add
3461the following to your \file{\$HOME/.pythonrc} file:% $ <- bow to font-lock
3462\indexii{.pythonrc.py}{file}%
3463\refstmodindex{rlcompleter}%
3464\refbimodindex{readline}
3465
3466\begin{verbatim}
3467import rlcompleter, readline
3468readline.parse_and_bind('tab: complete')
3469\end{verbatim}
3470
3471This binds the TAB key to the completion function, so hitting the TAB
3472key twice suggests completions; it looks at Python statement names,
3473the current local variables, and the available module names. For
3474dotted expressions such as \code{string.a}, it will evaluate the the
3475expression up to the final \character{.} and then suggest completions
3476from the attributes of the resulting object. Note that this may
3477execute application-defined code if an object with a
3478\method{__getattr__()} method is part of the expression.
3479
3480
Fred Drake8d486b11998-02-11 22:12:18 +00003481\section{Commentary}
Fred Drake6c2176e1998-02-26 21:47:54 +00003482\label{commentary}
Guido van Rossum194e57c1995-02-15 15:51:38 +00003483
Guido van Rossum02455691997-07-17 16:21:52 +00003484This facility is an enormous step forward compared to previous
3485versions of the interpreter; however, some wishes are left: It would
3486be nice if the proper indentation were suggested on continuation lines
3487(the parser knows if an indent token is required next). The
3488completion mechanism might use the interpreter's symbol table. A
3489command to check (or even suggest) matching parentheses, quotes etc.
3490would also be useful.
Guido van Rossum194e57c1995-02-15 15:51:38 +00003491
Fred Drake8842e861998-02-13 07:16:30 +00003492% XXX Lele Gaifax's readline module, which adds name completion...
Guido van Rossum97662c81996-08-23 15:35:47 +00003493
Guido van Rossumd9bf55d1991-01-11 16:35:08 +00003494\end{document}
Guido van Rossum02455691997-07-17 16:21:52 +00003495