Fred Drake | 6659c30 | 1998-03-03 22:02:19 +0000 | [diff] [blame] | 1 | \documentclass{manual} |
Fred Drake | 1b0b2a4 | 2001-03-13 17:56:08 +0000 | [diff] [blame] | 2 | \usepackage[T1]{fontenc} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4 | % Things to do: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5 | % Should really move the Python startup file info to an appendix |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 7 | \title{Python Tutorial} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 9 | \input{boilerplate} |
Guido van Rossum | 83eb962 | 1993-11-23 16:28:45 +0000 | [diff] [blame] | 10 | |
Skip Montanaro | 40d4bc5 | 2003-09-24 16:53:02 +0000 | [diff] [blame] | 11 | \makeindex |
| 12 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 13 | \begin{document} |
| 14 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 15 | \maketitle |
| 16 | |
Fred Drake | 9f86b66 | 1998-07-28 21:55:19 +0000 | [diff] [blame] | 17 | \ifhtml |
| 18 | \chapter*{Front Matter\label{front}} |
| 19 | \fi |
| 20 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 21 | \input{copyright} |
| 22 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 23 | \begin{abstract} |
| 24 | |
| 25 | \noindent |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 26 | Python is an easy to learn, powerful programming language. It has |
| 27 | efficient high-level data structures and a simple but effective |
| 28 | approach to object-oriented programming. Python's elegant syntax and |
| 29 | dynamic typing, together with its interpreted nature, make it an ideal |
| 30 | language for scripting and rapid application development in many areas |
| 31 | on most platforms. |
| 32 | |
| 33 | The Python interpreter and the extensive standard library are freely |
| 34 | available in source or binary form for all major platforms from the |
Fred Drake | 17f690f | 2001-07-14 02:14:42 +0000 | [diff] [blame] | 35 | Python Web site, \url{http://www.python.org/}, and can be freely |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 36 | distributed. The same site also contains distributions of and |
| 37 | pointers to many free third party Python modules, programs and tools, |
| 38 | and additional documentation. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 39 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 40 | The Python interpreter is easily extended with new functions and data |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 41 | types implemented in C or \Cpp{} (or other languages callable from C). |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 42 | Python is also suitable as an extension language for customizable |
| 43 | applications. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 44 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 45 | This tutorial introduces the reader informally to the basic concepts |
| 46 | and features of the Python language and system. It helps to have a |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 47 | Python interpreter handy for hands-on experience, but all examples are |
| 48 | self-contained, so the tutorial can be read off-line as well. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 49 | |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 50 | For a description of standard objects and modules, see the |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 51 | \citetitle[../lib/lib.html]{Python Library Reference} document. The |
| 52 | \citetitle[../ref/ref.html]{Python Reference Manual} gives a more |
| 53 | formal definition of the language. To write extensions in C or |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 54 | \Cpp, read \citetitle[../ext/ext.html]{Extending and Embedding the |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 55 | Python Interpreter} and \citetitle[../api/api.html]{Python/C API |
| 56 | Reference}. There are also several books covering Python in depth. |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 57 | |
| 58 | This tutorial does not attempt to be comprehensive and cover every |
| 59 | single feature, or even every commonly used feature. Instead, it |
| 60 | introduces many of Python's most noteworthy features, and will give |
| 61 | you a good idea of the language's flavor and style. After reading it, |
| 62 | you will be able to read and write Python modules and programs, and |
| 63 | you will be ready to learn more about the various Python library |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 64 | modules described in the \citetitle[../lib/lib.html]{Python Library |
| 65 | Reference}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 66 | |
| 67 | \end{abstract} |
| 68 | |
Fred Drake | 4d4f9e7 | 1998-01-13 22:25:02 +0000 | [diff] [blame] | 69 | \tableofcontents |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 70 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 71 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 72 | \chapter{Whetting Your Appetite \label{intro}} |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 73 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 74 | If you ever wrote a large shell script, you probably know this |
| 75 | feeling: you'd love to add yet another feature, but it's already so |
| 76 | slow, and so big, and so complicated; or the feature involves a system |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 77 | call or other function that is only accessible from C \ldots Usually |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 78 | the problem at hand isn't serious enough to warrant rewriting the |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 79 | script in C; perhaps the problem requires variable-length strings or |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 80 | other data types (like sorted lists of file names) that are easy in |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 81 | the shell but lots of work to implement in C, or perhaps you're not |
| 82 | sufficiently familiar with C. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 83 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 84 | Another situation: perhaps you have to work with several C libraries, |
| 85 | and the usual C write/compile/test/re-compile cycle is too slow. You |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 86 | need to develop software more quickly. Possibly perhaps you've |
| 87 | written a program that could use an extension language, and you don't |
| 88 | want to design a language, write and debug an interpreter for it, then |
| 89 | tie it into your application. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 90 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 91 | In such cases, Python may be just the language for you. Python is |
| 92 | simple to use, but it is a real programming language, offering much |
| 93 | more structure and support for large programs than the shell has. On |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 94 | the other hand, it also offers much more error checking than C, and, |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 95 | being a \emph{very-high-level language}, it has high-level data types |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 96 | built in, such as flexible arrays and dictionaries that would cost you |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 97 | days to implement efficiently in C. Because of its more general data |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 98 | types Python is applicable to a much larger problem domain than |
| 99 | \emph{Awk} or even \emph{Perl}, yet many things are at least as easy |
| 100 | in Python as in those languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 101 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 102 | Python allows you to split up your program in modules that can be |
| 103 | reused in other Python programs. It comes with a large collection of |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 104 | standard modules that you can use as the basis of your programs --- or |
| 105 | as examples to start learning to program in Python. There are also |
| 106 | built-in modules that provide things like file I/O, system calls, |
Fred Drake | 17f690f | 2001-07-14 02:14:42 +0000 | [diff] [blame] | 107 | sockets, and even interfaces to graphical user interface toolkits like Tk. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 108 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 109 | Python is an interpreted language, which can save you considerable time |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 110 | during program development because no compilation and linking is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 111 | necessary. The interpreter can be used interactively, which makes it |
| 112 | easy to experiment with features of the language, to write throw-away |
| 113 | programs, or to test functions during bottom-up program development. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 114 | It is also a handy desk calculator. |
| 115 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 116 | Python allows writing very compact and readable programs. Programs |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 117 | written in Python are typically much shorter than equivalent C or |
| 118 | \Cpp{} programs, for several reasons: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 119 | \begin{itemize} |
| 120 | \item |
| 121 | the high-level data types allow you to express complex operations in a |
| 122 | single statement; |
| 123 | \item |
Raymond Hettinger | 57d7128 | 2003-08-30 23:21:32 +0000 | [diff] [blame] | 124 | statement grouping is done by indentation instead of beginning and ending |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 125 | brackets; |
| 126 | \item |
| 127 | no variable or argument declarations are necessary. |
| 128 | \end{itemize} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 129 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 130 | Python is \emph{extensible}: if you know how to program in C it is easy |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 131 | to add a new built-in function or module to the interpreter, either to |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 132 | perform critical operations at maximum speed, or to link Python |
| 133 | programs to libraries that may only be available in binary form (such |
| 134 | as a vendor-specific graphics library). Once you are really hooked, |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 135 | you can link the Python interpreter into an application written in C |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 136 | and use it as an extension or command language for that application. |
| 137 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 138 | By the way, the language is named after the BBC show ``Monty Python's |
| 139 | Flying Circus'' and has nothing to do with nasty reptiles. Making |
| 140 | references to Monty Python skits in documentation is not only allowed, |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 141 | it is encouraged! |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 142 | |
Fred Drake | 2664cbb | 2003-06-20 14:27:27 +0000 | [diff] [blame] | 143 | %\section{Where From Here \label{where}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 144 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 145 | Now that you are all excited about Python, you'll want to examine it |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 146 | in some more detail. Since the best way to learn a language is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 147 | using it, you are invited here to do so. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 148 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 149 | In the next chapter, the mechanics of using the interpreter are |
| 150 | explained. This is rather mundane information, but essential for |
| 151 | trying out the examples shown later. |
| 152 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 153 | The rest of the tutorial introduces various features of the Python |
Fred Drake | f64f8a0 | 1999-06-10 15:30:21 +0000 | [diff] [blame] | 154 | language and system through examples, beginning with simple |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 155 | expressions, statements and data types, through functions and modules, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 156 | and finally touching upon advanced concepts like exceptions |
| 157 | and user-defined classes. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 158 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 159 | \chapter{Using the Python Interpreter \label{using}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 160 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 161 | \section{Invoking the Interpreter \label{invoking}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 162 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 163 | The Python interpreter is usually installed as |
| 164 | \file{/usr/local/bin/python} on those machines where it is available; |
| 165 | putting \file{/usr/local/bin} in your \UNIX{} shell's search path |
| 166 | makes it possible to start it by typing the command |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 167 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 168 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 169 | python |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 170 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 171 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 172 | to the shell. Since the choice of the directory where the interpreter |
| 173 | lives is an installation option, other places are possible; check with |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 174 | your local Python guru or system administrator. (E.g., |
| 175 | \file{/usr/local/python} is a popular alternative location.) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 176 | |
Fred Drake | 5d6e402 | 2001-04-11 04:38:34 +0000 | [diff] [blame] | 177 | Typing an end-of-file character (\kbd{Control-D} on \UNIX, |
Martin v. Löwis | 36a4d8c | 2002-10-10 18:24:54 +0000 | [diff] [blame] | 178 | \kbd{Control-Z} on Windows) at the primary prompt causes the |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 179 | interpreter to exit with a zero exit status. If that doesn't work, |
| 180 | you can exit the interpreter by typing the following commands: |
| 181 | \samp{import sys; sys.exit()}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 182 | |
| 183 | The interpreter's line-editing features usually aren't very |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 184 | sophisticated. On \UNIX, whoever installed the interpreter may have |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 185 | enabled support for the GNU readline library, which adds more |
| 186 | elaborate interactive editing and history features. Perhaps the |
| 187 | quickest check to see whether command line editing is supported is |
| 188 | typing Control-P to the first Python prompt you get. If it beeps, you |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 189 | have command line editing; see Appendix \ref{interacting} for an |
| 190 | introduction to the keys. If nothing appears to happen, or if |
| 191 | \code{\^P} is echoed, command line editing isn't available; you'll |
| 192 | only be able to use backspace to remove characters from the current |
| 193 | line. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 194 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 195 | The interpreter operates somewhat like the \UNIX{} shell: when called |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 196 | with standard input connected to a tty device, it reads and executes |
| 197 | commands interactively; when called with a file name argument or with |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 198 | a file as standard input, it reads and executes a \emph{script} from |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 199 | that file. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 200 | |
Raymond Hettinger | c2a5cb2 | 2003-08-23 03:49:08 +0000 | [diff] [blame] | 201 | A second way of starting the interpreter is |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 202 | \samp{\program{python} \programopt{-c} \var{command} [arg] ...}, which |
| 203 | executes the statement(s) in \var{command}, analogous to the shell's |
| 204 | \programopt{-c} option. Since Python statements often contain spaces |
| 205 | or other characters that are special to the shell, it is best to quote |
| 206 | \var{command} in its entirety with double quotes. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 207 | |
Raymond Hettinger | db29e0f | 2004-10-07 06:46:25 +0000 | [diff] [blame^] | 208 | Some Python modules are also useful as scripts. These can be invoked using |
| 209 | \samp{\program{python} \programopt{-m} \var{module} [arg] ...}, which |
| 210 | executes the source file for \var{module} as if you had spelled out its |
| 211 | full name on the command line. |
| 212 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 213 | Note that there is a difference between \samp{python file} and |
| 214 | \samp{python <file}. In the latter case, input requests from the |
Fred Drake | 6bab183 | 2003-05-20 15:28:58 +0000 | [diff] [blame] | 215 | program, such as calls to \function{input()} and \function{raw_input()}, are |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 216 | satisfied from \emph{file}. Since this file has already been read |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 217 | until the end by the parser before the program starts executing, the |
Fred Drake | 5d6e402 | 2001-04-11 04:38:34 +0000 | [diff] [blame] | 218 | program will encounter end-of-file immediately. In the former case |
| 219 | (which is usually what you want) they are satisfied from whatever file |
| 220 | or device is connected to standard input of the Python interpreter. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 221 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 222 | When a script file is used, it is sometimes useful to be able to run |
| 223 | the script and enter interactive mode afterwards. This can be done by |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 224 | passing \programopt{-i} before the script. (This does not work if the |
| 225 | script is read from standard input, for the same reason as explained |
| 226 | in the previous paragraph.) |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 227 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 228 | \subsection{Argument Passing \label{argPassing}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 229 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 230 | When known to the interpreter, the script name and additional |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 231 | arguments thereafter are passed to the script in the variable |
| 232 | \code{sys.argv}, which is a list of strings. Its length is at least |
| 233 | one; when no script and no arguments are given, \code{sys.argv[0]} is |
| 234 | an empty string. When the script name is given as \code{'-'} (meaning |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 235 | standard input), \code{sys.argv[0]} is set to \code{'-'}. When |
| 236 | \programopt{-c} \var{command} is used, \code{sys.argv[0]} is set to |
Raymond Hettinger | db29e0f | 2004-10-07 06:46:25 +0000 | [diff] [blame^] | 237 | \code{'-c'}. When \programopt{-m} \var{module} is used, \code{sys.argv[0]} |
| 238 | is set to the full name of the located module. Options found after |
| 239 | \programopt{-c} \var{command} or \programopt{-m} \var{module} are not consumed |
| 240 | by the Python interpreter's option processing but left in \code{sys.argv} for |
| 241 | the command or module to handle. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 242 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 243 | \subsection{Interactive Mode \label{interactive}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 244 | |
Guido van Rossum | dd01080 | 1991-06-07 14:31:11 +0000 | [diff] [blame] | 245 | When commands are read from a tty, the interpreter is said to be in |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 246 | \emph{interactive mode}. In this mode it prompts for the next command |
| 247 | with the \emph{primary prompt}, usually three greater-than signs |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 248 | (\samp{>\code{>}>~}); for continuation lines it prompts with the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 249 | \emph{secondary prompt}, by default three dots (\samp{...~}). |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 250 | The interpreter prints a welcome message stating its version number |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 251 | and a copyright notice before printing the first prompt: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 252 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 253 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 254 | python |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 255 | Python 1.5.2b2 (#1, Feb 28 1999, 00:02:06) [GCC 2.8.1] on sunos5 |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 256 | Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 257 | >>> |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 258 | \end{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 259 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 260 | Continuation lines are needed when entering a multi-line construct. |
| 261 | As an example, take a look at this \keyword{if} statement: |
| 262 | |
| 263 | \begin{verbatim} |
| 264 | >>> the_world_is_flat = 1 |
| 265 | >>> if the_world_is_flat: |
| 266 | ... print "Be careful not to fall off!" |
| 267 | ... |
| 268 | Be careful not to fall off! |
| 269 | \end{verbatim} |
| 270 | |
| 271 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 272 | \section{The Interpreter and Its Environment \label{interp}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 273 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 274 | \subsection{Error Handling \label{error}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 275 | |
| 276 | When an error occurs, the interpreter prints an error |
| 277 | message and a stack trace. In interactive mode, it then returns to |
| 278 | the primary prompt; when input came from a file, it exits with a |
| 279 | nonzero exit status after printing |
Fred Drake | 6bab183 | 2003-05-20 15:28:58 +0000 | [diff] [blame] | 280 | the stack trace. (Exceptions handled by an \keyword{except} clause in a |
| 281 | \keyword{try} statement are not errors in this context.) Some errors are |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 282 | unconditionally fatal and cause an exit with a nonzero exit; this |
| 283 | applies to internal inconsistencies and some cases of running out of |
| 284 | memory. All error messages are written to the standard error stream; |
| 285 | normal output from the executed commands is written to standard |
| 286 | output. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 287 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 288 | Typing the interrupt character (usually Control-C or DEL) to the |
| 289 | primary or secondary prompt cancels the input and returns to the |
Fred Drake | 93aa0f2 | 1999-04-05 21:39:17 +0000 | [diff] [blame] | 290 | primary prompt.\footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 291 | A problem with the GNU Readline package may prevent this. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 292 | } |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 293 | Typing an interrupt while a command is executing raises the |
Fred Drake | 6bab183 | 2003-05-20 15:28:58 +0000 | [diff] [blame] | 294 | \exception{KeyboardInterrupt} exception, which may be handled by a |
| 295 | \keyword{try} statement. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 296 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 297 | \subsection{Executable Python Scripts \label{scripts}} |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 298 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 299 | On BSD'ish \UNIX{} systems, Python scripts can be made directly |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 300 | executable, like shell scripts, by putting the line |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 301 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 302 | \begin{verbatim} |
Fred Drake | 9e63faa | 1997-10-15 14:37:24 +0000 | [diff] [blame] | 303 | #! /usr/bin/env python |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 304 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 305 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 306 | (assuming that the interpreter is on the user's \envvar{PATH}) at the |
| 307 | beginning of the script and giving the file an executable mode. The |
Fred Drake | dfda8d7 | 2003-07-07 21:00:29 +0000 | [diff] [blame] | 308 | \samp{\#!} must be the first two characters of the file. On some |
| 309 | platforms, this first line must end with a \UNIX-style line ending |
| 310 | (\character{\e n}), not a Mac OS (\character{\e r}) or Windows |
| 311 | (\character{\e r\e n}) line ending. Note that |
Fred Drake | bdadf0f | 1999-04-29 13:20:25 +0000 | [diff] [blame] | 312 | the hash, or pound, character, \character{\#}, is used to start a |
| 313 | comment in Python. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 314 | |
Fred Drake | dfda8d7 | 2003-07-07 21:00:29 +0000 | [diff] [blame] | 315 | The script can be given a executable mode, or permission, using the |
| 316 | \program{chmod} command: |
| 317 | |
| 318 | \begin{verbatim} |
| 319 | $ chmod +x myscript.py |
| 320 | \end{verbatim} % $ <-- bow to font-lock |
| 321 | |
| 322 | |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 323 | \subsection{Source Code Encoding} |
| 324 | |
Fred Drake | dfda8d7 | 2003-07-07 21:00:29 +0000 | [diff] [blame] | 325 | It is possible to use encodings different than \ASCII{} in Python source |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 326 | files. The best way to do it is to put one more special comment line |
Skip Montanaro | 32a5e87 | 2003-06-29 16:01:51 +0000 | [diff] [blame] | 327 | right after the \code{\#!} line to define the source file encoding: |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 328 | |
| 329 | \begin{verbatim} |
| 330 | # -*- coding: iso-8859-1 -*- |
| 331 | \end{verbatim} |
| 332 | |
Skip Montanaro | 32a5e87 | 2003-06-29 16:01:51 +0000 | [diff] [blame] | 333 | With that declaration, all characters in the source file will be treated as |
| 334 | {}\code{iso-8859-1}, and it will be |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 335 | possible to directly write Unicode string literals in the selected |
Skip Montanaro | 32a5e87 | 2003-06-29 16:01:51 +0000 | [diff] [blame] | 336 | encoding. The list of possible encodings can be found in the |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 337 | \citetitle[../lib/lib.html]{Python Library Reference}, in the section |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 338 | on \ulink{\module{codecs}}{../lib/module-codecs.html}. |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 339 | |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 340 | If your editor supports saving files as \code{UTF-8} with a UTF-8 |
| 341 | \emph{byte order mark} (aka BOM), you can use that instead of an |
Skip Montanaro | 32a5e87 | 2003-06-29 16:01:51 +0000 | [diff] [blame] | 342 | encoding declaration. IDLE supports this capability if |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 343 | \code{Options/General/Default Source Encoding/UTF-8} is set. Notice |
| 344 | that this signature is not understood in older Python releases (2.2 |
| 345 | and earlier), and also not understood by the operating system for |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 346 | \code{\#!} files. |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 347 | |
Skip Montanaro | 32a5e87 | 2003-06-29 16:01:51 +0000 | [diff] [blame] | 348 | By using UTF-8 (either through the signature or an encoding |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 349 | declaration), characters of most languages in the world can be used |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 350 | simultaneously in string literals and comments. Using non-\ASCII |
Martin v. Löwis | 7928f38 | 2003-06-28 08:11:55 +0000 | [diff] [blame] | 351 | characters in identifiers is not supported. To display all these |
| 352 | characters properly, your editor must recognize that the file is |
| 353 | UTF-8, and it must use a font that supports all the characters in the |
| 354 | file. |
| 355 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 356 | \subsection{The Interactive Startup File \label{startup}} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 357 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 358 | % XXX This should probably be dumped in an appendix, since most people |
| 359 | % don't use Python interactively in non-trivial ways. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 360 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 361 | When you use Python interactively, it is frequently handy to have some |
| 362 | standard commands executed every time the interpreter is started. You |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 363 | can do this by setting an environment variable named |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 364 | \envvar{PYTHONSTARTUP} to the name of a file containing your start-up |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 365 | commands. This is similar to the \file{.profile} feature of the |
| 366 | \UNIX{} shells. |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 367 | |
| 368 | This file is only read in interactive sessions, not when Python reads |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 369 | commands from a script, and not when \file{/dev/tty} is given as the |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 370 | explicit source of commands (which otherwise behaves like an |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 371 | interactive session). It is executed in the same namespace where |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 372 | interactive commands are executed, so that objects that it defines or |
| 373 | imports can be used without qualification in the interactive session. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 374 | You can also change the prompts \code{sys.ps1} and \code{sys.ps2} in |
Guido van Rossum | 7b3c8a1 | 1992-09-08 09:20:13 +0000 | [diff] [blame] | 375 | this file. |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 376 | |
| 377 | If you want to read an additional start-up file from the current |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 378 | directory, you can program this in the global start-up file using code |
| 379 | like \samp{if os.path.isfile('.pythonrc.py'): |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 380 | execfile('.pythonrc.py')}. If you want to use the startup file in a |
| 381 | script, you must do this explicitly in the script: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 382 | |
| 383 | \begin{verbatim} |
| 384 | import os |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 385 | filename = os.environ.get('PYTHONSTARTUP') |
| 386 | if filename and os.path.isfile(filename): |
| 387 | execfile(filename) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 388 | \end{verbatim} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 389 | |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 390 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 391 | \chapter{An Informal Introduction to Python \label{informal}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 392 | |
| 393 | In the following examples, input and output are distinguished by the |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 394 | presence or absence of prompts (\samp{>\code{>}>~} and \samp{...~}): to repeat |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 395 | the example, you must type everything after the prompt, when the |
| 396 | prompt appears; lines that do not begin with a prompt are output from |
Fred Drake | bdadf0f | 1999-04-29 13:20:25 +0000 | [diff] [blame] | 397 | the interpreter. % |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 398 | %\footnote{ |
| 399 | % I'd prefer to use different fonts to distinguish input |
| 400 | % from output, but the amount of LaTeX hacking that would require |
| 401 | % is currently beyond my ability. |
| 402 | %} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 403 | Note that a secondary prompt on a line by itself in an example means |
| 404 | you must type a blank line; this is used to end a multi-line command. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 405 | |
Fred Drake | bdadf0f | 1999-04-29 13:20:25 +0000 | [diff] [blame] | 406 | Many of the examples in this manual, even those entered at the |
| 407 | interactive prompt, include comments. Comments in Python start with |
| 408 | the hash character, \character{\#}, and extend to the end of the |
| 409 | physical line. A comment may appear at the start of a line or |
| 410 | following whitespace or code, but not within a string literal. A hash |
| 411 | character within a string literal is just a hash character. |
| 412 | |
| 413 | Some examples: |
| 414 | |
| 415 | \begin{verbatim} |
| 416 | # this is the first comment |
| 417 | SPAM = 1 # and this is the second comment |
| 418 | # ... and now a third! |
| 419 | STRING = "# This is not a comment." |
| 420 | \end{verbatim} |
| 421 | |
| 422 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 423 | \section{Using Python as a Calculator \label{calculator}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 424 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 425 | Let's try some simple Python commands. Start the interpreter and wait |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 426 | for the primary prompt, \samp{>\code{>}>~}. (It shouldn't take long.) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 427 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 428 | \subsection{Numbers \label{numbers}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 429 | |
| 430 | The interpreter acts as a simple calculator: you can type an |
| 431 | expression at it and it will write the value. Expression syntax is |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 432 | straightforward: the operators \code{+}, \code{-}, \code{*} and |
| 433 | \code{/} work just like in most other languages (for example, Pascal |
| 434 | or C); parentheses can be used for grouping. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 435 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 436 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 437 | >>> 2+2 |
| 438 | 4 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 439 | >>> # This is a comment |
| 440 | ... 2+2 |
| 441 | 4 |
| 442 | >>> 2+2 # and a comment on the same line as code |
| 443 | 4 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 444 | >>> (50-5*6)/4 |
| 445 | 5 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 446 | >>> # Integer division returns the floor: |
| 447 | ... 7/3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 448 | 2 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 449 | >>> 7/-3 |
| 450 | -3 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 451 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 452 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 453 | Like in C, the equal sign (\character{=}) is used to assign a value to a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 454 | variable. The value of an assignment is not written: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 455 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 456 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 457 | >>> width = 20 |
| 458 | >>> height = 5*9 |
| 459 | >>> width * height |
| 460 | 900 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 461 | \end{verbatim} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 462 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 463 | A value can be assigned to several variables simultaneously: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 464 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 465 | \begin{verbatim} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 466 | >>> x = y = z = 0 # Zero x, y and z |
| 467 | >>> x |
| 468 | 0 |
| 469 | >>> y |
| 470 | 0 |
| 471 | >>> z |
| 472 | 0 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 473 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 474 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 475 | There is full support for floating point; operators with mixed type |
| 476 | operands convert the integer operand to floating point: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 477 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 478 | \begin{verbatim} |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 479 | >>> 3 * 3.75 / 1.5 |
| 480 | 7.5 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 481 | >>> 7.0 / 2 |
| 482 | 3.5 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 483 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 484 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 485 | Complex numbers are also supported; imaginary numbers are written with |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 486 | a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero |
| 487 | real component are written as \samp{(\var{real}+\var{imag}j)}, or can |
| 488 | be created with the \samp{complex(\var{real}, \var{imag})} function. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 489 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 490 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 491 | >>> 1j * 1J |
| 492 | (-1+0j) |
| 493 | >>> 1j * complex(0,1) |
| 494 | (-1+0j) |
| 495 | >>> 3+1j*3 |
| 496 | (3+3j) |
| 497 | >>> (3+1j)*3 |
| 498 | (9+3j) |
| 499 | >>> (1+2j)/(1+1j) |
| 500 | (1.5+0.5j) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 501 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 502 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 503 | Complex numbers are always represented as two floating point numbers, |
| 504 | the real and imaginary part. To extract these parts from a complex |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 505 | number \var{z}, use \code{\var{z}.real} and \code{\var{z}.imag}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 506 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 507 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 508 | >>> a=1.5+0.5j |
| 509 | >>> a.real |
| 510 | 1.5 |
| 511 | >>> a.imag |
| 512 | 0.5 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 513 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 514 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 515 | The conversion functions to floating point and integer |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 516 | (\function{float()}, \function{int()} and \function{long()}) don't |
| 517 | work for complex numbers --- there is no one correct way to convert a |
| 518 | complex number to a real number. Use \code{abs(\var{z})} to get its |
| 519 | magnitude (as a float) or \code{z.real} to get its real part. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 520 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 521 | \begin{verbatim} |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 522 | >>> a=3.0+4.0j |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 523 | >>> float(a) |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 524 | Traceback (most recent call last): |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 525 | File "<stdin>", line 1, in ? |
Raymond Hettinger | 57d7128 | 2003-08-30 23:21:32 +0000 | [diff] [blame] | 526 | TypeError: can't convert complex to float; use abs(z) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 527 | >>> a.real |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 528 | 3.0 |
| 529 | >>> a.imag |
| 530 | 4.0 |
| 531 | >>> abs(a) # sqrt(a.real**2 + a.imag**2) |
| 532 | 5.0 |
| 533 | >>> |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 534 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 535 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 536 | In interactive mode, the last printed expression is assigned to the |
| 537 | variable \code{_}. This means that when you are using Python as a |
| 538 | desk calculator, it is somewhat easier to continue calculations, for |
| 539 | example: |
| 540 | |
| 541 | \begin{verbatim} |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 542 | >>> tax = 12.5 / 100 |
| 543 | >>> price = 100.50 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 544 | >>> price * tax |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 545 | 12.5625 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 546 | >>> price + _ |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 547 | 113.0625 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 548 | >>> round(_, 2) |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 549 | 113.06 |
| 550 | >>> |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 551 | \end{verbatim} |
| 552 | |
| 553 | This variable should be treated as read-only by the user. Don't |
| 554 | explicitly assign a value to it --- you would create an independent |
| 555 | local variable with the same name masking the built-in variable with |
| 556 | its magic behavior. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 557 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 558 | \subsection{Strings \label{strings}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 559 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 560 | Besides numbers, Python can also manipulate strings, which can be |
| 561 | expressed in several ways. They can be enclosed in single quotes or |
| 562 | double quotes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 563 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 564 | \begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 565 | >>> 'spam eggs' |
| 566 | 'spam eggs' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 567 | >>> 'doesn\'t' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 568 | "doesn't" |
| 569 | >>> "doesn't" |
| 570 | "doesn't" |
| 571 | >>> '"Yes," he said.' |
| 572 | '"Yes," he said.' |
| 573 | >>> "\"Yes,\" he said." |
| 574 | '"Yes," he said.' |
| 575 | >>> '"Isn\'t," she said.' |
| 576 | '"Isn\'t," she said.' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 577 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 578 | |
Fred Drake | ba5c41d | 2001-09-06 18:41:15 +0000 | [diff] [blame] | 579 | String literals can span multiple lines in several ways. Continuation |
| 580 | lines can be used, with a backslash as the last character on the line |
| 581 | indicating that the next line is a logical continuation of the line: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 582 | |
| 583 | \begin{verbatim} |
| 584 | hello = "This is a rather long string containing\n\ |
| 585 | several lines of text just as you would do in C.\n\ |
| 586 | Note that whitespace at the beginning of the line is\ |
Fred Drake | ba5c41d | 2001-09-06 18:41:15 +0000 | [diff] [blame] | 587 | significant." |
| 588 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 589 | print hello |
| 590 | \end{verbatim} |
| 591 | |
Fred Drake | ba5c41d | 2001-09-06 18:41:15 +0000 | [diff] [blame] | 592 | Note that newlines would still need to be embedded in the string using |
| 593 | \code{\e n}; the newline following the trailing backslash is |
| 594 | discarded. This example would print the following: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 595 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 596 | \begin{verbatim} |
| 597 | This is a rather long string containing |
| 598 | several lines of text just as you would do in C. |
| 599 | Note that whitespace at the beginning of the line is significant. |
| 600 | \end{verbatim} |
| 601 | |
Fred Drake | ba5c41d | 2001-09-06 18:41:15 +0000 | [diff] [blame] | 602 | If we make the string literal a ``raw'' string, however, the |
| 603 | \code{\e n} sequences are not converted to newlines, but the backslash |
| 604 | at the end of the line, and the newline character in the source, are |
| 605 | both included in the string as data. Thus, the example: |
| 606 | |
| 607 | \begin{verbatim} |
| 608 | hello = r"This is a rather long string containing\n\ |
| 609 | several lines of text much as you would do in C." |
| 610 | |
| 611 | print hello |
| 612 | \end{verbatim} |
| 613 | |
| 614 | would print: |
| 615 | |
| 616 | \begin{verbatim} |
| 617 | This is a rather long string containing\n\ |
| 618 | several lines of text much as you would do in C. |
| 619 | \end{verbatim} |
| 620 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 621 | Or, strings can be surrounded in a pair of matching triple-quotes: |
Fred Drake | ba5c41d | 2001-09-06 18:41:15 +0000 | [diff] [blame] | 622 | \code{"""} or \code{'\code{'}'}. End of lines do not need to be escaped |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 623 | when using triple-quotes, but they will be included in the string. |
| 624 | |
| 625 | \begin{verbatim} |
| 626 | print """ |
| 627 | Usage: thingy [OPTIONS] |
| 628 | -h Display this usage message |
| 629 | -H hostname Hostname to connect to |
| 630 | """ |
| 631 | \end{verbatim} |
| 632 | |
| 633 | produces the following output: |
| 634 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 635 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 636 | Usage: thingy [OPTIONS] |
| 637 | -h Display this usage message |
| 638 | -H hostname Hostname to connect to |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 639 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 640 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 641 | The interpreter prints the result of string operations in the same way |
| 642 | as they are typed for input: inside quotes, and with quotes and other |
| 643 | funny characters escaped by backslashes, to show the precise |
| 644 | value. The string is enclosed in double quotes if the string contains |
| 645 | a single quote and no double quotes, else it's enclosed in single |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 646 | quotes. (The \keyword{print} statement, described later, can be used |
| 647 | to write strings without quotes or escapes.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 648 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 649 | Strings can be concatenated (glued together) with the |
| 650 | \code{+} operator, and repeated with \code{*}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 651 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 652 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 653 | >>> word = 'Help' + 'A' |
| 654 | >>> word |
| 655 | 'HelpA' |
| 656 | >>> '<' + word*5 + '>' |
| 657 | '<HelpAHelpAHelpAHelpAHelpA>' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 658 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 659 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 660 | Two string literals next to each other are automatically concatenated; |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 661 | the first line above could also have been written \samp{word = 'Help' |
Guido van Rossum | e51aa5b | 1999-01-06 23:14:14 +0000 | [diff] [blame] | 662 | 'A'}; this only works with two literals, not with arbitrary string |
| 663 | expressions: |
| 664 | |
| 665 | \begin{verbatim} |
| 666 | >>> 'str' 'ing' # <- This is ok |
| 667 | 'string' |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 668 | >>> 'str'.strip() + 'ing' # <- This is ok |
Guido van Rossum | e51aa5b | 1999-01-06 23:14:14 +0000 | [diff] [blame] | 669 | 'string' |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 670 | >>> 'str'.strip() 'ing' # <- This is invalid |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 671 | File "<stdin>", line 1, in ? |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 672 | 'str'.strip() 'ing' |
| 673 | ^ |
Guido van Rossum | e51aa5b | 1999-01-06 23:14:14 +0000 | [diff] [blame] | 674 | SyntaxError: invalid syntax |
| 675 | \end{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 676 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 677 | Strings can be subscripted (indexed); like in C, the first character |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 678 | of a string has subscript (index) 0. There is no separate character |
| 679 | type; a character is simply a string of size one. Like in Icon, |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 680 | substrings can be specified with the \emph{slice notation}: two indices |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 681 | separated by a colon. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 682 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 683 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 684 | >>> word[4] |
| 685 | 'A' |
| 686 | >>> word[0:2] |
| 687 | 'He' |
| 688 | >>> word[2:4] |
| 689 | 'lp' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 690 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 691 | |
Raymond Hettinger | 60de2e8 | 2003-03-12 04:46:52 +0000 | [diff] [blame] | 692 | Slice indices have useful defaults; an omitted first index defaults to |
| 693 | zero, an omitted second index defaults to the size of the string being |
| 694 | sliced. |
| 695 | |
| 696 | \begin{verbatim} |
| 697 | >>> word[:2] # The first two characters |
| 698 | 'He' |
Fred Drake | 20938f5 | 2004-07-21 17:18:19 +0000 | [diff] [blame] | 699 | >>> word[2:] # Everything except the first two characters |
Raymond Hettinger | 60de2e8 | 2003-03-12 04:46:52 +0000 | [diff] [blame] | 700 | 'lpA' |
| 701 | \end{verbatim} |
| 702 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 703 | Unlike a C string, Python strings cannot be changed. Assigning to an |
| 704 | indexed position in the string results in an error: |
| 705 | |
| 706 | \begin{verbatim} |
| 707 | >>> word[0] = 'x' |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 708 | Traceback (most recent call last): |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 709 | File "<stdin>", line 1, in ? |
| 710 | TypeError: object doesn't support item assignment |
Fred Drake | 67fdaa4 | 2001-03-06 07:19:34 +0000 | [diff] [blame] | 711 | >>> word[:1] = 'Splat' |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 712 | Traceback (most recent call last): |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 713 | File "<stdin>", line 1, in ? |
| 714 | TypeError: object doesn't support slice assignment |
| 715 | \end{verbatim} |
| 716 | |
| 717 | However, creating a new string with the combined content is easy and |
| 718 | efficient: |
| 719 | |
| 720 | \begin{verbatim} |
| 721 | >>> 'x' + word[1:] |
| 722 | 'xelpA' |
Fred Drake | 67fdaa4 | 2001-03-06 07:19:34 +0000 | [diff] [blame] | 723 | >>> 'Splat' + word[4] |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 724 | 'SplatA' |
| 725 | \end{verbatim} |
| 726 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 727 | Here's a useful invariant of slice operations: |
| 728 | \code{s[:i] + s[i:]} equals \code{s}. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 729 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 730 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 731 | >>> word[:2] + word[2:] |
| 732 | 'HelpA' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 733 | >>> word[:3] + word[3:] |
| 734 | 'HelpA' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 735 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 736 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 737 | Degenerate slice indices are handled gracefully: an index that is too |
| 738 | large is replaced by the string size, an upper bound smaller than the |
| 739 | lower bound returns an empty string. |
| 740 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 741 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 742 | >>> word[1:100] |
| 743 | 'elpA' |
| 744 | >>> word[10:] |
| 745 | '' |
| 746 | >>> word[2:1] |
| 747 | '' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 748 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 749 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 750 | Indices may be negative numbers, to start counting from the right. |
| 751 | For example: |
| 752 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 753 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 754 | >>> word[-1] # The last character |
| 755 | 'A' |
| 756 | >>> word[-2] # The last-but-one character |
| 757 | 'p' |
| 758 | >>> word[-2:] # The last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 759 | 'pA' |
Fred Drake | 4ab0e9e | 2004-07-21 17:36:47 +0000 | [diff] [blame] | 760 | >>> word[:-2] # Everything except the last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 761 | 'Hel' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 762 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 763 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 764 | But note that -0 is really the same as 0, so it does not count from |
| 765 | the right! |
| 766 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 767 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 768 | >>> word[-0] # (since -0 equals 0) |
| 769 | 'H' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 770 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 771 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 772 | Out-of-range negative slice indices are truncated, but don't try this |
| 773 | for single-element (non-slice) indices: |
| 774 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 775 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 776 | >>> word[-100:] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 777 | 'HelpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 778 | >>> word[-10] # error |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 779 | Traceback (most recent call last): |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 780 | File "<stdin>", line 1, in ? |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 781 | IndexError: string index out of range |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 782 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 783 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 784 | The best way to remember how slices work is to think of the indices as |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 785 | pointing \emph{between} characters, with the left edge of the first |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 786 | character numbered 0. Then the right edge of the last character of a |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 787 | string of \var{n} characters has index \var{n}, for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 788 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 789 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 790 | +---+---+---+---+---+ |
| 791 | | H | e | l | p | A | |
| 792 | +---+---+---+---+---+ |
| 793 | 0 1 2 3 4 5 |
| 794 | -5 -4 -3 -2 -1 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 795 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 796 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 797 | The first row of numbers gives the position of the indices 0...5 in |
| 798 | the string; the second row gives the corresponding negative indices. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 799 | The slice from \var{i} to \var{j} consists of all characters between |
| 800 | the edges labeled \var{i} and \var{j}, respectively. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 801 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 802 | For non-negative indices, the length of a slice is the difference of |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 803 | the indices, if both are within bounds. For example, the length of |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 804 | \code{word[1:3]} is 2. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 805 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 806 | The built-in function \function{len()} returns the length of a string: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 807 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 808 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 809 | >>> s = 'supercalifragilisticexpialidocious' |
| 810 | >>> len(s) |
| 811 | 34 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 812 | \end{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 813 | |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 814 | |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 815 | \begin{seealso} |
| 816 | \seetitle[../lib/typesseq.html]{Sequence Types}% |
| 817 | {Strings, and the Unicode strings described in the next |
| 818 | section, are examples of \emph{sequence types}, and |
| 819 | support the common operations supported by such types.} |
| 820 | \seetitle[../lib/string-methods.html]{String Methods}% |
| 821 | {Both strings and Unicode strings support a large number of |
| 822 | methods for basic transformations and searching.} |
| 823 | \seetitle[../lib/typesseq-strings.html]{String Formatting Operations}% |
| 824 | {The formatting operations invoked when strings and Unicode |
| 825 | strings are the left operand of the \code{\%} operator are |
| 826 | described in more detail here.} |
| 827 | \end{seealso} |
| 828 | |
| 829 | |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 830 | \subsection{Unicode Strings \label{unicodeStrings}} |
| 831 | \sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com} |
| 832 | |
Fred Drake | 30f76ff | 2000-06-30 16:06:19 +0000 | [diff] [blame] | 833 | Starting with Python 2.0 a new data type for storing text data is |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 834 | available to the programmer: the Unicode object. It can be used to |
Fred Drake | 17f690f | 2001-07-14 02:14:42 +0000 | [diff] [blame] | 835 | store and manipulate Unicode data (see \url{http://www.unicode.org/}) |
Thomas Wouters | f9b526d | 2000-07-16 19:05:38 +0000 | [diff] [blame] | 836 | and integrates well with the existing string objects providing |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 837 | auto-conversions where necessary. |
| 838 | |
| 839 | Unicode has the advantage of providing one ordinal for every character |
| 840 | in every script used in modern and ancient texts. Previously, there |
| 841 | were only 256 possible ordinals for script characters and texts were |
| 842 | typically bound to a code page which mapped the ordinals to script |
| 843 | characters. This lead to very much confusion especially with respect |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 844 | to internationalization (usually written as \samp{i18n} --- |
| 845 | \character{i} + 18 characters + \character{n}) of software. Unicode |
| 846 | solves these problems by defining one code page for all scripts. |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 847 | |
| 848 | Creating Unicode strings in Python is just as simple as creating |
| 849 | normal strings: |
| 850 | |
| 851 | \begin{verbatim} |
| 852 | >>> u'Hello World !' |
| 853 | u'Hello World !' |
| 854 | \end{verbatim} |
| 855 | |
| 856 | The small \character{u} in front of the quote indicates that an |
| 857 | Unicode string is supposed to be created. If you want to include |
| 858 | special characters in the string, you can do so by using the Python |
| 859 | \emph{Unicode-Escape} encoding. The following example shows how: |
| 860 | |
| 861 | \begin{verbatim} |
Tim Peters | 657ebef | 2000-11-29 05:51:59 +0000 | [diff] [blame] | 862 | >>> u'Hello\u0020World !' |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 863 | u'Hello World !' |
| 864 | \end{verbatim} |
| 865 | |
Fred Drake | 4a6f1df | 2000-11-29 06:03:45 +0000 | [diff] [blame] | 866 | The escape sequence \code{\e u0020} indicates to insert the Unicode |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 867 | character with the ordinal value 0x0020 (the space character) at the |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 868 | given position. |
| 869 | |
| 870 | Other characters are interpreted by using their respective ordinal |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 871 | values directly as Unicode ordinals. If you have literal strings |
| 872 | in the standard Latin-1 encoding that is used in many Western countries, |
| 873 | you will find it convenient that the lower 256 characters |
| 874 | of Unicode are the same as the 256 characters of Latin-1. |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 875 | |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 876 | For experts, there is also a raw mode just like the one for normal |
| 877 | strings. You have to prefix the opening quote with 'ur' to have |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 878 | Python use the \emph{Raw-Unicode-Escape} encoding. It will only apply |
Fred Drake | 4a6f1df | 2000-11-29 06:03:45 +0000 | [diff] [blame] | 879 | the above \code{\e uXXXX} conversion if there is an uneven number of |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 880 | backslashes in front of the small 'u'. |
| 881 | |
| 882 | \begin{verbatim} |
| 883 | >>> ur'Hello\u0020World !' |
| 884 | u'Hello World !' |
| 885 | >>> ur'Hello\\u0020World !' |
| 886 | u'Hello\\\\u0020World !' |
| 887 | \end{verbatim} |
| 888 | |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 889 | The raw mode is most useful when you have to enter lots of |
| 890 | backslashes, as can be necessary in regular expressions. |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 891 | |
| 892 | Apart from these standard encodings, Python provides a whole set of |
Thomas Wouters | f9b526d | 2000-07-16 19:05:38 +0000 | [diff] [blame] | 893 | other ways of creating Unicode strings on the basis of a known |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 894 | encoding. |
| 895 | |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 896 | The built-in function \function{unicode()}\bifuncindex{unicode} provides |
| 897 | access to all registered Unicode codecs (COders and DECoders). Some of |
| 898 | the more well known encodings which these codecs can convert are |
| 899 | \emph{Latin-1}, \emph{ASCII}, \emph{UTF-8}, and \emph{UTF-16}. |
| 900 | The latter two are variable-length encodings that store each Unicode |
| 901 | character in one or more bytes. The default encoding is |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 902 | normally set to \ASCII, which passes through characters in the range |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 903 | 0 to 127 and rejects any other characters with an error. |
| 904 | When a Unicode string is printed, written to a file, or converted |
| 905 | with \function{str()}, conversion takes place using this default encoding. |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 906 | |
| 907 | \begin{verbatim} |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 908 | >>> u"abc" |
| 909 | u'abc' |
| 910 | >>> str(u"abc") |
| 911 | 'abc' |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 912 | >>> u"äöü" |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 913 | u'\xe4\xf6\xfc' |
| 914 | >>> str(u"äöü") |
| 915 | Traceback (most recent call last): |
| 916 | File "<stdin>", line 1, in ? |
Raymond Hettinger | a2f84ce | 2003-05-07 17:11:15 +0000 | [diff] [blame] | 917 | UnicodeEncodeError: 'ascii' codec can't encode characters in position 0-2: ordinal not in range(128) |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 918 | \end{verbatim} |
| 919 | |
| 920 | To convert a Unicode string into an 8-bit string using a specific |
| 921 | encoding, Unicode objects provide an \function{encode()} method |
| 922 | that takes one argument, the name of the encoding. Lowercase names |
| 923 | for encodings are preferred. |
| 924 | |
| 925 | \begin{verbatim} |
| 926 | >>> u"äöü".encode('utf-8') |
| 927 | '\xc3\xa4\xc3\xb6\xc3\xbc' |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 928 | \end{verbatim} |
| 929 | |
| 930 | If you have data in a specific encoding and want to produce a |
| 931 | corresponding Unicode string from it, you can use the |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 932 | \function{unicode()} function with the encoding name as the second |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 933 | argument. |
| 934 | |
| 935 | \begin{verbatim} |
Ka-Ping Yee | 5401996 | 2001-02-13 22:20:22 +0000 | [diff] [blame] | 936 | >>> unicode('\xc3\xa4\xc3\xb6\xc3\xbc', 'utf-8') |
| 937 | u'\xe4\xf6\xfc' |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 938 | \end{verbatim} |
| 939 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 940 | \subsection{Lists \label{lists}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 941 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 942 | Python knows a number of \emph{compound} data types, used to group |
| 943 | together other values. The most versatile is the \emph{list}, which |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 944 | can be written as a list of comma-separated values (items) between |
| 945 | square brackets. List items need not all have the same type. |
| 946 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 947 | \begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 948 | >>> a = ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 949 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 950 | ['spam', 'eggs', 100, 1234] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 951 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 952 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 953 | Like string indices, list indices start at 0, and lists can be sliced, |
| 954 | concatenated and so on: |
| 955 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 956 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 957 | >>> a[0] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 958 | 'spam' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 959 | >>> a[3] |
| 960 | 1234 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 961 | >>> a[-2] |
| 962 | 100 |
| 963 | >>> a[1:-1] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 964 | ['eggs', 100] |
| 965 | >>> a[:2] + ['bacon', 2*2] |
| 966 | ['spam', 'eggs', 'bacon', 4] |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 967 | >>> 3*a[:3] + ['Boe!'] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 968 | ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 969 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 970 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 971 | Unlike strings, which are \emph{immutable}, it is possible to change |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 972 | individual elements of a list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 973 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 974 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 975 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 976 | ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 977 | >>> a[2] = a[2] + 23 |
| 978 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 979 | ['spam', 'eggs', 123, 1234] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 980 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 981 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 982 | Assignment to slices is also possible, and this can even change the size |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 983 | of the list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 984 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 985 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 986 | >>> # Replace some items: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 987 | ... a[0:2] = [1, 12] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 988 | >>> a |
| 989 | [1, 12, 123, 1234] |
| 990 | >>> # Remove some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 991 | ... a[0:2] = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 992 | >>> a |
| 993 | [123, 1234] |
| 994 | >>> # Insert some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 995 | ... a[1:1] = ['bletch', 'xyzzy'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 996 | >>> a |
| 997 | [123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 998 | >>> a[:0] = a # Insert (a copy of) itself at the beginning |
| 999 | >>> a |
| 1000 | [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1001 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1002 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1003 | The built-in function \function{len()} also applies to lists: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1004 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1005 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1006 | >>> len(a) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1007 | 8 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1008 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1009 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1010 | It is possible to nest lists (create lists containing other lists), |
| 1011 | for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1012 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1013 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1014 | >>> q = [2, 3] |
| 1015 | >>> p = [1, q, 4] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1016 | >>> len(p) |
| 1017 | 3 |
| 1018 | >>> p[1] |
| 1019 | [2, 3] |
| 1020 | >>> p[1][0] |
| 1021 | 2 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1022 | >>> p[1].append('xtra') # See section 5.1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1023 | >>> p |
| 1024 | [1, [2, 3, 'xtra'], 4] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1025 | >>> q |
| 1026 | [2, 3, 'xtra'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1027 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1028 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1029 | Note that in the last example, \code{p[1]} and \code{q} really refer to |
| 1030 | the same object! We'll come back to \emph{object semantics} later. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1031 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1032 | \section{First Steps Towards Programming \label{firstSteps}} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1033 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1034 | Of course, we can use Python for more complicated tasks than adding |
| 1035 | two and two together. For instance, we can write an initial |
Fred Drake | 979d041 | 2001-04-03 17:41:56 +0000 | [diff] [blame] | 1036 | sub-sequence of the \emph{Fibonacci} series as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1037 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1038 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1039 | >>> # Fibonacci series: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1040 | ... # the sum of two elements defines the next |
| 1041 | ... a, b = 0, 1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1042 | >>> while b < 10: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1043 | ... print b |
| 1044 | ... a, b = b, a+b |
| 1045 | ... |
| 1046 | 1 |
| 1047 | 1 |
| 1048 | 2 |
| 1049 | 3 |
| 1050 | 5 |
| 1051 | 8 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1052 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1053 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1054 | This example introduces several new features. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1055 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1056 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1057 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1058 | \item |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1059 | The first line contains a \emph{multiple assignment}: the variables |
| 1060 | \code{a} and \code{b} simultaneously get the new values 0 and 1. On the |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1061 | last line this is used again, demonstrating that the expressions on |
| 1062 | the right-hand side are all evaluated first before any of the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1063 | assignments take place. The right-hand side expressions are evaluated |
| 1064 | from the left to the right. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1065 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1066 | \item |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1067 | The \keyword{while} loop executes as long as the condition (here: |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1068 | \code{b < 10}) remains true. In Python, like in C, any non-zero |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1069 | integer value is true; zero is false. The condition may also be a |
| 1070 | string or list value, in fact any sequence; anything with a non-zero |
| 1071 | length is true, empty sequences are false. The test used in the |
| 1072 | example is a simple comparison. The standard comparison operators are |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1073 | written the same as in C: \code{<} (less than), \code{>} (greater than), |
| 1074 | \code{==} (equal to), \code{<=} (less than or equal to), |
| 1075 | \code{>=} (greater than or equal to) and \code{!=} (not equal to). |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1076 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1077 | \item |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1078 | The \emph{body} of the loop is \emph{indented}: indentation is Python's |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1079 | way of grouping statements. Python does not (yet!) provide an |
| 1080 | intelligent input line editing facility, so you have to type a tab or |
| 1081 | space(s) for each indented line. In practice you will prepare more |
| 1082 | complicated input for Python with a text editor; most text editors have |
| 1083 | an auto-indent facility. When a compound statement is entered |
| 1084 | interactively, it must be followed by a blank line to indicate |
| 1085 | completion (since the parser cannot guess when you have typed the last |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1086 | line). Note that each line within a basic block must be indented by |
| 1087 | the same amount. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1088 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1089 | \item |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1090 | The \keyword{print} statement writes the value of the expression(s) it is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1091 | given. It differs from just writing the expression you want to write |
| 1092 | (as we did earlier in the calculator examples) in the way it handles |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1093 | multiple expressions and strings. Strings are printed without quotes, |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1094 | and a space is inserted between items, so you can format things nicely, |
| 1095 | like this: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1096 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1097 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1098 | >>> i = 256*256 |
| 1099 | >>> print 'The value of i is', i |
| 1100 | The value of i is 65536 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1101 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1102 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1103 | A trailing comma avoids the newline after the output: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1104 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1105 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1106 | >>> a, b = 0, 1 |
| 1107 | >>> while b < 1000: |
| 1108 | ... print b, |
| 1109 | ... a, b = b, a+b |
| 1110 | ... |
| 1111 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1112 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1113 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1114 | Note that the interpreter inserts a newline before it prints the next |
| 1115 | prompt if the last line was not completed. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1116 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1117 | \end{itemize} |
| 1118 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1119 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1120 | \chapter{More Control Flow Tools \label{moreControl}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1121 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1122 | Besides the \keyword{while} statement just introduced, Python knows |
| 1123 | the usual control flow statements known from other languages, with |
| 1124 | some twists. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1125 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1126 | \section{\keyword{if} Statements \label{if}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1127 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1128 | Perhaps the most well-known statement type is the |
| 1129 | \keyword{if} statement. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1130 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1131 | \begin{verbatim} |
Fred Drake | d3ba10f | 2001-08-14 19:55:42 +0000 | [diff] [blame] | 1132 | >>> x = int(raw_input("Please enter an integer: ")) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1133 | >>> if x < 0: |
| 1134 | ... x = 0 |
| 1135 | ... print 'Negative changed to zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1136 | ... elif x == 0: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1137 | ... print 'Zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1138 | ... elif x == 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1139 | ... print 'Single' |
| 1140 | ... else: |
| 1141 | ... print 'More' |
| 1142 | ... |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1143 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1144 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1145 | There can be zero or more \keyword{elif} parts, and the |
| 1146 | \keyword{else} part is optional. The keyword `\keyword{elif}' is |
| 1147 | short for `else if', and is useful to avoid excessive indentation. An |
| 1148 | \keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif} \ldots\ sequence |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1149 | % Weird spacings happen here if the wrapping of the source text |
| 1150 | % gets changed in the wrong way. |
Fred Drake | 860106a | 2000-10-20 03:03:18 +0000 | [diff] [blame] | 1151 | is a substitute for the \keyword{switch} or |
| 1152 | \keyword{case} statements found in other languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1153 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1154 | |
| 1155 | \section{\keyword{for} Statements \label{for}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1156 | |
Fred Drake | f790b16 | 1998-11-30 20:37:24 +0000 | [diff] [blame] | 1157 | The \keyword{for}\stindex{for} statement in Python differs a bit from |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1158 | what you may be used to in C or Pascal. Rather than always |
Fred Drake | f790b16 | 1998-11-30 20:37:24 +0000 | [diff] [blame] | 1159 | iterating over an arithmetic progression of numbers (like in Pascal), |
| 1160 | or giving the user the ability to define both the iteration step and |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1161 | halting condition (as C), Python's |
| 1162 | \keyword{for}\stindex{for} statement iterates over the items of any |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 1163 | sequence (a list or a string), in the order that they appear in |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1164 | the sequence. For example (no pun intended): |
Fred Drake | f790b16 | 1998-11-30 20:37:24 +0000 | [diff] [blame] | 1165 | % One suggestion was to give a real C example here, but that may only |
| 1166 | % serve to confuse non-C programmers. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1167 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1168 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1169 | >>> # Measure some strings: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1170 | ... a = ['cat', 'window', 'defenestrate'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1171 | >>> for x in a: |
| 1172 | ... print x, len(x) |
| 1173 | ... |
| 1174 | cat 3 |
| 1175 | window 6 |
| 1176 | defenestrate 12 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1177 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1178 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1179 | It is not safe to modify the sequence being iterated over in the loop |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 1180 | (this can only happen for mutable sequence types, such as lists). If |
| 1181 | you need to modify the list you are iterating over (for example, to |
| 1182 | duplicate selected items) you must iterate over a copy. The slice |
| 1183 | notation makes this particularly convenient: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1184 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1185 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1186 | >>> for x in a[:]: # make a slice copy of the entire list |
| 1187 | ... if len(x) > 6: a.insert(0, x) |
| 1188 | ... |
| 1189 | >>> a |
| 1190 | ['defenestrate', 'cat', 'window', 'defenestrate'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1191 | \end{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1192 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1193 | |
| 1194 | \section{The \function{range()} Function \label{range}} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1195 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1196 | If you do need to iterate over a sequence of numbers, the built-in |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1197 | function \function{range()} comes in handy. It generates lists |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 1198 | containing arithmetic progressions: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1199 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1200 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1201 | >>> range(10) |
| 1202 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1203 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1204 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1205 | The given end point is never part of the generated list; |
| 1206 | \code{range(10)} generates a list of 10 values, exactly the legal |
| 1207 | indices for items of a sequence of length 10. It is possible to let |
| 1208 | the range start at another number, or to specify a different increment |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1209 | (even negative; sometimes this is called the `step'): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1210 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1211 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1212 | >>> range(5, 10) |
| 1213 | [5, 6, 7, 8, 9] |
| 1214 | >>> range(0, 10, 3) |
| 1215 | [0, 3, 6, 9] |
| 1216 | >>> range(-10, -100, -30) |
| 1217 | [-10, -40, -70] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1218 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1219 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1220 | To iterate over the indices of a sequence, combine |
| 1221 | \function{range()} and \function{len()} as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1222 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1223 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1224 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1225 | >>> for i in range(len(a)): |
| 1226 | ... print i, a[i] |
| 1227 | ... |
| 1228 | 0 Mary |
| 1229 | 1 had |
| 1230 | 2 a |
| 1231 | 3 little |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1232 | 4 lamb |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1233 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1234 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1235 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 1236 | \section{\keyword{break} and \keyword{continue} Statements, and |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1237 | \keyword{else} Clauses on Loops |
| 1238 | \label{break}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1239 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1240 | The \keyword{break} statement, like in C, breaks out of the smallest |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1241 | enclosing \keyword{for} or \keyword{while} loop. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1242 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1243 | The \keyword{continue} statement, also borrowed from C, continues |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1244 | with the next iteration of the loop. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1245 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1246 | Loop statements may have an \code{else} clause; it is executed when |
| 1247 | the loop terminates through exhaustion of the list (with |
| 1248 | \keyword{for}) or when the condition becomes false (with |
| 1249 | \keyword{while}), but not when the loop is terminated by a |
| 1250 | \keyword{break} statement. This is exemplified by the following loop, |
| 1251 | which searches for prime numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1252 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1253 | \begin{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1254 | >>> for n in range(2, 10): |
| 1255 | ... for x in range(2, n): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1256 | ... if n % x == 0: |
Fred Drake | 236ffba | 2003-08-16 06:30:47 +0000 | [diff] [blame] | 1257 | ... print n, 'equals', x, '*', n/x |
| 1258 | ... break |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1259 | ... else: |
Fred Drake | 236ffba | 2003-08-16 06:30:47 +0000 | [diff] [blame] | 1260 | ... # loop fell through without finding a factor |
| 1261 | ... print n, 'is a prime number' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1262 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1263 | 2 is a prime number |
| 1264 | 3 is a prime number |
| 1265 | 4 equals 2 * 2 |
| 1266 | 5 is a prime number |
| 1267 | 6 equals 2 * 3 |
| 1268 | 7 is a prime number |
| 1269 | 8 equals 2 * 4 |
| 1270 | 9 equals 3 * 3 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1271 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1272 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1273 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1274 | \section{\keyword{pass} Statements \label{pass}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1275 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1276 | The \keyword{pass} statement does nothing. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1277 | It can be used when a statement is required syntactically but the |
| 1278 | program requires no action. |
| 1279 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1280 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1281 | \begin{verbatim} |
Raymond Hettinger | a6e16a8 | 2002-08-21 04:54:00 +0000 | [diff] [blame] | 1282 | >>> while True: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1283 | ... pass # Busy-wait for keyboard interrupt |
| 1284 | ... |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1285 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1286 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1287 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1288 | \section{Defining Functions \label{functions}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1289 | |
| 1290 | We can create a function that writes the Fibonacci series to an |
| 1291 | arbitrary boundary: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1292 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1293 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1294 | >>> def fib(n): # write Fibonacci series up to n |
Fred Drake | 23d45f4 | 2001-12-20 23:54:56 +0000 | [diff] [blame] | 1295 | ... """Print a Fibonacci series up to n.""" |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1296 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1297 | ... while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1298 | ... print b, |
| 1299 | ... a, b = b, a+b |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1300 | ... |
| 1301 | >>> # Now call the function we just defined: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1302 | ... fib(2000) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1303 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1304 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1305 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1306 | The keyword \keyword{def} introduces a function \emph{definition}. It |
| 1307 | must be followed by the function name and the parenthesized list of |
| 1308 | formal parameters. The statements that form the body of the function |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1309 | start at the next line, and must be indented. The first statement of |
| 1310 | the function body can optionally be a string literal; this string |
| 1311 | literal is the function's \index{documentation strings}documentation |
| 1312 | string, or \dfn{docstring}.\index{docstrings}\index{strings, documentation} |
| 1313 | |
| 1314 | There are tools which use docstrings to automatically produce online |
| 1315 | or printed documentation, or to let the user interactively browse |
| 1316 | through code; it's good practice to include docstrings in code that |
| 1317 | you write, so try to make a habit of it. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1318 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1319 | The \emph{execution} of a function introduces a new symbol table used |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1320 | for the local variables of the function. More precisely, all variable |
| 1321 | assignments in a function store the value in the local symbol table; |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1322 | whereas variable references first look in the local symbol table, then |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1323 | in the global symbol table, and then in the table of built-in names. |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1324 | Thus, global variables cannot be directly assigned a value within a |
| 1325 | function (unless named in a \keyword{global} statement), although |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1326 | they may be referenced. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1327 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1328 | The actual parameters (arguments) to a function call are introduced in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1329 | the local symbol table of the called function when it is called; thus, |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1330 | arguments are passed using \emph{call by value} (where the |
| 1331 | \emph{value} is always an object \emph{reference}, not the value of |
| 1332 | the object).\footnote{ |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1333 | Actually, \emph{call by object reference} would be a better |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1334 | description, since if a mutable object is passed, the caller |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 1335 | will see any changes the callee makes to it (items |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1336 | inserted into a list). |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1337 | } When a function calls another function, a new local symbol table is |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1338 | created for that call. |
| 1339 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1340 | A function definition introduces the function name in the current |
| 1341 | symbol table. The value of the function name |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1342 | has a type that is recognized by the interpreter as a user-defined |
| 1343 | function. This value can be assigned to another name which can then |
| 1344 | also be used as a function. This serves as a general renaming |
| 1345 | mechanism: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1346 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1347 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1348 | >>> fib |
Raymond Hettinger | d3b0bab | 2004-08-22 15:24:33 +0000 | [diff] [blame] | 1349 | <function fib at 10042ed0> |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1350 | >>> f = fib |
| 1351 | >>> f(100) |
| 1352 | 1 1 2 3 5 8 13 21 34 55 89 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1353 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1354 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1355 | You might object that \code{fib} is not a function but a procedure. In |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1356 | Python, like in C, procedures are just functions that don't return a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1357 | value. In fact, technically speaking, procedures do return a value, |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1358 | albeit a rather boring one. This value is called \code{None} (it's a |
| 1359 | built-in name). Writing the value \code{None} is normally suppressed by |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1360 | the interpreter if it would be the only value written. You can see it |
| 1361 | if you really want to: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1362 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1363 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1364 | >>> print fib(0) |
| 1365 | None |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1366 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1367 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1368 | It is simple to write a function that returns a list of the numbers of |
| 1369 | the Fibonacci series, instead of printing it: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1370 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1371 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1372 | >>> def fib2(n): # return Fibonacci series up to n |
Fred Drake | 23d45f4 | 2001-12-20 23:54:56 +0000 | [diff] [blame] | 1373 | ... """Return a list containing the Fibonacci series up to n.""" |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1374 | ... result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1375 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1376 | ... while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1377 | ... result.append(b) # see below |
| 1378 | ... a, b = b, a+b |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1379 | ... return result |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1380 | ... |
| 1381 | >>> f100 = fib2(100) # call it |
| 1382 | >>> f100 # write the result |
| 1383 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1384 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1385 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1386 | This example, as usual, demonstrates some new Python features: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1387 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1388 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1389 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1390 | \item |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1391 | The \keyword{return} statement returns with a value from a function. |
Fred Drake | 0fe5af9 | 2001-01-19 22:34:59 +0000 | [diff] [blame] | 1392 | \keyword{return} without an expression argument returns \code{None}. |
| 1393 | Falling off the end of a procedure also returns \code{None}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1394 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1395 | \item |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1396 | The statement \code{result.append(b)} calls a \emph{method} of the list |
| 1397 | object \code{result}. A method is a function that `belongs' to an |
| 1398 | object and is named \code{obj.methodname}, where \code{obj} is some |
| 1399 | object (this may be an expression), and \code{methodname} is the name |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1400 | of a method that is defined by the object's type. Different types |
| 1401 | define different methods. Methods of different types may have the |
| 1402 | same name without causing ambiguity. (It is possible to define your |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1403 | own object types and methods, using \emph{classes}, as discussed later |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1404 | in this tutorial.) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1405 | The method \method{append()} shown in the example, is defined for |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1406 | list objects; it adds a new element at the end of the list. In this |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1407 | example it is equivalent to \samp{result = result + [b]}, but more |
| 1408 | efficient. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1409 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1410 | \end{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1411 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1412 | \section{More on Defining Functions \label{defining}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1413 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1414 | It is also possible to define functions with a variable number of |
| 1415 | arguments. There are three forms, which can be combined. |
| 1416 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1417 | \subsection{Default Argument Values \label{defaultArgs}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1418 | |
| 1419 | The most useful form is to specify a default value for one or more |
| 1420 | arguments. This creates a function that can be called with fewer |
Fred Drake | f0ae427 | 2004-02-24 16:13:36 +0000 | [diff] [blame] | 1421 | arguments than it is defined to allow. For example: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1422 | |
| 1423 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1424 | def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): |
Raymond Hettinger | a6e16a8 | 2002-08-21 04:54:00 +0000 | [diff] [blame] | 1425 | while True: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1426 | ok = raw_input(prompt) |
Raymond Hettinger | 2569528 | 2003-12-02 07:38:30 +0000 | [diff] [blame] | 1427 | if ok in ('y', 'ye', 'yes'): return True |
| 1428 | if ok in ('n', 'no', 'nop', 'nope'): return False |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1429 | retries = retries - 1 |
| 1430 | if retries < 0: raise IOError, 'refusenik user' |
| 1431 | print complaint |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1432 | \end{verbatim} |
| 1433 | |
| 1434 | This function can be called either like this: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1435 | \code{ask_ok('Do you really want to quit?')} or like this: |
| 1436 | \code{ask_ok('OK to overwrite the file?', 2)}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1437 | |
Martin v. Löwis | f1f0560 | 2004-05-06 01:35:45 +0000 | [diff] [blame] | 1438 | This example also introduces the \keyword{in} keyword. This tests |
| 1439 | whether or not a sequence contains a certain value. |
| 1440 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1441 | The default values are evaluated at the point of function definition |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 1442 | in the \emph{defining} scope, so that |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1443 | |
| 1444 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1445 | i = 5 |
Fred Drake | 8b09f49 | 2001-09-06 18:21:30 +0000 | [diff] [blame] | 1446 | |
| 1447 | def f(arg=i): |
| 1448 | print arg |
| 1449 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1450 | i = 6 |
| 1451 | f() |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1452 | \end{verbatim} |
| 1453 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1454 | will print \code{5}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1455 | |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1456 | \strong{Important warning:} The default value is evaluated only once. |
| 1457 | This makes a difference when the default is a mutable object such as a |
Fred Drake | 3a8fbe7 | 2003-06-18 17:14:29 +0000 | [diff] [blame] | 1458 | list, dictionary, or instances of most classes. For example, the |
| 1459 | following function accumulates the arguments passed to it on |
| 1460 | subsequent calls: |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1461 | |
| 1462 | \begin{verbatim} |
Fred Drake | 8b09f49 | 2001-09-06 18:21:30 +0000 | [diff] [blame] | 1463 | def f(a, L=[]): |
| 1464 | L.append(a) |
| 1465 | return L |
| 1466 | |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1467 | print f(1) |
| 1468 | print f(2) |
| 1469 | print f(3) |
| 1470 | \end{verbatim} |
| 1471 | |
| 1472 | This will print |
| 1473 | |
| 1474 | \begin{verbatim} |
| 1475 | [1] |
| 1476 | [1, 2] |
| 1477 | [1, 2, 3] |
| 1478 | \end{verbatim} |
| 1479 | |
| 1480 | If you don't want the default to be shared between subsequent calls, |
| 1481 | you can write the function like this instead: |
| 1482 | |
| 1483 | \begin{verbatim} |
Fred Drake | 8b09f49 | 2001-09-06 18:21:30 +0000 | [diff] [blame] | 1484 | def f(a, L=None): |
| 1485 | if L is None: |
| 1486 | L = [] |
| 1487 | L.append(a) |
| 1488 | return L |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1489 | \end{verbatim} |
| 1490 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1491 | \subsection{Keyword Arguments \label{keywordArgs}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1492 | |
| 1493 | Functions can also be called using |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1494 | keyword arguments of the form \samp{\var{keyword} = \var{value}}. For |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1495 | instance, the following function: |
| 1496 | |
| 1497 | \begin{verbatim} |
| 1498 | def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): |
| 1499 | print "-- This parrot wouldn't", action, |
| 1500 | print "if you put", voltage, "Volts through it." |
| 1501 | print "-- Lovely plumage, the", type |
| 1502 | print "-- It's", state, "!" |
| 1503 | \end{verbatim} |
| 1504 | |
| 1505 | could be called in any of the following ways: |
| 1506 | |
| 1507 | \begin{verbatim} |
| 1508 | parrot(1000) |
| 1509 | parrot(action = 'VOOOOOM', voltage = 1000000) |
| 1510 | parrot('a thousand', state = 'pushing up the daisies') |
| 1511 | parrot('a million', 'bereft of life', 'jump') |
| 1512 | \end{verbatim} |
| 1513 | |
| 1514 | but the following calls would all be invalid: |
| 1515 | |
| 1516 | \begin{verbatim} |
| 1517 | parrot() # required argument missing |
| 1518 | parrot(voltage=5.0, 'dead') # non-keyword argument following keyword |
| 1519 | parrot(110, voltage=220) # duplicate value for argument |
| 1520 | parrot(actor='John Cleese') # unknown keyword |
| 1521 | \end{verbatim} |
| 1522 | |
| 1523 | In general, an argument list must have any positional arguments |
| 1524 | followed by any keyword arguments, where the keywords must be chosen |
| 1525 | from the formal parameter names. It's not important whether a formal |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1526 | parameter has a default value or not. No argument may receive a |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1527 | value more than once --- formal parameter names corresponding to |
| 1528 | positional arguments cannot be used as keywords in the same calls. |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1529 | Here's an example that fails due to this restriction: |
| 1530 | |
| 1531 | \begin{verbatim} |
| 1532 | >>> def function(a): |
| 1533 | ... pass |
| 1534 | ... |
| 1535 | >>> function(0, a=0) |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 1536 | Traceback (most recent call last): |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1537 | File "<stdin>", line 1, in ? |
Raymond Hettinger | a02469f | 2003-05-07 17:49:36 +0000 | [diff] [blame] | 1538 | TypeError: function() got multiple values for keyword argument 'a' |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1539 | \end{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1540 | |
| 1541 | When a final formal parameter of the form \code{**\var{name}} is |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 1542 | present, it receives a \ulink{dictionary}{../lib/typesmapping.html} containing all keyword arguments |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1543 | whose keyword doesn't correspond to a formal parameter. This may be |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1544 | combined with a formal parameter of the form |
| 1545 | \code{*\var{name}} (described in the next subsection) which receives a |
| 1546 | tuple containing the positional arguments beyond the formal parameter |
| 1547 | list. (\code{*\var{name}} must occur before \code{**\var{name}}.) |
| 1548 | For example, if we define a function like this: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1549 | |
| 1550 | \begin{verbatim} |
| 1551 | def cheeseshop(kind, *arguments, **keywords): |
| 1552 | print "-- Do you have any", kind, '?' |
| 1553 | print "-- I'm sorry, we're all out of", kind |
| 1554 | for arg in arguments: print arg |
| 1555 | print '-'*40 |
Fred Drake | c26467d | 2002-01-29 14:53:30 +0000 | [diff] [blame] | 1556 | keys = keywords.keys() |
| 1557 | keys.sort() |
| 1558 | for kw in keys: print kw, ':', keywords[kw] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1559 | \end{verbatim} |
| 1560 | |
| 1561 | It could be called like this: |
| 1562 | |
| 1563 | \begin{verbatim} |
| 1564 | cheeseshop('Limburger', "It's very runny, sir.", |
| 1565 | "It's really very, VERY runny, sir.", |
| 1566 | client='John Cleese', |
| 1567 | shopkeeper='Michael Palin', |
| 1568 | sketch='Cheese Shop Sketch') |
| 1569 | \end{verbatim} |
| 1570 | |
| 1571 | and of course it would print: |
| 1572 | |
| 1573 | \begin{verbatim} |
| 1574 | -- Do you have any Limburger ? |
| 1575 | -- I'm sorry, we're all out of Limburger |
| 1576 | It's very runny, sir. |
| 1577 | It's really very, VERY runny, sir. |
| 1578 | ---------------------------------------- |
| 1579 | client : John Cleese |
| 1580 | shopkeeper : Michael Palin |
| 1581 | sketch : Cheese Shop Sketch |
| 1582 | \end{verbatim} |
| 1583 | |
Fred Drake | c26467d | 2002-01-29 14:53:30 +0000 | [diff] [blame] | 1584 | Note that the \method{sort()} method of the list of keyword argument |
| 1585 | names is called before printing the contents of the \code{keywords} |
| 1586 | dictionary; if this is not done, the order in which the arguments are |
| 1587 | printed is undefined. |
| 1588 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1589 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1590 | \subsection{Arbitrary Argument Lists \label{arbitraryArgs}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1591 | |
| 1592 | Finally, the least frequently used option is to specify that a |
| 1593 | function can be called with an arbitrary number of arguments. These |
| 1594 | arguments will be wrapped up in a tuple. Before the variable number |
| 1595 | of arguments, zero or more normal arguments may occur. |
| 1596 | |
| 1597 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1598 | def fprintf(file, format, *args): |
| 1599 | file.write(format % args) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1600 | \end{verbatim} |
| 1601 | |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1602 | |
Raymond Hettinger | 0eec087 | 2003-08-08 23:32:46 +0000 | [diff] [blame] | 1603 | \subsection{Unpacking Argument Lists \label{unpacking-arguments}} |
| 1604 | |
| 1605 | The reverse situation occurs when the arguments are already in a list |
| 1606 | or tuple but need to be unpacked for a function call requiring separate |
| 1607 | positional arguments. For instance, the built-in \function{range()} |
| 1608 | function expects separate \var{start} and \var{stop} arguments. If they |
| 1609 | are not available separately, write the function call with the |
| 1610 | \code{*}-operator to unpack the arguments out of a list or tuple: |
| 1611 | |
| 1612 | \begin{verbatim} |
| 1613 | >>> range(3, 6) # normal call with separate arguments |
| 1614 | [3, 4, 5] |
| 1615 | >>> args = [3, 6] |
| 1616 | >>> range(*args) # call with arguments unpacked from a list |
| 1617 | [3, 4, 5] |
| 1618 | \end{verbatim} |
| 1619 | |
| 1620 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1621 | \subsection{Lambda Forms \label{lambda}} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1622 | |
| 1623 | By popular demand, a few features commonly found in functional |
| 1624 | programming languages and Lisp have been added to Python. With the |
| 1625 | \keyword{lambda} keyword, small anonymous functions can be created. |
| 1626 | Here's a function that returns the sum of its two arguments: |
| 1627 | \samp{lambda a, b: a+b}. Lambda forms can be used wherever function |
| 1628 | objects are required. They are syntactically restricted to a single |
| 1629 | expression. Semantically, they are just syntactic sugar for a normal |
| 1630 | function definition. Like nested function definitions, lambda forms |
Fred Drake | fcf9468 | 2001-12-03 21:47:37 +0000 | [diff] [blame] | 1631 | can reference variables from the containing scope: |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1632 | |
| 1633 | \begin{verbatim} |
Tim Peters | c113465 | 2000-11-27 06:38:04 +0000 | [diff] [blame] | 1634 | >>> def make_incrementor(n): |
Fred Drake | fcf9468 | 2001-12-03 21:47:37 +0000 | [diff] [blame] | 1635 | ... return lambda x: x + n |
Tim Peters | c113465 | 2000-11-27 06:38:04 +0000 | [diff] [blame] | 1636 | ... |
| 1637 | >>> f = make_incrementor(42) |
| 1638 | >>> f(0) |
| 1639 | 42 |
| 1640 | >>> f(1) |
| 1641 | 43 |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1642 | \end{verbatim} |
| 1643 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1644 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1645 | \subsection{Documentation Strings \label{docstrings}} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1646 | |
| 1647 | There are emerging conventions about the content and formatting of |
| 1648 | documentation strings. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1649 | \index{docstrings}\index{documentation strings} |
| 1650 | \index{strings, documentation} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1651 | |
| 1652 | The first line should always be a short, concise summary of the |
| 1653 | object's purpose. For brevity, it should not explicitly state the |
| 1654 | object's name or type, since these are available by other means |
| 1655 | (except if the name happens to be a verb describing a function's |
| 1656 | operation). This line should begin with a capital letter and end with |
| 1657 | a period. |
| 1658 | |
| 1659 | If there are more lines in the documentation string, the second line |
| 1660 | should be blank, visually separating the summary from the rest of the |
Fred Drake | 4b1a07a | 1999-03-12 18:21:32 +0000 | [diff] [blame] | 1661 | description. The following lines should be one or more paragraphs |
| 1662 | describing the object's calling conventions, its side effects, etc. |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1663 | |
| 1664 | The Python parser does not strip indentation from multi-line string |
| 1665 | literals in Python, so tools that process documentation have to strip |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1666 | indentation if desired. This is done using the following convention. |
| 1667 | The first non-blank line \emph{after} the first line of the string |
| 1668 | determines the amount of indentation for the entire documentation |
| 1669 | string. (We can't use the first line since it is generally adjacent |
| 1670 | to the string's opening quotes so its indentation is not apparent in |
| 1671 | the string literal.) Whitespace ``equivalent'' to this indentation is |
| 1672 | then stripped from the start of all lines of the string. Lines that |
| 1673 | are indented less should not occur, but if they occur all their |
| 1674 | leading whitespace should be stripped. Equivalence of whitespace |
| 1675 | should be tested after expansion of tabs (to 8 spaces, normally). |
| 1676 | |
| 1677 | Here is an example of a multi-line docstring: |
| 1678 | |
| 1679 | \begin{verbatim} |
| 1680 | >>> def my_function(): |
| 1681 | ... """Do nothing, but document it. |
| 1682 | ... |
| 1683 | ... No, really, it doesn't do anything. |
| 1684 | ... """ |
| 1685 | ... pass |
| 1686 | ... |
| 1687 | >>> print my_function.__doc__ |
| 1688 | Do nothing, but document it. |
| 1689 | |
| 1690 | No, really, it doesn't do anything. |
| 1691 | |
| 1692 | \end{verbatim} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1693 | |
| 1694 | |
| 1695 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1696 | \chapter{Data Structures \label{structures}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1697 | |
| 1698 | This chapter describes some things you've learned about already in |
| 1699 | more detail, and adds some new things as well. |
| 1700 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1701 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1702 | \section{More on Lists \label{moreLists}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1703 | |
| 1704 | The list data type has some more methods. Here are all of the methods |
Fred Drake | ed68854 | 1998-02-11 22:29:17 +0000 | [diff] [blame] | 1705 | of list objects: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1706 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1707 | \begin{methoddesc}[list]{append}{x} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1708 | Add an item to the end of the list; |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1709 | equivalent to \code{a[len(a):] = [\var{x}]}. |
| 1710 | \end{methoddesc} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1711 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1712 | \begin{methoddesc}[list]{extend}{L} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1713 | Extend the list by appending all the items in the given list; |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1714 | equivalent to \code{a[len(a):] = \var{L}}. |
| 1715 | \end{methoddesc} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1716 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1717 | \begin{methoddesc}[list]{insert}{i, x} |
| 1718 | Insert an item at a given position. The first argument is the index |
| 1719 | of the element before which to insert, so \code{a.insert(0, \var{x})} |
| 1720 | inserts at the front of the list, and \code{a.insert(len(a), \var{x})} |
| 1721 | is equivalent to \code{a.append(\var{x})}. |
| 1722 | \end{methoddesc} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1723 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1724 | \begin{methoddesc}[list]{remove}{x} |
| 1725 | Remove the first item from the list whose value is \var{x}. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1726 | It is an error if there is no such item. |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1727 | \end{methoddesc} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1728 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1729 | \begin{methoddesc}[list]{pop}{\optional{i}} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1730 | Remove the item at the given position in the list, and return it. If |
| 1731 | no index is specified, \code{a.pop()} returns the last item in the |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1732 | list. The item is also removed from the list. (The square brackets |
| 1733 | around the \var{i} in the method signature denote that the parameter |
| 1734 | is optional, not that you should type square brackets at that |
| 1735 | position. You will see this notation frequently in the |
| 1736 | \citetitle[../lib/lib.html]{Python Library Reference}.) |
| 1737 | \end{methoddesc} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1738 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1739 | \begin{methoddesc}[list]{index}{x} |
| 1740 | Return the index in the list of the first item whose value is \var{x}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1741 | It is an error if there is no such item. |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1742 | \end{methoddesc} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1743 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1744 | \begin{methoddesc}[list]{count}{x} |
| 1745 | Return the number of times \var{x} appears in the list. |
| 1746 | \end{methoddesc} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1747 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1748 | \begin{methoddesc}[list]{sort}{} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1749 | Sort the items of the list, in place. |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1750 | \end{methoddesc} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1751 | |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1752 | \begin{methoddesc}[list]{reverse}{} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1753 | Reverse the elements of the list, in place. |
Fred Drake | 55ad7f8 | 2002-06-11 02:56:17 +0000 | [diff] [blame] | 1754 | \end{methoddesc} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1755 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1756 | An example that uses most of the list methods: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1757 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1758 | \begin{verbatim} |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1759 | >>> a = [66.25, 333, 333, 1, 1234.5] |
| 1760 | >>> print a.count(333), a.count(66.25), a.count('x') |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1761 | 2 1 0 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1762 | >>> a.insert(2, -1) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1763 | >>> a.append(333) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1764 | >>> a |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1765 | [66.25, 333, -1, 333, 1, 1234.5, 333] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1766 | >>> a.index(333) |
| 1767 | 1 |
| 1768 | >>> a.remove(333) |
| 1769 | >>> a |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1770 | [66.25, -1, 333, 1, 1234.5, 333] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1771 | >>> a.reverse() |
| 1772 | >>> a |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1773 | [333, 1234.5, 1, 333, -1, 66.25] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1774 | >>> a.sort() |
| 1775 | >>> a |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1776 | [-1, 1, 66.25, 333, 333, 1234.5] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1777 | \end{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1778 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1779 | |
| 1780 | \subsection{Using Lists as Stacks \label{lists-as-stacks}} |
Fred Drake | 67fdaa4 | 2001-03-06 07:19:34 +0000 | [diff] [blame] | 1781 | \sectionauthor{Ka-Ping Yee}{ping@lfw.org} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1782 | |
| 1783 | The list methods make it very easy to use a list as a stack, where the |
| 1784 | last element added is the first element retrieved (``last-in, |
| 1785 | first-out''). To add an item to the top of the stack, use |
| 1786 | \method{append()}. To retrieve an item from the top of the stack, use |
| 1787 | \method{pop()} without an explicit index. For example: |
| 1788 | |
| 1789 | \begin{verbatim} |
| 1790 | >>> stack = [3, 4, 5] |
| 1791 | >>> stack.append(6) |
| 1792 | >>> stack.append(7) |
| 1793 | >>> stack |
| 1794 | [3, 4, 5, 6, 7] |
| 1795 | >>> stack.pop() |
| 1796 | 7 |
| 1797 | >>> stack |
| 1798 | [3, 4, 5, 6] |
| 1799 | >>> stack.pop() |
| 1800 | 6 |
| 1801 | >>> stack.pop() |
| 1802 | 5 |
| 1803 | >>> stack |
| 1804 | [3, 4] |
| 1805 | \end{verbatim} |
| 1806 | |
| 1807 | |
| 1808 | \subsection{Using Lists as Queues \label{lists-as-queues}} |
Fred Drake | 67fdaa4 | 2001-03-06 07:19:34 +0000 | [diff] [blame] | 1809 | \sectionauthor{Ka-Ping Yee}{ping@lfw.org} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1810 | |
| 1811 | You can also use a list conveniently as a queue, where the first |
| 1812 | element added is the first element retrieved (``first-in, |
| 1813 | first-out''). To add an item to the back of the queue, use |
| 1814 | \method{append()}. To retrieve an item from the front of the queue, |
| 1815 | use \method{pop()} with \code{0} as the index. For example: |
| 1816 | |
| 1817 | \begin{verbatim} |
| 1818 | >>> queue = ["Eric", "John", "Michael"] |
| 1819 | >>> queue.append("Terry") # Terry arrives |
| 1820 | >>> queue.append("Graham") # Graham arrives |
| 1821 | >>> queue.pop(0) |
| 1822 | 'Eric' |
| 1823 | >>> queue.pop(0) |
| 1824 | 'John' |
| 1825 | >>> queue |
| 1826 | ['Michael', 'Terry', 'Graham'] |
| 1827 | \end{verbatim} |
| 1828 | |
| 1829 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1830 | \subsection{Functional Programming Tools \label{functional}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1831 | |
| 1832 | There are three built-in functions that are very useful when used with |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1833 | lists: \function{filter()}, \function{map()}, and \function{reduce()}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1834 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1835 | \samp{filter(\var{function}, \var{sequence})} returns a sequence (of |
| 1836 | the same type, if possible) consisting of those items from the |
| 1837 | sequence for which \code{\var{function}(\var{item})} is true. For |
| 1838 | example, to compute some primes: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1839 | |
| 1840 | \begin{verbatim} |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1841 | >>> def f(x): return x % 2 != 0 and x % 3 != 0 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1842 | ... |
| 1843 | >>> filter(f, range(2, 25)) |
| 1844 | [5, 7, 11, 13, 17, 19, 23] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1845 | \end{verbatim} |
| 1846 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1847 | \samp{map(\var{function}, \var{sequence})} calls |
| 1848 | \code{\var{function}(\var{item})} for each of the sequence's items and |
| 1849 | returns a list of the return values. For example, to compute some |
| 1850 | cubes: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1851 | |
| 1852 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1853 | >>> def cube(x): return x*x*x |
| 1854 | ... |
| 1855 | >>> map(cube, range(1, 11)) |
| 1856 | [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1857 | \end{verbatim} |
| 1858 | |
| 1859 | More than one sequence may be passed; the function must then have as |
| 1860 | many arguments as there are sequences and is called with the |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1861 | corresponding item from each sequence (or \code{None} if some sequence |
Neil Schemenauer | 90b182c | 2003-08-14 22:57:46 +0000 | [diff] [blame] | 1862 | is shorter than another). For example: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1863 | |
| 1864 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1865 | >>> seq = range(8) |
Neil Schemenauer | 90b182c | 2003-08-14 22:57:46 +0000 | [diff] [blame] | 1866 | >>> def add(x, y): return x+y |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1867 | ... |
Neil Schemenauer | 90b182c | 2003-08-14 22:57:46 +0000 | [diff] [blame] | 1868 | >>> map(add, seq, seq) |
| 1869 | [0, 2, 4, 6, 8, 10, 12, 14] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1870 | \end{verbatim} |
| 1871 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1872 | \samp{reduce(\var{func}, \var{sequence})} returns a single value |
| 1873 | constructed by calling the binary function \var{func} on the first two |
| 1874 | items of the sequence, then on the result and the next item, and so |
| 1875 | on. For example, to compute the sum of the numbers 1 through 10: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1876 | |
| 1877 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1878 | >>> def add(x,y): return x+y |
| 1879 | ... |
| 1880 | >>> reduce(add, range(1, 11)) |
| 1881 | 55 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1882 | \end{verbatim} |
| 1883 | |
| 1884 | If there's only one item in the sequence, its value is returned; if |
| 1885 | the sequence is empty, an exception is raised. |
| 1886 | |
| 1887 | A third argument can be passed to indicate the starting value. In this |
| 1888 | case the starting value is returned for an empty sequence, and the |
| 1889 | function is first applied to the starting value and the first sequence |
| 1890 | item, then to the result and the next item, and so on. For example, |
| 1891 | |
| 1892 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1893 | >>> def sum(seq): |
| 1894 | ... def add(x,y): return x+y |
| 1895 | ... return reduce(add, seq, 0) |
| 1896 | ... |
| 1897 | >>> sum(range(1, 11)) |
| 1898 | 55 |
| 1899 | >>> sum([]) |
| 1900 | 0 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1901 | \end{verbatim} |
| 1902 | |
Fred Drake | 03e929e | 2003-04-22 14:30:53 +0000 | [diff] [blame] | 1903 | Don't use this example's definition of \function{sum()}: since summing |
| 1904 | numbers is such a common need, a built-in function |
| 1905 | \code{sum(\var{sequence})} is already provided, and works exactly like |
| 1906 | this. |
| 1907 | \versionadded{2.3} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1908 | |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1909 | \subsection{List Comprehensions} |
| 1910 | |
Skip Montanaro | 46dfa5f | 2000-08-22 02:43:07 +0000 | [diff] [blame] | 1911 | List comprehensions provide a concise way to create lists without resorting |
| 1912 | to use of \function{map()}, \function{filter()} and/or \keyword{lambda}. |
| 1913 | The resulting list definition tends often to be clearer than lists built |
| 1914 | using those constructs. Each list comprehension consists of an expression |
Fred Drake | 33fd5f7 | 2002-06-26 21:25:15 +0000 | [diff] [blame] | 1915 | followed by a \keyword{for} clause, then zero or more \keyword{for} or |
Skip Montanaro | 46dfa5f | 2000-08-22 02:43:07 +0000 | [diff] [blame] | 1916 | \keyword{if} clauses. The result will be a list resulting from evaluating |
| 1917 | the expression in the context of the \keyword{for} and \keyword{if} clauses |
| 1918 | which follow it. If the expression would evaluate to a tuple, it must be |
| 1919 | parenthesized. |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1920 | |
| 1921 | \begin{verbatim} |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1922 | >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] |
| 1923 | >>> [weapon.strip() for weapon in freshfruit] |
| 1924 | ['banana', 'loganberry', 'passion fruit'] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1925 | >>> vec = [2, 4, 6] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1926 | >>> [3*x for x in vec] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1927 | [6, 12, 18] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1928 | >>> [3*x for x in vec if x > 3] |
| 1929 | [12, 18] |
| 1930 | >>> [3*x for x in vec if x < 2] |
| 1931 | [] |
Skip Montanaro | 46dfa5f | 2000-08-22 02:43:07 +0000 | [diff] [blame] | 1932 | >>> [[x,x**2] for x in vec] |
| 1933 | [[2, 4], [4, 16], [6, 36]] |
| 1934 | >>> [x, x**2 for x in vec] # error - parens required for tuples |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 1935 | File "<stdin>", line 1, in ? |
Skip Montanaro | 46dfa5f | 2000-08-22 02:43:07 +0000 | [diff] [blame] | 1936 | [x, x**2 for x in vec] |
| 1937 | ^ |
| 1938 | SyntaxError: invalid syntax |
| 1939 | >>> [(x, x**2) for x in vec] |
| 1940 | [(2, 4), (4, 16), (6, 36)] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1941 | >>> vec1 = [2, 4, 6] |
| 1942 | >>> vec2 = [4, 3, -9] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1943 | >>> [x*y for x in vec1 for y in vec2] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1944 | [8, 6, -18, 16, 12, -36, 24, 18, -54] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1945 | >>> [x+y for x in vec1 for y in vec2] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1946 | [6, 5, -7, 8, 7, -5, 10, 9, -3] |
Fred Drake | 1da50f6 | 2001-12-03 18:54:33 +0000 | [diff] [blame] | 1947 | >>> [vec1[i]*vec2[i] for i in range(len(vec1))] |
| 1948 | [8, 12, -54] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1949 | \end{verbatim} |
| 1950 | |
Raymond Hettinger | 57d7128 | 2003-08-30 23:21:32 +0000 | [diff] [blame] | 1951 | List comprehensions are much more flexible than \function{map()} and can be |
| 1952 | applied to functions with more than one argument and to nested functions: |
| 1953 | |
| 1954 | \begin{verbatim} |
| 1955 | >>> [str(round(355/113.0, i)) for i in range(1,6)] |
| 1956 | ['3.1', '3.14', '3.142', '3.1416', '3.14159'] |
| 1957 | \end{verbatim} |
| 1958 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1959 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1960 | \section{The \keyword{del} statement \label{del}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1961 | |
| 1962 | There is a way to remove an item from a list given its index instead |
Fred Drake | 81f7eb6 | 2000-08-12 20:08:04 +0000 | [diff] [blame] | 1963 | of its value: the \keyword{del} statement. This can also be used to |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1964 | remove slices from a list (which we did earlier by assignment of an |
| 1965 | empty list to the slice). For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1966 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1967 | \begin{verbatim} |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1968 | >>> a = [-1, 1, 66.25, 333, 333, 1234.5] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1969 | >>> del a[0] |
| 1970 | >>> a |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1971 | [1, 66.25, 333, 333, 1234.5] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1972 | >>> del a[2:4] |
| 1973 | >>> a |
Tim Peters | 01ba799 | 2004-09-28 16:12:50 +0000 | [diff] [blame] | 1974 | [1, 66.25, 1234.5] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1975 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1976 | |
| 1977 | \keyword{del} can also be used to delete entire variables: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1978 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1979 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1980 | >>> del a |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1981 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1982 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1983 | Referencing the name \code{a} hereafter is an error (at least until |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1984 | another value is assigned to it). We'll find other uses for |
| 1985 | \keyword{del} later. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1986 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1987 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1988 | \section{Tuples and Sequences \label{tuples}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1989 | |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 1990 | We saw that lists and strings have many common properties, such as |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1991 | indexing and slicing operations. They are two examples of |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 1992 | \ulink{\emph{sequence} data types}{../lib/typesseq.html}. Since |
| 1993 | Python is an evolving language, other sequence data types may be |
| 1994 | added. There is also another standard sequence data type: the |
| 1995 | \emph{tuple}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1996 | |
| 1997 | A tuple consists of a number of values separated by commas, for |
| 1998 | instance: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1999 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2000 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2001 | >>> t = 12345, 54321, 'hello!' |
| 2002 | >>> t[0] |
| 2003 | 12345 |
| 2004 | >>> t |
| 2005 | (12345, 54321, 'hello!') |
| 2006 | >>> # Tuples may be nested: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2007 | ... u = t, (1, 2, 3, 4, 5) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2008 | >>> u |
| 2009 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2010 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2011 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2012 | As you see, on output tuples are alway enclosed in parentheses, so |
| 2013 | that nested tuples are interpreted correctly; they may be input with |
| 2014 | or without surrounding parentheses, although often parentheses are |
| 2015 | necessary anyway (if the tuple is part of a larger expression). |
| 2016 | |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2017 | Tuples have many uses. For example: (x, y) coordinate pairs, employee |
| 2018 | records from a database, etc. Tuples, like strings, are immutable: it |
| 2019 | is not possible to assign to the individual items of a tuple (you can |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2020 | simulate much of the same effect with slicing and concatenation, |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2021 | though). It is also possible to create tuples which contain mutable |
| 2022 | objects, such as lists. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2023 | |
| 2024 | A special problem is the construction of tuples containing 0 or 1 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2025 | items: the syntax has some extra quirks to accommodate these. Empty |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2026 | tuples are constructed by an empty pair of parentheses; a tuple with |
| 2027 | one item is constructed by following a value with a comma |
| 2028 | (it is not sufficient to enclose a single value in parentheses). |
| 2029 | Ugly, but effective. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2030 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2031 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2032 | >>> empty = () |
| 2033 | >>> singleton = 'hello', # <-- note trailing comma |
| 2034 | >>> len(empty) |
| 2035 | 0 |
| 2036 | >>> len(singleton) |
| 2037 | 1 |
| 2038 | >>> singleton |
| 2039 | ('hello',) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2040 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2041 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2042 | The statement \code{t = 12345, 54321, 'hello!'} is an example of |
| 2043 | \emph{tuple packing}: the values \code{12345}, \code{54321} and |
| 2044 | \code{'hello!'} are packed together in a tuple. The reverse operation |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2045 | is also possible: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2046 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2047 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2048 | >>> x, y, z = t |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2049 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2050 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2051 | This is called, appropriately enough, \emph{sequence unpacking}. |
| 2052 | Sequence unpacking requires that the list of variables on the left |
| 2053 | have the same number of elements as the length of the sequence. Note |
| 2054 | that multiple assignment is really just a combination of tuple packing |
| 2055 | and sequence unpacking! |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2056 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2057 | There is a small bit of asymmetry here: packing multiple values |
| 2058 | always creates a tuple, and unpacking works for any sequence. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2059 | |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 2060 | % XXX Add a bit on the difference between tuples and lists. |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2061 | |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 2062 | |
Raymond Hettinger | 65674b8 | 2003-11-18 17:50:34 +0000 | [diff] [blame] | 2063 | \section{Sets \label{sets}} |
| 2064 | |
| 2065 | Python also includes a data type for \emph{sets}. A set is an unordered |
| 2066 | collection with no duplicate elements. Basic uses include membership |
| 2067 | testing and eliminating duplicate entries. Set objects also support |
| 2068 | mathematical operations like union, intersection, difference, and |
| 2069 | symmetric difference. |
| 2070 | |
| 2071 | Here is a brief demonstration: |
| 2072 | |
| 2073 | \begin{verbatim} |
| 2074 | >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] |
| 2075 | >>> fruits = set(basket) # create a set without duplicates |
| 2076 | >>> fruits |
| 2077 | set(['orange', 'pear', 'apple', 'banana']) |
| 2078 | >>> 'orange' in fruits # fast membership testing |
| 2079 | True |
| 2080 | >>> 'crabgrass' in fruits |
| 2081 | False |
| 2082 | |
| 2083 | >>> # Demonstrate set operations on unique letters from two words |
| 2084 | ... |
| 2085 | >>> a = set('abracadabra') |
| 2086 | >>> b = set('alacazam') |
| 2087 | >>> a # unique letters in a |
| 2088 | set(['a', 'r', 'b', 'c', 'd']) |
| 2089 | >>> a - b # letters in a but not in b |
| 2090 | set(['r', 'd', 'b']) |
| 2091 | >>> a | b # letters in either a or b |
| 2092 | set(['a', 'c', 'r', 'd', 'b', 'm', 'z', 'l']) |
| 2093 | >>> a & b # letters in both a and b |
| 2094 | set(['a', 'c']) |
| 2095 | >>> a ^ b # letters in a or b but not both |
| 2096 | set(['r', 'd', 'b', 'm', 'z', 'l']) |
| 2097 | \end{verbatim} |
| 2098 | |
| 2099 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2100 | \section{Dictionaries \label{dictionaries}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2101 | |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2102 | Another useful data type built into Python is the |
| 2103 | \ulink{\emph{dictionary}}{../lib/typesmapping.html}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2104 | Dictionaries are sometimes found in other languages as ``associative |
| 2105 | memories'' or ``associative arrays''. Unlike sequences, which are |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2106 | indexed by a range of numbers, dictionaries are indexed by \emph{keys}, |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 2107 | which can be any immutable type; strings and numbers can always be |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2108 | keys. Tuples can be used as keys if they contain only strings, |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2109 | numbers, or tuples; if a tuple contains any mutable object either |
| 2110 | directly or indirectly, it cannot be used as a key. You can't use |
| 2111 | lists as keys, since lists can be modified in place using their |
| 2112 | \method{append()} and \method{extend()} methods, as well as slice and |
| 2113 | indexed assignments. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2114 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2115 | It is best to think of a dictionary as an unordered set of |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2116 | \emph{key: value} pairs, with the requirement that the keys are unique |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2117 | (within one dictionary). |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2118 | A pair of braces creates an empty dictionary: \code{\{\}}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2119 | Placing a comma-separated list of key:value pairs within the |
| 2120 | braces adds initial key:value pairs to the dictionary; this is also the |
| 2121 | way dictionaries are written on output. |
| 2122 | |
| 2123 | The main operations on a dictionary are storing a value with some key |
| 2124 | and extracting the value given the key. It is also possible to delete |
| 2125 | a key:value pair |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2126 | with \code{del}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2127 | If you store using a key that is already in use, the old value |
| 2128 | associated with that key is forgotten. It is an error to extract a |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2129 | value using a non-existent key. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2130 | |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2131 | The \method{keys()} method of a dictionary object returns a list of all |
Johannes Gijsbers | 6ab4b99 | 2004-09-11 17:48:21 +0000 | [diff] [blame] | 2132 | the keys used in the dictionary, in arbitrary order (if you want it |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2133 | sorted, just apply the \method{sort()} method to the list of keys). To |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2134 | check whether a single key is in the dictionary, use the |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2135 | \method{has_key()} method of the dictionary. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2136 | |
| 2137 | Here is a small example using a dictionary: |
| 2138 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2139 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2140 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 2141 | >>> tel['guido'] = 4127 |
| 2142 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 2143 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2144 | >>> tel['jack'] |
| 2145 | 4098 |
| 2146 | >>> del tel['sape'] |
| 2147 | >>> tel['irv'] = 4127 |
| 2148 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 2149 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2150 | >>> tel.keys() |
| 2151 | ['guido', 'irv', 'jack'] |
| 2152 | >>> tel.has_key('guido') |
Raymond Hettinger | a02469f | 2003-05-07 17:49:36 +0000 | [diff] [blame] | 2153 | True |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2154 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2155 | |
Walter Dörwald | 7bafa9f | 2003-12-03 10:34:57 +0000 | [diff] [blame] | 2156 | The \function{dict()} constructor builds dictionaries directly from |
Raymond Hettinger | 07dc918 | 2002-06-25 15:13:18 +0000 | [diff] [blame] | 2157 | lists of key-value pairs stored as tuples. When the pairs form a |
| 2158 | pattern, list comprehensions can compactly specify the key-value list. |
| 2159 | |
| 2160 | \begin{verbatim} |
| 2161 | >>> dict([('sape', 4139), ('guido', 4127), ('jack', 4098)]) |
| 2162 | {'sape': 4139, 'jack': 4098, 'guido': 4127} |
| 2163 | >>> dict([(x, x**2) for x in vec]) # use a list comprehension |
| 2164 | {2: 4, 4: 16, 6: 36} |
| 2165 | \end{verbatim} |
| 2166 | |
Fred Drake | 38f7197 | 2002-04-26 20:29:44 +0000 | [diff] [blame] | 2167 | |
| 2168 | \section{Looping Techniques \label{loopidioms}} |
| 2169 | |
| 2170 | When looping through dictionaries, the key and corresponding value can |
Raymond Hettinger | d446230 | 2003-11-26 17:52:45 +0000 | [diff] [blame] | 2171 | be retrieved at the same time using the \method{iteritems()} method. |
Fred Drake | 38f7197 | 2002-04-26 20:29:44 +0000 | [diff] [blame] | 2172 | |
| 2173 | \begin{verbatim} |
| 2174 | >>> knights = {'gallahad': 'the pure', 'robin': 'the brave'} |
Raymond Hettinger | d446230 | 2003-11-26 17:52:45 +0000 | [diff] [blame] | 2175 | >>> for k, v in knights.iteritems(): |
Fred Drake | 38f7197 | 2002-04-26 20:29:44 +0000 | [diff] [blame] | 2176 | ... print k, v |
| 2177 | ... |
| 2178 | gallahad the pure |
| 2179 | robin the brave |
| 2180 | \end{verbatim} |
| 2181 | |
| 2182 | When looping through a sequence, the position index and corresponding |
| 2183 | value can be retrieved at the same time using the |
| 2184 | \function{enumerate()} function. |
| 2185 | |
| 2186 | \begin{verbatim} |
| 2187 | >>> for i, v in enumerate(['tic', 'tac', 'toe']): |
| 2188 | ... print i, v |
| 2189 | ... |
| 2190 | 0 tic |
| 2191 | 1 tac |
| 2192 | 2 toe |
| 2193 | \end{verbatim} |
| 2194 | |
| 2195 | To loop over two or more sequences at the same time, the entries |
| 2196 | can be paired with the \function{zip()} function. |
| 2197 | |
| 2198 | \begin{verbatim} |
| 2199 | >>> questions = ['name', 'quest', 'favorite color'] |
| 2200 | >>> answers = ['lancelot', 'the holy grail', 'blue'] |
| 2201 | >>> for q, a in zip(questions, answers): |
| 2202 | ... print 'What is your %s? It is %s.' % (q, a) |
| 2203 | ... |
Raymond Hettinger | 7951f60 | 2002-06-25 03:17:03 +0000 | [diff] [blame] | 2204 | What is your name? It is lancelot. |
| 2205 | What is your quest? It is the holy grail. |
| 2206 | What is your favorite color? It is blue. |
Fred Drake | 38f7197 | 2002-04-26 20:29:44 +0000 | [diff] [blame] | 2207 | \end{verbatim} |
| 2208 | |
Raymond Hettinger | dc62aec | 2003-11-07 01:30:58 +0000 | [diff] [blame] | 2209 | To loop over a sequence in reverse, first specify the sequence |
| 2210 | in a forward direction and then call the \function{reversed()} |
| 2211 | function. |
| 2212 | |
| 2213 | \begin{verbatim} |
| 2214 | >>> for i in reversed(xrange(1,10,2)): |
| 2215 | ... print i |
| 2216 | ... |
| 2217 | 9 |
| 2218 | 7 |
| 2219 | 5 |
| 2220 | 3 |
| 2221 | 1 |
| 2222 | \end{verbatim} |
| 2223 | |
Raymond Hettinger | a95e87a | 2003-12-17 21:38:26 +0000 | [diff] [blame] | 2224 | To loop over a sequence in sorted order, use the \function{sorted()} |
| 2225 | function which returns a new sorted list while leaving the source |
| 2226 | unaltered. |
| 2227 | |
| 2228 | \begin{verbatim} |
| 2229 | >>> basket = ['apple', 'orange', 'apple', 'pear', 'orange', 'banana'] |
| 2230 | >>> for f in sorted(set(basket)): |
| 2231 | ... print f |
| 2232 | ... |
| 2233 | apple |
| 2234 | banana |
| 2235 | orange |
| 2236 | pear |
| 2237 | \end{verbatim} |
Fred Drake | 38f7197 | 2002-04-26 20:29:44 +0000 | [diff] [blame] | 2238 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2239 | \section{More on Conditions \label{conditions}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2240 | |
Johannes Gijsbers | 6ab4b99 | 2004-09-11 17:48:21 +0000 | [diff] [blame] | 2241 | The conditions used in \code{while} and \code{if} statements can |
| 2242 | contain any operators, not just comparisons. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2243 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2244 | The comparison operators \code{in} and \code{not in} check whether a value |
| 2245 | occurs (does not occur) in a sequence. The operators \code{is} and |
| 2246 | \code{is not} compare whether two objects are really the same object; this |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2247 | only matters for mutable objects like lists. All comparison operators |
| 2248 | have the same priority, which is lower than that of all numerical |
| 2249 | operators. |
| 2250 | |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2251 | Comparisons can be chained. For example, \code{a < b == c} tests |
| 2252 | whether \code{a} is less than \code{b} and moreover \code{b} equals |
| 2253 | \code{c}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2254 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2255 | Comparisons may be combined by the Boolean operators \code{and} and |
| 2256 | \code{or}, and the outcome of a comparison (or of any other Boolean |
Johannes Gijsbers | 6ab4b99 | 2004-09-11 17:48:21 +0000 | [diff] [blame] | 2257 | expression) may be negated with \code{not}. These have lower |
| 2258 | priorities than comparison operators; between them, \code{not} has |
| 2259 | the highest priority and \code{or} the lowest, so that |
| 2260 | \code{A and not B or C} is equivalent to \code{(A and (not B)) or C}. |
| 2261 | As always, parentheses can be used to express the desired composition. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2262 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2263 | The Boolean operators \code{and} and \code{or} are so-called |
Fred Drake | 6cb64f9 | 2002-03-08 00:54:43 +0000 | [diff] [blame] | 2264 | \emph{short-circuit} operators: their arguments are evaluated from |
| 2265 | left to right, and evaluation stops as soon as the outcome is |
| 2266 | determined. For example, if \code{A} and \code{C} are true but |
| 2267 | \code{B} is false, \code{A and B and C} does not evaluate the |
| 2268 | expression \code{C}. In general, the return value of a short-circuit |
| 2269 | operator, when used as a general value and not as a Boolean, is the |
| 2270 | last evaluated argument. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2271 | |
| 2272 | It is possible to assign the result of a comparison or other Boolean |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2273 | expression to a variable. For example, |
| 2274 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2275 | \begin{verbatim} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2276 | >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' |
| 2277 | >>> non_null = string1 or string2 or string3 |
| 2278 | >>> non_null |
| 2279 | 'Trondheim' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2280 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2281 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2282 | Note that in Python, unlike C, assignment cannot occur inside expressions. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2283 | C programmers may grumble about this, but it avoids a common class of |
| 2284 | problems encountered in C programs: typing \code{=} in an expression when |
| 2285 | \code{==} was intended. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2286 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2287 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2288 | \section{Comparing Sequences and Other Types \label{comparing}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2289 | |
| 2290 | Sequence objects may be compared to other objects with the same |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2291 | sequence type. The comparison uses \emph{lexicographical} ordering: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2292 | first the first two items are compared, and if they differ this |
| 2293 | determines the outcome of the comparison; if they are equal, the next |
| 2294 | two items are compared, and so on, until either sequence is exhausted. |
| 2295 | If two items to be compared are themselves sequences of the same type, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2296 | the lexicographical comparison is carried out recursively. If all |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2297 | items of two sequences compare equal, the sequences are considered |
Fred Drake | 979d041 | 2001-04-03 17:41:56 +0000 | [diff] [blame] | 2298 | equal. If one sequence is an initial sub-sequence of the other, the |
Fred Drake | 20c9491 | 2001-08-01 17:17:13 +0000 | [diff] [blame] | 2299 | shorter sequence is the smaller (lesser) one. Lexicographical |
| 2300 | ordering for strings uses the \ASCII{} ordering for individual |
| 2301 | characters. Some examples of comparisons between sequences with the |
| 2302 | same types: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2303 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2304 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2305 | (1, 2, 3) < (1, 2, 4) |
| 2306 | [1, 2, 3] < [1, 2, 4] |
| 2307 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 2308 | (1, 2, 3, 4) < (1, 2, 4) |
| 2309 | (1, 2) < (1, 2, -1) |
Fred Drake | 511281a | 1999-04-16 13:17:04 +0000 | [diff] [blame] | 2310 | (1, 2, 3) == (1.0, 2.0, 3.0) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2311 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2312 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2313 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2314 | Note that comparing objects of different types is legal. The outcome |
| 2315 | is deterministic but arbitrary: the types are ordered by their name. |
| 2316 | Thus, a list is always smaller than a string, a string is always |
Johannes Gijsbers | 6ab4b99 | 2004-09-11 17:48:21 +0000 | [diff] [blame] | 2317 | smaller than a tuple, etc. \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2318 | The rules for comparing objects of different types should |
| 2319 | not be relied upon; they may change in a future version of |
| 2320 | the language. |
Johannes Gijsbers | 6ab4b99 | 2004-09-11 17:48:21 +0000 | [diff] [blame] | 2321 | } Mixed numeric types are compared according to their numeric value, so |
| 2322 | 0 equals 0.0, etc. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2323 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2324 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2325 | \chapter{Modules \label{modules}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2326 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2327 | If you quit from the Python interpreter and enter it again, the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2328 | definitions you have made (functions and variables) are lost. |
| 2329 | Therefore, if you want to write a somewhat longer program, you are |
| 2330 | better off using a text editor to prepare the input for the interpreter |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2331 | and running it with that file as input instead. This is known as creating a |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2332 | \emph{script}. As your program gets longer, you may want to split it |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2333 | into several files for easier maintenance. You may also want to use a |
| 2334 | handy function that you've written in several programs without copying |
| 2335 | its definition into each program. |
| 2336 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2337 | To support this, Python has a way to put definitions in a file and use |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2338 | them in a script or in an interactive instance of the interpreter. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2339 | Such a file is called a \emph{module}; definitions from a module can be |
| 2340 | \emph{imported} into other modules or into the \emph{main} module (the |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2341 | collection of variables that you have access to in a script |
| 2342 | executed at the top level |
| 2343 | and in calculator mode). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2344 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2345 | A module is a file containing Python definitions and statements. The |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2346 | file name is the module name with the suffix \file{.py} appended. Within |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2347 | a module, the module's name (as a string) is available as the value of |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2348 | the global variable \code{__name__}. For instance, use your favorite text |
| 2349 | editor to create a file called \file{fibo.py} in the current directory |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2350 | with the following contents: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2351 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2352 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2353 | # Fibonacci numbers module |
| 2354 | |
| 2355 | def fib(n): # write Fibonacci series up to n |
| 2356 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 2357 | while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2358 | print b, |
| 2359 | a, b = b, a+b |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2360 | |
| 2361 | def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2362 | result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2363 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 2364 | while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2365 | result.append(b) |
| 2366 | a, b = b, a+b |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2367 | return result |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2368 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2369 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2370 | Now enter the Python interpreter and import this module with the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2371 | following command: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2372 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2373 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2374 | >>> import fibo |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2375 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2376 | |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 2377 | This does not enter the names of the functions defined in \code{fibo} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2378 | directly in the current symbol table; it only enters the module name |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 2379 | \code{fibo} there. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2380 | Using the module name you can access the functions: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2381 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2382 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2383 | >>> fibo.fib(1000) |
| 2384 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 2385 | >>> fibo.fib2(100) |
| 2386 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2387 | >>> fibo.__name__ |
| 2388 | 'fibo' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2389 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2390 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2391 | If you intend to use a function often you can assign it to a local name: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2392 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2393 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2394 | >>> fib = fibo.fib |
| 2395 | >>> fib(500) |
| 2396 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2397 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2398 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2399 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2400 | \section{More on Modules \label{moreModules}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2401 | |
| 2402 | A module can contain executable statements as well as function |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2403 | definitions. |
| 2404 | These statements are intended to initialize the module. |
| 2405 | They are executed only the |
| 2406 | \emph{first} time the module is imported somewhere.\footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2407 | In fact function definitions are also `statements' that are |
| 2408 | `executed'; the execution enters the function name in the |
| 2409 | module's global symbol table. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2410 | } |
| 2411 | |
| 2412 | Each module has its own private symbol table, which is used as the |
| 2413 | global symbol table by all functions defined in the module. |
| 2414 | Thus, the author of a module can use global variables in the module |
| 2415 | without worrying about accidental clashes with a user's global |
| 2416 | variables. |
| 2417 | On the other hand, if you know what you are doing you can touch a |
| 2418 | module's global variables with the same notation used to refer to its |
| 2419 | functions, |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2420 | \code{modname.itemname}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2421 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2422 | Modules can import other modules. It is customary but not required to |
| 2423 | place all \keyword{import} statements at the beginning of a module (or |
| 2424 | script, for that matter). The imported module names are placed in the |
| 2425 | importing module's global symbol table. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2426 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2427 | There is a variant of the \keyword{import} statement that imports |
| 2428 | names from a module directly into the importing module's symbol |
| 2429 | table. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2430 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2431 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2432 | >>> from fibo import fib, fib2 |
| 2433 | >>> fib(500) |
| 2434 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2435 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2436 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2437 | This does not introduce the module name from which the imports are taken |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2438 | in the local symbol table (so in the example, \code{fibo} is not |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2439 | defined). |
| 2440 | |
| 2441 | There is even a variant to import all names that a module defines: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2442 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2443 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2444 | >>> from fibo import * |
| 2445 | >>> fib(500) |
| 2446 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2447 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2448 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2449 | This imports all names except those beginning with an underscore |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2450 | (\code{_}). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2451 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2452 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2453 | \subsection{The Module Search Path \label{searchPath}} |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 2454 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2455 | \indexiii{module}{search}{path} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2456 | When a module named \module{spam} is imported, the interpreter searches |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2457 | for a file named \file{spam.py} in the current directory, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2458 | and then in the list of directories specified by |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2459 | the environment variable \envvar{PYTHONPATH}. This has the same syntax as |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2460 | the shell variable \envvar{PATH}, that is, a list of |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2461 | directory names. When \envvar{PYTHONPATH} is not set, or when the file |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2462 | is not found there, the search continues in an installation-dependent |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 2463 | default path; on \UNIX, this is usually \file{.:/usr/local/lib/python}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2464 | |
| 2465 | Actually, modules are searched in the list of directories given by the |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2466 | variable \code{sys.path} which is initialized from the directory |
| 2467 | containing the input script (or the current directory), |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2468 | \envvar{PYTHONPATH} and the installation-dependent default. This allows |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2469 | Python programs that know what they're doing to modify or replace the |
Fred Drake | ecd8157 | 2001-12-04 19:47:46 +0000 | [diff] [blame] | 2470 | module search path. Note that because the directory containing the |
| 2471 | script being run is on the search path, it is important that the |
| 2472 | script not have the same name as a standard module, or Python will |
| 2473 | attempt to load the script as a module when that module is imported. |
| 2474 | This will generally be an error. See section~\ref{standardModules}, |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 2475 | ``Standard Modules,'' for more information. |
Fred Drake | ecd8157 | 2001-12-04 19:47:46 +0000 | [diff] [blame] | 2476 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2477 | |
| 2478 | \subsection{``Compiled'' Python files} |
| 2479 | |
| 2480 | As an important speed-up of the start-up time for short programs that |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2481 | use a lot of standard modules, if a file called \file{spam.pyc} exists |
| 2482 | in the directory where \file{spam.py} is found, this is assumed to |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2483 | contain an already-``byte-compiled'' version of the module \module{spam}. |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2484 | The modification time of the version of \file{spam.py} used to create |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2485 | \file{spam.pyc} is recorded in \file{spam.pyc}, and the |
| 2486 | \file{.pyc} file is ignored if these don't match. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2487 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2488 | Normally, you don't need to do anything to create the |
| 2489 | \file{spam.pyc} file. Whenever \file{spam.py} is successfully |
| 2490 | compiled, an attempt is made to write the compiled version to |
| 2491 | \file{spam.pyc}. It is not an error if this attempt fails; if for any |
| 2492 | reason the file is not written completely, the resulting |
| 2493 | \file{spam.pyc} file will be recognized as invalid and thus ignored |
| 2494 | later. The contents of the \file{spam.pyc} file are platform |
| 2495 | independent, so a Python module directory can be shared by machines of |
| 2496 | different architectures. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2497 | |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2498 | Some tips for experts: |
| 2499 | |
| 2500 | \begin{itemize} |
| 2501 | |
| 2502 | \item |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2503 | When the Python interpreter is invoked with the \programopt{-O} flag, |
Michael W. Hudson | dd32a91 | 2002-08-15 14:59:02 +0000 | [diff] [blame] | 2504 | optimized code is generated and stored in \file{.pyo} files. The |
| 2505 | optimizer currently doesn't help much; it only removes |
| 2506 | \keyword{assert} statements. When \programopt{-O} is used, \emph{all} |
| 2507 | bytecode is optimized; \code{.pyc} files are ignored and \code{.py} |
| 2508 | files are compiled to optimized bytecode. |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2509 | |
| 2510 | \item |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2511 | Passing two \programopt{-O} flags to the Python interpreter |
| 2512 | (\programopt{-OO}) will cause the bytecode compiler to perform |
| 2513 | optimizations that could in some rare cases result in malfunctioning |
| 2514 | programs. Currently only \code{__doc__} strings are removed from the |
| 2515 | bytecode, resulting in more compact \file{.pyo} files. Since some |
| 2516 | programs may rely on having these available, you should only use this |
| 2517 | option if you know what you're doing. |
Guido van Rossum | 6b86a42 | 1999-01-28 15:07:47 +0000 | [diff] [blame] | 2518 | |
| 2519 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2520 | A program doesn't run any faster when it is read from a \file{.pyc} or |
| 2521 | \file{.pyo} file than when it is read from a \file{.py} file; the only |
| 2522 | thing that's faster about \file{.pyc} or \file{.pyo} files is the |
| 2523 | speed with which they are loaded. |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2524 | |
| 2525 | \item |
Guido van Rossum | 002f7aa | 1998-06-28 19:16:38 +0000 | [diff] [blame] | 2526 | When a script is run by giving its name on the command line, the |
| 2527 | bytecode for the script is never written to a \file{.pyc} or |
| 2528 | \file{.pyo} file. Thus, the startup time of a script may be reduced |
| 2529 | by moving most of its code to a module and having a small bootstrap |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2530 | script that imports that module. It is also possible to name a |
| 2531 | \file{.pyc} or \file{.pyo} file directly on the command line. |
Guido van Rossum | 002f7aa | 1998-06-28 19:16:38 +0000 | [diff] [blame] | 2532 | |
| 2533 | \item |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2534 | It is possible to have a file called \file{spam.pyc} (or |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2535 | \file{spam.pyo} when \programopt{-O} is used) without a file |
| 2536 | \file{spam.py} for the same module. This can be used to distribute a |
| 2537 | library of Python code in a form that is moderately hard to reverse |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2538 | engineer. |
| 2539 | |
| 2540 | \item |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 2541 | The module \ulink{\module{compileall}}{../lib/module-compileall.html}% |
| 2542 | {} \refstmodindex{compileall} can create \file{.pyc} files (or |
| 2543 | \file{.pyo} files when \programopt{-O} is used) for all modules in a |
| 2544 | directory. |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2545 | |
| 2546 | \end{itemize} |
| 2547 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2548 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2549 | \section{Standard Modules \label{standardModules}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2550 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2551 | Python comes with a library of standard modules, described in a separate |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2552 | document, the \citetitle[../lib/lib.html]{Python Library Reference} |
| 2553 | (``Library Reference'' hereafter). Some modules are built into the |
| 2554 | interpreter; these provide access to operations that are not part of |
| 2555 | the core of the language but are nevertheless built in, either for |
| 2556 | efficiency or to provide access to operating system primitives such as |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2557 | system calls. The set of such modules is a configuration option which |
Martin v. Löwis | 95cf84a | 2003-10-19 07:32:24 +0000 | [diff] [blame] | 2558 | also depends on the underlying platform For example, |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2559 | the \module{amoeba} module is only provided on systems that somehow |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2560 | support Amoeba primitives. One particular module deserves some |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 2561 | attention: \ulink{\module{sys}}{../lib/module-sys.html}% |
| 2562 | \refstmodindex{sys}, which is built into every |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2563 | Python interpreter. The variables \code{sys.ps1} and |
| 2564 | \code{sys.ps2} define the strings used as primary and secondary |
| 2565 | prompts: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2566 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2567 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2568 | >>> import sys |
| 2569 | >>> sys.ps1 |
| 2570 | '>>> ' |
| 2571 | >>> sys.ps2 |
| 2572 | '... ' |
| 2573 | >>> sys.ps1 = 'C> ' |
| 2574 | C> print 'Yuck!' |
| 2575 | Yuck! |
Raymond Hettinger | a02469f | 2003-05-07 17:49:36 +0000 | [diff] [blame] | 2576 | C> |
| 2577 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2578 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2579 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2580 | These two variables are only defined if the interpreter is in |
| 2581 | interactive mode. |
| 2582 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2583 | The variable \code{sys.path} is a list of strings that determine the |
| 2584 | interpreter's search path for modules. It is initialized to a default |
| 2585 | path taken from the environment variable \envvar{PYTHONPATH}, or from |
| 2586 | a built-in default if \envvar{PYTHONPATH} is not set. You can modify |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2587 | it using standard list operations: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2588 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2589 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2590 | >>> import sys |
| 2591 | >>> sys.path.append('/ufs/guido/lib/python') |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2592 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2593 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2594 | \section{The \function{dir()} Function \label{dir}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2595 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2596 | The built-in function \function{dir()} is used to find out which names |
| 2597 | a module defines. It returns a sorted list of strings: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2598 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2599 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2600 | >>> import fibo, sys |
| 2601 | >>> dir(fibo) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2602 | ['__name__', 'fib', 'fib2'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2603 | >>> dir(sys) |
Fred Drake | ecd8157 | 2001-12-04 19:47:46 +0000 | [diff] [blame] | 2604 | ['__displayhook__', '__doc__', '__excepthook__', '__name__', '__stderr__', |
Guido van Rossum | 46d3dc3 | 2003-03-01 03:20:41 +0000 | [diff] [blame] | 2605 | '__stdin__', '__stdout__', '_getframe', 'api_version', 'argv', |
| 2606 | 'builtin_module_names', 'byteorder', 'callstats', 'copyright', |
| 2607 | 'displayhook', 'exc_clear', 'exc_info', 'exc_type', 'excepthook', |
| 2608 | 'exec_prefix', 'executable', 'exit', 'getdefaultencoding', 'getdlopenflags', |
| 2609 | 'getrecursionlimit', 'getrefcount', 'hexversion', 'maxint', 'maxunicode', |
| 2610 | 'meta_path', 'modules', 'path', 'path_hooks', 'path_importer_cache', |
| 2611 | 'platform', 'prefix', 'ps1', 'ps2', 'setcheckinterval', 'setdlopenflags', |
| 2612 | 'setprofile', 'setrecursionlimit', 'settrace', 'stderr', 'stdin', 'stdout', |
| 2613 | 'version', 'version_info', 'warnoptions'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2614 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2615 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2616 | Without arguments, \function{dir()} lists the names you have defined |
| 2617 | currently: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2618 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2619 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2620 | >>> a = [1, 2, 3, 4, 5] |
| 2621 | >>> import fibo, sys |
| 2622 | >>> fib = fibo.fib |
| 2623 | >>> dir() |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2624 | ['__name__', 'a', 'fib', 'fibo', 'sys'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2625 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2626 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2627 | Note that it lists all types of names: variables, modules, functions, etc. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2628 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2629 | \function{dir()} does not list the names of built-in functions and |
| 2630 | variables. If you want a list of those, they are defined in the |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2631 | standard module \module{__builtin__}\refbimodindex{__builtin__}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2632 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2633 | \begin{verbatim} |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 2634 | >>> import __builtin__ |
| 2635 | >>> dir(__builtin__) |
Fred Drake | ecd8157 | 2001-12-04 19:47:46 +0000 | [diff] [blame] | 2636 | ['ArithmeticError', 'AssertionError', 'AttributeError', |
| 2637 | 'DeprecationWarning', 'EOFError', 'Ellipsis', 'EnvironmentError', |
Neal Norwitz | d68f517 | 2002-05-29 15:54:55 +0000 | [diff] [blame] | 2638 | 'Exception', 'False', 'FloatingPointError', 'IOError', 'ImportError', |
Fred Drake | ecd8157 | 2001-12-04 19:47:46 +0000 | [diff] [blame] | 2639 | 'IndentationError', 'IndexError', 'KeyError', 'KeyboardInterrupt', |
| 2640 | 'LookupError', 'MemoryError', 'NameError', 'None', 'NotImplemented', |
| 2641 | 'NotImplementedError', 'OSError', 'OverflowError', 'OverflowWarning', |
Neal Norwitz | d68f517 | 2002-05-29 15:54:55 +0000 | [diff] [blame] | 2642 | 'PendingDeprecationWarning', 'ReferenceError', |
| 2643 | 'RuntimeError', 'RuntimeWarning', 'StandardError', 'StopIteration', |
| 2644 | 'SyntaxError', 'SyntaxWarning', 'SystemError', 'SystemExit', 'TabError', |
| 2645 | 'True', 'TypeError', 'UnboundLocalError', 'UnicodeError', 'UserWarning', |
| 2646 | 'ValueError', 'Warning', 'ZeroDivisionError', '__debug__', '__doc__', |
| 2647 | '__import__', '__name__', 'abs', 'apply', 'bool', 'buffer', |
| 2648 | 'callable', 'chr', 'classmethod', 'cmp', 'coerce', 'compile', 'complex', |
| 2649 | 'copyright', 'credits', 'delattr', 'dict', 'dir', 'divmod', |
| 2650 | 'enumerate', 'eval', 'execfile', 'exit', 'file', 'filter', 'float', |
| 2651 | 'getattr', 'globals', 'hasattr', 'hash', 'help', 'hex', 'id', |
| 2652 | 'input', 'int', 'intern', 'isinstance', 'issubclass', 'iter', |
| 2653 | 'len', 'license', 'list', 'locals', 'long', 'map', 'max', 'min', |
| 2654 | 'object', 'oct', 'open', 'ord', 'pow', 'property', 'quit', |
| 2655 | 'range', 'raw_input', 'reduce', 'reload', 'repr', 'round', |
Alex Martelli | a70b191 | 2003-04-22 08:12:33 +0000 | [diff] [blame] | 2656 | 'setattr', 'slice', 'staticmethod', 'str', 'string', 'sum', 'super', |
Neal Norwitz | d68f517 | 2002-05-29 15:54:55 +0000 | [diff] [blame] | 2657 | 'tuple', 'type', 'unichr', 'unicode', 'vars', 'xrange', 'zip'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2658 | \end{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2659 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2660 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2661 | \section{Packages \label{packages}} |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2662 | |
| 2663 | Packages are a way of structuring Python's module namespace |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2664 | by using ``dotted module names''. For example, the module name |
| 2665 | \module{A.B} designates a submodule named \samp{B} in a package named |
| 2666 | \samp{A}. Just like the use of modules saves the authors of different |
| 2667 | modules from having to worry about each other's global variable names, |
| 2668 | the use of dotted module names saves the authors of multi-module |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2669 | packages like NumPy or the Python Imaging Library from having to worry |
| 2670 | about each other's module names. |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2671 | |
| 2672 | Suppose you want to design a collection of modules (a ``package'') for |
| 2673 | the uniform handling of sound files and sound data. There are many |
| 2674 | different sound file formats (usually recognized by their extension, |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2675 | for example: \file{.wav}, \file{.aiff}, \file{.au}), so you may need |
| 2676 | to create and maintain a growing collection of modules for the |
| 2677 | conversion between the various file formats. There are also many |
| 2678 | different operations you might want to perform on sound data (such as |
| 2679 | mixing, adding echo, applying an equalizer function, creating an |
| 2680 | artificial stereo effect), so in addition you will be writing a |
| 2681 | never-ending stream of modules to perform these operations. Here's a |
| 2682 | possible structure for your package (expressed in terms of a |
| 2683 | hierarchical filesystem): |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2684 | |
| 2685 | \begin{verbatim} |
| 2686 | Sound/ Top-level package |
| 2687 | __init__.py Initialize the sound package |
| 2688 | Formats/ Subpackage for file format conversions |
| 2689 | __init__.py |
| 2690 | wavread.py |
| 2691 | wavwrite.py |
| 2692 | aiffread.py |
| 2693 | aiffwrite.py |
| 2694 | auread.py |
| 2695 | auwrite.py |
| 2696 | ... |
| 2697 | Effects/ Subpackage for sound effects |
| 2698 | __init__.py |
| 2699 | echo.py |
| 2700 | surround.py |
| 2701 | reverse.py |
| 2702 | ... |
| 2703 | Filters/ Subpackage for filters |
| 2704 | __init__.py |
| 2705 | equalizer.py |
| 2706 | vocoder.py |
| 2707 | karaoke.py |
| 2708 | ... |
| 2709 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2710 | |
Martin v. Löwis | 95cf84a | 2003-10-19 07:32:24 +0000 | [diff] [blame] | 2711 | When importing the package, Python searches through the directories |
Raymond Hettinger | 7fbd012 | 2002-10-26 03:13:57 +0000 | [diff] [blame] | 2712 | on \code{sys.path} looking for the package subdirectory. |
| 2713 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2714 | The \file{__init__.py} files are required to make Python treat the |
| 2715 | directories as containing packages; this is done to prevent |
| 2716 | directories with a common name, such as \samp{string}, from |
| 2717 | unintentionally hiding valid modules that occur later on the module |
| 2718 | search path. In the simplest case, \file{__init__.py} can just be an |
| 2719 | empty file, but it can also execute initialization code for the |
| 2720 | package or set the \code{__all__} variable, described later. |
| 2721 | |
| 2722 | Users of the package can import individual modules from the |
| 2723 | package, for example: |
| 2724 | |
| 2725 | \begin{verbatim} |
| 2726 | import Sound.Effects.echo |
| 2727 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2728 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2729 | This loads the submodule \module{Sound.Effects.echo}. It must be referenced |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2730 | with its full name. |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2731 | |
| 2732 | \begin{verbatim} |
| 2733 | Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4) |
| 2734 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2735 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2736 | An alternative way of importing the submodule is: |
| 2737 | |
| 2738 | \begin{verbatim} |
| 2739 | from Sound.Effects import echo |
| 2740 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2741 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2742 | This also loads the submodule \module{echo}, and makes it available without |
| 2743 | its package prefix, so it can be used as follows: |
| 2744 | |
| 2745 | \begin{verbatim} |
| 2746 | echo.echofilter(input, output, delay=0.7, atten=4) |
| 2747 | \end{verbatim} |
| 2748 | |
| 2749 | Yet another variation is to import the desired function or variable directly: |
| 2750 | |
| 2751 | \begin{verbatim} |
| 2752 | from Sound.Effects.echo import echofilter |
| 2753 | \end{verbatim} |
| 2754 | |
| 2755 | Again, this loads the submodule \module{echo}, but this makes its function |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2756 | \function{echofilter()} directly available: |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2757 | |
| 2758 | \begin{verbatim} |
| 2759 | echofilter(input, output, delay=0.7, atten=4) |
| 2760 | \end{verbatim} |
| 2761 | |
| 2762 | Note that when using \code{from \var{package} import \var{item}}, the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2763 | item can be either a submodule (or subpackage) of the package, or some |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2764 | other name defined in the package, like a function, class or |
| 2765 | variable. The \code{import} statement first tests whether the item is |
| 2766 | defined in the package; if not, it assumes it is a module and attempts |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2767 | to load it. If it fails to find it, an |
| 2768 | \exception{ImportError} exception is raised. |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2769 | |
| 2770 | Contrarily, when using syntax like \code{import |
| 2771 | \var{item.subitem.subsubitem}}, each item except for the last must be |
| 2772 | a package; the last item can be a module or a package but can't be a |
| 2773 | class or function or variable defined in the previous item. |
| 2774 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2775 | \subsection{Importing * From a Package \label{pkg-import-star}} |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2776 | %The \code{__all__} Attribute |
Fred Drake | 830d8b8 | 2004-08-09 14:06:58 +0000 | [diff] [blame] | 2777 | |
| 2778 | \ttindex{__all__} |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2779 | Now what happens when the user writes \code{from Sound.Effects import |
| 2780 | *}? Ideally, one would hope that this somehow goes out to the |
| 2781 | filesystem, finds which submodules are present in the package, and |
| 2782 | imports them all. Unfortunately, this operation does not work very |
| 2783 | well on Mac and Windows platforms, where the filesystem does not |
| 2784 | always have accurate information about the case of a filename! On |
| 2785 | these platforms, there is no guaranteed way to know whether a file |
| 2786 | \file{ECHO.PY} should be imported as a module \module{echo}, |
| 2787 | \module{Echo} or \module{ECHO}. (For example, Windows 95 has the |
| 2788 | annoying practice of showing all file names with a capitalized first |
| 2789 | letter.) The DOS 8+3 filename restriction adds another interesting |
| 2790 | problem for long module names. |
| 2791 | |
| 2792 | The only solution is for the package author to provide an explicit |
| 2793 | index of the package. The import statement uses the following |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2794 | convention: if a package's \file{__init__.py} code defines a list |
| 2795 | named \code{__all__}, it is taken to be the list of module names that |
| 2796 | should be imported when \code{from \var{package} import *} is |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2797 | encountered. It is up to the package author to keep this list |
| 2798 | up-to-date when a new version of the package is released. Package |
| 2799 | authors may also decide not to support it, if they don't see a use for |
| 2800 | importing * from their package. For example, the file |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2801 | \file{Sounds/Effects/__init__.py} could contain the following code: |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2802 | |
| 2803 | \begin{verbatim} |
| 2804 | __all__ = ["echo", "surround", "reverse"] |
| 2805 | \end{verbatim} |
| 2806 | |
| 2807 | This would mean that \code{from Sound.Effects import *} would |
| 2808 | import the three named submodules of the \module{Sound} package. |
| 2809 | |
| 2810 | If \code{__all__} is not defined, the statement \code{from Sound.Effects |
| 2811 | import *} does \emph{not} import all submodules from the package |
| 2812 | \module{Sound.Effects} into the current namespace; it only ensures that the |
| 2813 | package \module{Sound.Effects} has been imported (possibly running its |
| 2814 | initialization code, \file{__init__.py}) and then imports whatever names are |
| 2815 | defined in the package. This includes any names defined (and |
| 2816 | submodules explicitly loaded) by \file{__init__.py}. It also includes any |
| 2817 | submodules of the package that were explicitly loaded by previous |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 2818 | import statements. Consider this code: |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2819 | |
| 2820 | \begin{verbatim} |
| 2821 | import Sound.Effects.echo |
| 2822 | import Sound.Effects.surround |
| 2823 | from Sound.Effects import * |
| 2824 | \end{verbatim} |
| 2825 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2826 | In this example, the echo and surround modules are imported in the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2827 | current namespace because they are defined in the |
| 2828 | \module{Sound.Effects} package when the \code{from...import} statement |
| 2829 | is executed. (This also works when \code{__all__} is defined.) |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2830 | |
Fred Drake | 55803bc | 2002-10-22 21:00:44 +0000 | [diff] [blame] | 2831 | Note that in general the practice of importing \code{*} from a module or |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2832 | package is frowned upon, since it often causes poorly readable code. |
| 2833 | However, it is okay to use it to save typing in interactive sessions, |
| 2834 | and certain modules are designed to export only names that follow |
| 2835 | certain patterns. |
| 2836 | |
| 2837 | Remember, there is nothing wrong with using \code{from Package |
| 2838 | import specific_submodule}! In fact, this is the |
| 2839 | recommended notation unless the importing module needs to use |
| 2840 | submodules with the same name from different packages. |
| 2841 | |
| 2842 | |
| 2843 | \subsection{Intra-package References} |
| 2844 | |
| 2845 | The submodules often need to refer to each other. For example, the |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 2846 | \module{surround} module might use the \module{echo} module. In fact, |
| 2847 | such references |
| 2848 | are so common that the \keyword{import} statement first looks in the |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2849 | containing package before looking in the standard module search path. |
| 2850 | Thus, the surround module can simply use \code{import echo} or |
| 2851 | \code{from echo import echofilter}. If the imported module is not |
| 2852 | found in the current package (the package of which the current module |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 2853 | is a submodule), the \keyword{import} statement looks for a top-level |
| 2854 | module with the given name. |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2855 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2856 | When packages are structured into subpackages (as with the |
| 2857 | \module{Sound} package in the example), there's no shortcut to refer |
| 2858 | to submodules of sibling packages - the full name of the subpackage |
| 2859 | must be used. For example, if the module |
| 2860 | \module{Sound.Filters.vocoder} needs to use the \module{echo} module |
| 2861 | in the \module{Sound.Effects} package, it can use \code{from |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2862 | Sound.Effects import echo}. |
| 2863 | |
Fred Drake | 55803bc | 2002-10-22 21:00:44 +0000 | [diff] [blame] | 2864 | \subsection{Packages in Multiple Directories} |
| 2865 | |
| 2866 | Packages support one more special attribute, \member{__path__}. This |
| 2867 | is initialized to be a list containing the name of the directory |
| 2868 | holding the package's \file{__init__.py} before the code in that file |
| 2869 | is executed. This variable can be modified; doing so affects future |
| 2870 | searches for modules and subpackages contained in the package. |
| 2871 | |
| 2872 | While this feature is not often needed, it can be used to extend the |
| 2873 | set of modules found in a package. |
| 2874 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2875 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2876 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2877 | \chapter{Input and Output \label{io}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2878 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2879 | There are several ways to present the output of a program; data can be |
| 2880 | printed in a human-readable form, or written to a file for future use. |
| 2881 | This chapter will discuss some of the possibilities. |
| 2882 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2883 | |
| 2884 | \section{Fancier Output Formatting \label{formatting}} |
| 2885 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2886 | So far we've encountered two ways of writing values: \emph{expression |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2887 | statements} and the \keyword{print} statement. (A third way is using |
| 2888 | the \method{write()} method of file objects; the standard output file |
| 2889 | can be referenced as \code{sys.stdout}. See the Library Reference for |
| 2890 | more information on this.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2891 | |
| 2892 | Often you'll want more control over the formatting of your output than |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2893 | simply printing space-separated values. There are two ways to format |
| 2894 | your output; the first way is to do all the string handling yourself; |
| 2895 | using string slicing and concatenation operations you can create any |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2896 | lay-out you can imagine. The standard module |
| 2897 | \module{string}\refstmodindex{string} contains some useful operations |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2898 | for padding strings to a given column width; these will be discussed |
| 2899 | shortly. The second way is to use the \code{\%} operator with a |
| 2900 | string as the left argument. The \code{\%} operator interprets the |
Fred Drake | cc97f8c | 2001-01-01 20:33:06 +0000 | [diff] [blame] | 2901 | left argument much like a \cfunction{sprintf()}-style format |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2902 | string to be applied to the right argument, and returns the string |
| 2903 | resulting from this formatting operation. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2904 | |
| 2905 | One question remains, of course: how do you convert values to strings? |
Fred Drake | 6016dbe | 2001-12-04 19:20:43 +0000 | [diff] [blame] | 2906 | Luckily, Python has ways to convert any value to a string: pass it to |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2907 | the \function{repr()} or \function{str()} functions. Reverse quotes |
| 2908 | (\code{``}) are equivalent to \function{repr()}, but their use is |
| 2909 | discouraged. |
Fred Drake | 6016dbe | 2001-12-04 19:20:43 +0000 | [diff] [blame] | 2910 | |
| 2911 | The \function{str()} function is meant to return representations of |
| 2912 | values which are fairly human-readable, while \function{repr()} is |
| 2913 | meant to generate representations which can be read by the interpreter |
| 2914 | (or will force a \exception{SyntaxError} if there is not equivalent |
| 2915 | syntax). For objects which don't have a particular representation for |
| 2916 | human consumption, \function{str()} will return the same value as |
| 2917 | \function{repr()}. Many values, such as numbers or structures like |
| 2918 | lists and dictionaries, have the same representation using either |
| 2919 | function. Strings and floating point numbers, in particular, have two |
| 2920 | distinct representations. |
| 2921 | |
| 2922 | Some examples: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2923 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2924 | \begin{verbatim} |
Fred Drake | 6016dbe | 2001-12-04 19:20:43 +0000 | [diff] [blame] | 2925 | >>> s = 'Hello, world.' |
| 2926 | >>> str(s) |
| 2927 | 'Hello, world.' |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2928 | >>> repr(s) |
Fred Drake | 6016dbe | 2001-12-04 19:20:43 +0000 | [diff] [blame] | 2929 | "'Hello, world.'" |
| 2930 | >>> str(0.1) |
| 2931 | '0.1' |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2932 | >>> repr(0.1) |
Fred Drake | 6016dbe | 2001-12-04 19:20:43 +0000 | [diff] [blame] | 2933 | '0.10000000000000001' |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 2934 | >>> x = 10 * 3.25 |
Fred Drake | 8b0b840 | 2001-05-21 16:55:39 +0000 | [diff] [blame] | 2935 | >>> y = 200 * 200 |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2936 | >>> s = 'The value of x is ' + repr(x) + ', and y is ' + repr(y) + '...' |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2937 | >>> print s |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 2938 | The value of x is 32.5, and y is 40000... |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2939 | >>> # The repr() of a string adds string quotes and backslashes: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2940 | ... hello = 'hello, world\n' |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2941 | >>> hellos = repr(hello) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2942 | >>> print hellos |
Fred Drake | 0c14961 | 2001-04-12 04:26:24 +0000 | [diff] [blame] | 2943 | 'hello, world\n' |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2944 | >>> # The argument to repr() may be any Python object: |
Skip Montanaro | 45a9c93 | 2003-05-07 16:01:43 +0000 | [diff] [blame] | 2945 | ... repr((x, y, ('spam', 'eggs'))) |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 2946 | "(32.5, 40000, ('spam', 'eggs'))" |
| 2947 | >>> # reverse quotes are convenient in interactive sessions: |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2948 | ... `x, y, ('spam', 'eggs')` |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 2949 | "(32.5, 40000, ('spam', 'eggs'))" |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2950 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2951 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2952 | Here are two ways to write a table of squares and cubes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2953 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2954 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2955 | >>> for x in range(1, 11): |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2956 | ... print repr(x).rjust(2), repr(x*x).rjust(3), |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2957 | ... # Note trailing comma on previous line |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2958 | ... print repr(x*x*x).rjust(4) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2959 | ... |
| 2960 | 1 1 1 |
| 2961 | 2 4 8 |
| 2962 | 3 9 27 |
| 2963 | 4 16 64 |
| 2964 | 5 25 125 |
| 2965 | 6 36 216 |
| 2966 | 7 49 343 |
| 2967 | 8 64 512 |
| 2968 | 9 81 729 |
| 2969 | 10 100 1000 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2970 | >>> for x in range(1,11): |
| 2971 | ... print '%2d %3d %4d' % (x, x*x, x*x*x) |
| 2972 | ... |
| 2973 | 1 1 1 |
| 2974 | 2 4 8 |
| 2975 | 3 9 27 |
| 2976 | 4 16 64 |
| 2977 | 5 25 125 |
| 2978 | 6 36 216 |
| 2979 | 7 49 343 |
| 2980 | 8 64 512 |
| 2981 | 9 81 729 |
| 2982 | 10 100 1000 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2983 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2984 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2985 | (Note that one space between each column was added by the way |
| 2986 | \keyword{print} works: it always adds spaces between its arguments.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2987 | |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2988 | This example demonstrates the \method{rjust()} method of string objects, |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2989 | which right-justifies a string in a field of a given width by padding |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2990 | it with spaces on the left. There are similar methods |
| 2991 | \method{ljust()} and \method{center()}. These |
| 2992 | methods do not write anything, they just return a new string. If |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2993 | the input string is too long, they don't truncate it, but return it |
| 2994 | unchanged; this will mess up your column lay-out but that's usually |
| 2995 | better than the alternative, which would be lying about a value. (If |
| 2996 | you really want truncation you can always add a slice operation, as in |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2997 | \samp{x.ljust(~n)[:n]}.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2998 | |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 2999 | There is another method, \method{zfill()}, which pads a |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3000 | numeric string on the left with zeros. It understands about plus and |
| 3001 | minus signs: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3002 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3003 | \begin{verbatim} |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 3004 | >>> '12'.zfill(5) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3005 | '00012' |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 3006 | >>> '-3.14'.zfill(7) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3007 | '-003.14' |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 3008 | >>> '3.14159265359'.zfill(5) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3009 | '3.14159265359' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3010 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 3011 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3012 | Using the \code{\%} operator looks like this: |
| 3013 | |
| 3014 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3015 | >>> import math |
| 3016 | >>> print 'The value of PI is approximately %5.3f.' % math.pi |
| 3017 | The value of PI is approximately 3.142. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3018 | \end{verbatim} |
| 3019 | |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 3020 | If there is more than one format in the string, you need to pass a |
| 3021 | tuple as right operand, as in this example: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3022 | |
| 3023 | \begin{verbatim} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3024 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3025 | >>> for name, phone in table.items(): |
| 3026 | ... print '%-10s ==> %10d' % (name, phone) |
| 3027 | ... |
| 3028 | Jack ==> 4098 |
Fred Drake | 69fbf33 | 2000-04-04 19:53:06 +0000 | [diff] [blame] | 3029 | Dcab ==> 7678 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3030 | Sjoerd ==> 4127 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3031 | \end{verbatim} |
| 3032 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3033 | Most formats work exactly as in C and require that you pass the proper |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3034 | type; however, if you don't you get an exception, not a core dump. |
Fred Drake | db70d06 | 1998-11-17 21:59:04 +0000 | [diff] [blame] | 3035 | The \code{\%s} format is more relaxed: if the corresponding argument is |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3036 | not a string object, it is converted to string using the |
| 3037 | \function{str()} built-in function. Using \code{*} to pass the width |
| 3038 | or precision in as a separate (integer) argument is supported. The |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3039 | C formats \code{\%n} and \code{\%p} are not supported. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3040 | |
| 3041 | If you have a really long format string that you don't want to split |
| 3042 | up, it would be nice if you could reference the variables to be |
| 3043 | formatted by name instead of by position. This can be done by using |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 3044 | form \code{\%(name)format}, as shown here: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3045 | |
| 3046 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3047 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
| 3048 | >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table |
| 3049 | Jack: 4098; Sjoerd: 4127; Dcab: 8637678 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3050 | \end{verbatim} |
| 3051 | |
| 3052 | This is particularly useful in combination with the new built-in |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3053 | \function{vars()} function, which returns a dictionary containing all |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3054 | local variables. |
| 3055 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3056 | \section{Reading and Writing Files \label{files}} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3057 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3058 | % Opening files |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3059 | \function{open()}\bifuncindex{open} returns a file |
| 3060 | object\obindex{file}, and is most commonly used with two arguments: |
| 3061 | \samp{open(\var{filename}, \var{mode})}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3062 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3063 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3064 | >>> f=open('/tmp/workfile', 'w') |
| 3065 | >>> print f |
| 3066 | <open file '/tmp/workfile', mode 'w' at 80a0960> |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3067 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3068 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3069 | The first argument is a string containing the filename. The second |
| 3070 | argument is another string containing a few characters describing the |
| 3071 | way in which the file will be used. \var{mode} can be \code{'r'} when |
| 3072 | the file will only be read, \code{'w'} for only writing (an existing |
| 3073 | file with the same name will be erased), and \code{'a'} opens the file |
| 3074 | for appending; any data written to the file is automatically added to |
| 3075 | the end. \code{'r+'} opens the file for both reading and writing. |
| 3076 | The \var{mode} argument is optional; \code{'r'} will be assumed if |
| 3077 | it's omitted. |
| 3078 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3079 | On Windows and the Macintosh, \code{'b'} appended to the |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3080 | mode opens the file in binary mode, so there are also modes like |
| 3081 | \code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a |
| 3082 | distinction between text and binary files; the end-of-line characters |
| 3083 | in text files are automatically altered slightly when data is read or |
| 3084 | written. This behind-the-scenes modification to file data is fine for |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3085 | \ASCII{} text files, but it'll corrupt binary data like that in JPEGs or |
| 3086 | \file{.EXE} files. Be very careful to use binary mode when reading and |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3087 | writing such files. (Note that the precise semantics of text mode on |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3088 | the Macintosh depends on the underlying C library being used.) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3089 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3090 | \subsection{Methods of File Objects \label{fileMethods}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3091 | |
| 3092 | The rest of the examples in this section will assume that a file |
| 3093 | object called \code{f} has already been created. |
| 3094 | |
| 3095 | To read a file's contents, call \code{f.read(\var{size})}, which reads |
| 3096 | some quantity of data and returns it as a string. \var{size} is an |
| 3097 | optional numeric argument. When \var{size} is omitted or negative, |
| 3098 | the entire contents of the file will be read and returned; it's your |
| 3099 | problem if the file is twice as large as your machine's memory. |
| 3100 | Otherwise, at most \var{size} bytes are read and returned. If the end |
| 3101 | of the file has been reached, \code{f.read()} will return an empty |
| 3102 | string (\code {""}). |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3103 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3104 | >>> f.read() |
Fred Drake | 0c14961 | 2001-04-12 04:26:24 +0000 | [diff] [blame] | 3105 | 'This is the entire file.\n' |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3106 | >>> f.read() |
| 3107 | '' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3108 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3109 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3110 | \code{f.readline()} reads a single line from the file; a newline |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3111 | character (\code{\e n}) is left at the end of the string, and is only |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3112 | omitted on the last line of the file if the file doesn't end in a |
| 3113 | newline. This makes the return value unambiguous; if |
| 3114 | \code{f.readline()} returns an empty string, the end of the file has |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3115 | been reached, while a blank line is represented by \code{'\e n'}, a |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3116 | string containing only a single newline. |
| 3117 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3118 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3119 | >>> f.readline() |
Fred Drake | 0c14961 | 2001-04-12 04:26:24 +0000 | [diff] [blame] | 3120 | 'This is the first line of the file.\n' |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3121 | >>> f.readline() |
Fred Drake | 0c14961 | 2001-04-12 04:26:24 +0000 | [diff] [blame] | 3122 | 'Second line of the file\n' |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3123 | >>> f.readline() |
| 3124 | '' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3125 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3126 | |
Fred Drake | 343ad7a | 2000-09-22 04:12:27 +0000 | [diff] [blame] | 3127 | \code{f.readlines()} returns a list containing all the lines of data |
| 3128 | in the file. If given an optional parameter \var{sizehint}, it reads |
| 3129 | that many bytes from the file and enough more to complete a line, and |
| 3130 | returns the lines from that. This is often used to allow efficient |
| 3131 | reading of a large file by lines, but without having to load the |
| 3132 | entire file in memory. Only complete lines will be returned. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3133 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3134 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3135 | >>> f.readlines() |
Fred Drake | 0c14961 | 2001-04-12 04:26:24 +0000 | [diff] [blame] | 3136 | ['This is the first line of the file.\n', 'Second line of the file\n'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3137 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3138 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3139 | \code{f.write(\var{string})} writes the contents of \var{string} to |
| 3140 | the file, returning \code{None}. |
| 3141 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3142 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3143 | >>> f.write('This is a test\n') |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3144 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3145 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3146 | \code{f.tell()} returns an integer giving the file object's current |
| 3147 | position in the file, measured in bytes from the beginning of the |
| 3148 | file. To change the file object's position, use |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3149 | \samp{f.seek(\var{offset}, \var{from_what})}. The position is |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3150 | computed from adding \var{offset} to a reference point; the reference |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3151 | point is selected by the \var{from_what} argument. A |
| 3152 | \var{from_what} value of 0 measures from the beginning of the file, 1 |
| 3153 | uses the current file position, and 2 uses the end of the file as the |
| 3154 | reference point. \var{from_what} can be omitted and defaults to 0, |
| 3155 | using the beginning of the file as the reference point. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3156 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3157 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3158 | >>> f=open('/tmp/workfile', 'r+') |
| 3159 | >>> f.write('0123456789abcdef') |
Fred Drake | a815916 | 2001-10-16 03:25:00 +0000 | [diff] [blame] | 3160 | >>> f.seek(5) # Go to the 6th byte in the file |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3161 | >>> f.read(1) |
| 3162 | '5' |
| 3163 | >>> f.seek(-3, 2) # Go to the 3rd byte before the end |
| 3164 | >>> f.read(1) |
| 3165 | 'd' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3166 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3167 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3168 | When you're done with a file, call \code{f.close()} to close it and |
| 3169 | free up any system resources taken up by the open file. After calling |
| 3170 | \code{f.close()}, attempts to use the file object will automatically fail. |
| 3171 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3172 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3173 | >>> f.close() |
| 3174 | >>> f.read() |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 3175 | Traceback (most recent call last): |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3176 | File "<stdin>", line 1, in ? |
| 3177 | ValueError: I/O operation on closed file |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3178 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3179 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3180 | File objects have some additional methods, such as |
| 3181 | \method{isatty()} and \method{truncate()} which are less frequently |
| 3182 | used; consult the Library Reference for a complete guide to file |
| 3183 | objects. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3184 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3185 | \subsection{The \module{pickle} Module \label{pickle}} |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3186 | \refstmodindex{pickle} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3187 | |
| 3188 | Strings can easily be written to and read from a file. Numbers take a |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3189 | bit more effort, since the \method{read()} method only returns |
| 3190 | strings, which will have to be passed to a function like |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 3191 | \function{int()}, which takes a string like \code{'123'} and |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3192 | returns its numeric value 123. However, when you want to save more |
| 3193 | complex data types like lists, dictionaries, or class instances, |
| 3194 | things get a lot more complicated. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3195 | |
| 3196 | Rather than have users be constantly writing and debugging code to |
| 3197 | save complicated data types, Python provides a standard module called |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 3198 | \ulink{\module{pickle}}{../lib/module-pickle.html}. This is an |
| 3199 | amazing module that can take almost |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3200 | any Python object (even some forms of Python code!), and convert it to |
| 3201 | a string representation; this process is called \dfn{pickling}. |
| 3202 | Reconstructing the object from the string representation is called |
| 3203 | \dfn{unpickling}. Between pickling and unpickling, the string |
| 3204 | representing the object may have been stored in a file or data, or |
| 3205 | sent over a network connection to some distant machine. |
| 3206 | |
| 3207 | If you have an object \code{x}, and a file object \code{f} that's been |
| 3208 | opened for writing, the simplest way to pickle the object takes only |
| 3209 | one line of code: |
| 3210 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3211 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3212 | pickle.dump(x, f) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3213 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3214 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3215 | To unpickle the object again, if \code{f} is a file object which has |
| 3216 | been opened for reading: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3217 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3218 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3219 | x = pickle.load(f) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3220 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3221 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3222 | (There are other variants of this, used when pickling many objects or |
| 3223 | when you don't want to write the pickled data to a file; consult the |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 3224 | complete documentation for |
| 3225 | \ulink{\module{pickle}}{../lib/module-pickle.html} in the |
| 3226 | \citetitle[../lib/]{Python Library Reference}.) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3227 | |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 3228 | \ulink{\module{pickle}}{../lib/module-pickle.html} is the standard way |
| 3229 | to make Python objects which can be stored and reused by other |
| 3230 | programs or by a future invocation of the same program; the technical |
| 3231 | term for this is a \dfn{persistent} object. Because |
| 3232 | \ulink{\module{pickle}}{../lib/module-pickle.html} is so widely used, |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3233 | many authors who write Python extensions take care to ensure that new |
| 3234 | data types such as matrices can be properly pickled and unpickled. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3235 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3236 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3237 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3238 | \chapter{Errors and Exceptions \label{errors}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3239 | |
| 3240 | Until now error messages haven't been more than mentioned, but if you |
| 3241 | have tried out the examples you have probably seen some. There are |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3242 | (at least) two distinguishable kinds of errors: |
| 3243 | \emph{syntax errors} and \emph{exceptions}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3244 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3245 | \section{Syntax Errors \label{syntaxErrors}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3246 | |
| 3247 | Syntax errors, also known as parsing errors, are perhaps the most common |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 3248 | kind of complaint you get while you are still learning Python: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3249 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3250 | \begin{verbatim} |
Raymond Hettinger | a6e16a8 | 2002-08-21 04:54:00 +0000 | [diff] [blame] | 3251 | >>> while True print 'Hello world' |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3252 | File "<stdin>", line 1, in ? |
Raymond Hettinger | a6e16a8 | 2002-08-21 04:54:00 +0000 | [diff] [blame] | 3253 | while True print 'Hello world' |
| 3254 | ^ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3255 | SyntaxError: invalid syntax |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3256 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3257 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3258 | The parser repeats the offending line and displays a little `arrow' |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3259 | pointing at the earliest point in the line where the error was |
| 3260 | detected. The error is caused by (or at least detected at) the token |
| 3261 | \emph{preceding} the arrow: in the example, the error is detected at |
| 3262 | the keyword \keyword{print}, since a colon (\character{:}) is missing |
| 3263 | before it. File name and line number are printed so you know where to |
| 3264 | look in case the input came from a script. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3265 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3266 | \section{Exceptions \label{exceptions}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3267 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3268 | Even if a statement or expression is syntactically correct, it may |
| 3269 | cause an error when an attempt is made to execute it. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3270 | Errors detected during execution are called \emph{exceptions} and are |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 3271 | not unconditionally fatal: you will soon learn how to handle them in |
| 3272 | Python programs. Most exceptions are not handled by programs, |
| 3273 | however, and result in error messages as shown here: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3274 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3275 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3276 | >>> 10 * (1/0) |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 3277 | Traceback (most recent call last): |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3278 | File "<stdin>", line 1, in ? |
Raymond Hettinger | a02469f | 2003-05-07 17:49:36 +0000 | [diff] [blame] | 3279 | ZeroDivisionError: integer division or modulo by zero |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 3280 | >>> 4 + spam*3 |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 3281 | Traceback (most recent call last): |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3282 | File "<stdin>", line 1, in ? |
Andrew M. Kuchling | e7bd876 | 2002-05-02 14:31:55 +0000 | [diff] [blame] | 3283 | NameError: name 'spam' is not defined |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3284 | >>> '2' + 2 |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 3285 | Traceback (most recent call last): |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3286 | File "<stdin>", line 1, in ? |
Raymond Hettinger | a02469f | 2003-05-07 17:49:36 +0000 | [diff] [blame] | 3287 | TypeError: cannot concatenate 'str' and 'int' objects |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3288 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3289 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3290 | The last line of the error message indicates what happened. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3291 | Exceptions come in different types, and the type is printed as part of |
| 3292 | the message: the types in the example are |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3293 | \exception{ZeroDivisionError}, \exception{NameError} and |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3294 | \exception{TypeError}. |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3295 | The string printed as the exception type is the name of the built-in |
Fred Drake | f0ae427 | 2004-02-24 16:13:36 +0000 | [diff] [blame] | 3296 | exception that occurred. This is true for all built-in |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3297 | exceptions, but need not be true for user-defined exceptions (although |
| 3298 | it is a useful convention). |
| 3299 | Standard exception names are built-in identifiers (not reserved |
| 3300 | keywords). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3301 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3302 | The rest of the line is a detail whose interpretation depends on the |
| 3303 | exception type; its meaning is dependent on the exception type. |
| 3304 | |
| 3305 | The preceding part of the error message shows the context where the |
| 3306 | exception happened, in the form of a stack backtrace. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 3307 | In general it contains a stack backtrace listing source lines; however, |
| 3308 | it will not display lines read from standard input. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3309 | |
Fred Drake | 860106a | 2000-10-20 03:03:18 +0000 | [diff] [blame] | 3310 | The \citetitle[../lib/module-exceptions.html]{Python Library |
| 3311 | Reference} lists the built-in exceptions and their meanings. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3312 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3313 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3314 | \section{Handling Exceptions \label{handling}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3315 | |
| 3316 | It is possible to write programs that handle selected exceptions. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3317 | Look at the following example, which asks the user for input until a |
| 3318 | valid integer has been entered, but allows the user to interrupt the |
| 3319 | program (using \kbd{Control-C} or whatever the operating system |
| 3320 | supports); note that a user-generated interruption is signalled by |
| 3321 | raising the \exception{KeyboardInterrupt} exception. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3322 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3323 | \begin{verbatim} |
Raymond Hettinger | a6e16a8 | 2002-08-21 04:54:00 +0000 | [diff] [blame] | 3324 | >>> while True: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3325 | ... try: |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3326 | ... x = int(raw_input("Please enter a number: ")) |
| 3327 | ... break |
| 3328 | ... except ValueError: |
| 3329 | ... print "Oops! That was no valid number. Try again..." |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3330 | ... |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3331 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3332 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3333 | The \keyword{try} statement works as follows. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3334 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3335 | \begin{itemize} |
| 3336 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3337 | First, the \emph{try clause} (the statement(s) between the |
| 3338 | \keyword{try} and \keyword{except} keywords) is executed. |
| 3339 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3340 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3341 | If no exception occurs, the \emph{except\ clause} is skipped and |
| 3342 | execution of the \keyword{try} statement is finished. |
| 3343 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3344 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3345 | If an exception occurs during execution of the try clause, the rest of |
| 3346 | the clause is skipped. Then if its type matches the exception named |
| 3347 | after the \keyword{except} keyword, the rest of the try clause is |
| 3348 | skipped, the except clause is executed, and then execution continues |
| 3349 | after the \keyword{try} statement. |
| 3350 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3351 | \item |
| 3352 | If an exception occurs which does not match the exception named in the |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3353 | except clause, it is passed on to outer \keyword{try} statements; if |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3354 | no handler is found, it is an \emph{unhandled exception} and execution |
| 3355 | stops with a message as shown above. |
| 3356 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3357 | \end{itemize} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3358 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3359 | A \keyword{try} statement may have more than one except clause, to |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3360 | specify handlers for different exceptions. At most one handler will |
| 3361 | be executed. Handlers only handle exceptions that occur in the |
| 3362 | corresponding try clause, not in other handlers of the same |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 3363 | \keyword{try} statement. An except clause may name multiple exceptions |
| 3364 | as a parenthesized list, for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3365 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3366 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3367 | ... except (RuntimeError, TypeError, NameError): |
| 3368 | ... pass |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3369 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3370 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3371 | The last except clause may omit the exception name(s), to serve as a |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3372 | wildcard. Use this with extreme caution, since it is easy to mask a |
| 3373 | real programming error in this way! It can also be used to print an |
| 3374 | error message and then re-raise the exception (allowing a caller to |
| 3375 | handle the exception as well): |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3376 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3377 | \begin{verbatim} |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 3378 | import sys |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3379 | |
| 3380 | try: |
| 3381 | f = open('myfile.txt') |
| 3382 | s = f.readline() |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 3383 | i = int(s.strip()) |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3384 | except IOError, (errno, strerror): |
| 3385 | print "I/O error(%s): %s" % (errno, strerror) |
| 3386 | except ValueError: |
| 3387 | print "Could not convert data to an integer." |
| 3388 | except: |
| 3389 | print "Unexpected error:", sys.exc_info()[0] |
| 3390 | raise |
| 3391 | \end{verbatim} |
Fred Drake | 2900ff9 | 1999-08-24 22:14:57 +0000 | [diff] [blame] | 3392 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3393 | The \keyword{try} \ldots\ \keyword{except} statement has an optional |
Fred Drake | e99d1db | 2000-04-17 14:56:31 +0000 | [diff] [blame] | 3394 | \emph{else clause}, which, when present, must follow all except |
| 3395 | clauses. It is useful for code that must be executed if the try |
| 3396 | clause does not raise an exception. For example: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3397 | |
| 3398 | \begin{verbatim} |
Guido van Rossum | a4289a7 | 1998-07-07 20:18:06 +0000 | [diff] [blame] | 3399 | for arg in sys.argv[1:]: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3400 | try: |
| 3401 | f = open(arg, 'r') |
| 3402 | except IOError: |
| 3403 | print 'cannot open', arg |
| 3404 | else: |
| 3405 | print arg, 'has', len(f.readlines()), 'lines' |
| 3406 | f.close() |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3407 | \end{verbatim} |
| 3408 | |
Fred Drake | e99d1db | 2000-04-17 14:56:31 +0000 | [diff] [blame] | 3409 | The use of the \keyword{else} clause is better than adding additional |
| 3410 | code to the \keyword{try} clause because it avoids accidentally |
| 3411 | catching an exception that wasn't raised by the code being protected |
| 3412 | by the \keyword{try} \ldots\ \keyword{except} statement. |
| 3413 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3414 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3415 | When an exception occurs, it may have an associated value, also known as |
Thomas Wouters | f9b526d | 2000-07-16 19:05:38 +0000 | [diff] [blame] | 3416 | the exception's \emph{argument}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3417 | The presence and type of the argument depend on the exception type. |
Raymond Hettinger | 6122d02 | 2003-07-12 01:05:37 +0000 | [diff] [blame] | 3418 | |
| 3419 | The except clause may specify a variable after the exception name (or list). |
| 3420 | The variable is bound to an exception instance with the arguments stored |
| 3421 | in \code{instance.args}. For convenience, the exception instance |
| 3422 | defines \method{__getitem__} and \method{__str__} so the arguments can |
| 3423 | be accessed or printed directly without having to reference \code{.args}. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3424 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3425 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3426 | >>> try: |
Raymond Hettinger | 6122d02 | 2003-07-12 01:05:37 +0000 | [diff] [blame] | 3427 | ... raise Exception('spam', 'eggs') |
| 3428 | ... except Exception, inst: |
| 3429 | ... print type(inst) # the exception instance |
Raymond Hettinger | b233e54 | 2003-07-15 23:16:01 +0000 | [diff] [blame] | 3430 | ... print inst.args # arguments stored in .args |
Raymond Hettinger | 6122d02 | 2003-07-12 01:05:37 +0000 | [diff] [blame] | 3431 | ... print inst # __str__ allows args to printed directly |
| 3432 | ... x, y = inst # __getitem__ allows args to be unpacked directly |
| 3433 | ... print 'x =', x |
| 3434 | ... print 'y =', y |
| 3435 | ... |
| 3436 | <type 'instance'> |
| 3437 | ('spam', 'eggs') |
| 3438 | ('spam', 'eggs') |
| 3439 | x = spam |
| 3440 | y = eggs |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3441 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3442 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3443 | If an exception has an argument, it is printed as the last part |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3444 | (`detail') of the message for unhandled exceptions. |
| 3445 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3446 | Exception handlers don't just handle exceptions if they occur |
| 3447 | immediately in the try clause, but also if they occur inside functions |
| 3448 | that are called (even indirectly) in the try clause. |
| 3449 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3450 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3451 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3452 | >>> def this_fails(): |
| 3453 | ... x = 1/0 |
| 3454 | ... |
| 3455 | >>> try: |
| 3456 | ... this_fails() |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3457 | ... except ZeroDivisionError, detail: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3458 | ... print 'Handling run-time error:', detail |
| 3459 | ... |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3460 | Handling run-time error: integer division or modulo |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3461 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3462 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3463 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3464 | \section{Raising Exceptions \label{raising}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3465 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3466 | The \keyword{raise} statement allows the programmer to force a |
| 3467 | specified exception to occur. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3468 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3469 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3470 | \begin{verbatim} |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3471 | >>> raise NameError, 'HiThere' |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 3472 | Traceback (most recent call last): |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3473 | File "<stdin>", line 1, in ? |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3474 | NameError: HiThere |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3475 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3476 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3477 | The first argument to \keyword{raise} names the exception to be |
| 3478 | raised. The optional second argument specifies the exception's |
| 3479 | argument. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3480 | |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3481 | If you need to determine whether an exception was raised but don't |
| 3482 | intend to handle it, a simpler form of the \keyword{raise} statement |
| 3483 | allows you to re-raise the exception: |
| 3484 | |
| 3485 | \begin{verbatim} |
| 3486 | >>> try: |
| 3487 | ... raise NameError, 'HiThere' |
| 3488 | ... except NameError: |
| 3489 | ... print 'An exception flew by!' |
| 3490 | ... raise |
| 3491 | ... |
| 3492 | An exception flew by! |
| 3493 | Traceback (most recent call last): |
| 3494 | File "<stdin>", line 2, in ? |
| 3495 | NameError: HiThere |
| 3496 | \end{verbatim} |
| 3497 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3498 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3499 | \section{User-defined Exceptions \label{userExceptions}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3500 | |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3501 | Programs may name their own exceptions by creating a new exception |
| 3502 | class. Exceptions should typically be derived from the |
| 3503 | \exception{Exception} class, either directly or indirectly. For |
| 3504 | example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3505 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3506 | \begin{verbatim} |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3507 | >>> class MyError(Exception): |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3508 | ... def __init__(self, value): |
| 3509 | ... self.value = value |
| 3510 | ... def __str__(self): |
Skip Montanaro | b4f1242 | 2003-05-07 15:29:12 +0000 | [diff] [blame] | 3511 | ... return repr(self.value) |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3512 | ... |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3513 | >>> try: |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3514 | ... raise MyError(2*2) |
| 3515 | ... except MyError, e: |
| 3516 | ... print 'My exception occurred, value:', e.value |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3517 | ... |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3518 | My exception occurred, value: 4 |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3519 | >>> raise MyError, 'oops!' |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 3520 | Traceback (most recent call last): |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3521 | File "<stdin>", line 1, in ? |
| 3522 | __main__.MyError: 'oops!' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3523 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3524 | |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3525 | Exception classes can be defined which do anything any other class can |
| 3526 | do, but are usually kept simple, often only offering a number of |
| 3527 | attributes that allow information about the error to be extracted by |
| 3528 | handlers for the exception. When creating a module which can raise |
| 3529 | several distinct errors, a common practice is to create a base class |
| 3530 | for exceptions defined by that module, and subclass that to create |
| 3531 | specific exception classes for different error conditions: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3532 | |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3533 | \begin{verbatim} |
| 3534 | class Error(Exception): |
| 3535 | """Base class for exceptions in this module.""" |
| 3536 | pass |
| 3537 | |
| 3538 | class InputError(Error): |
| 3539 | """Exception raised for errors in the input. |
| 3540 | |
| 3541 | Attributes: |
| 3542 | expression -- input expression in which the error occurred |
| 3543 | message -- explanation of the error |
| 3544 | """ |
| 3545 | |
| 3546 | def __init__(self, expression, message): |
| 3547 | self.expression = expression |
| 3548 | self.message = message |
| 3549 | |
| 3550 | class TransitionError(Error): |
| 3551 | """Raised when an operation attempts a state transition that's not |
| 3552 | allowed. |
| 3553 | |
| 3554 | Attributes: |
| 3555 | previous -- state at beginning of transition |
| 3556 | next -- attempted new state |
| 3557 | message -- explanation of why the specific transition is not allowed |
| 3558 | """ |
| 3559 | |
| 3560 | def __init__(self, previous, next, message): |
| 3561 | self.previous = previous |
| 3562 | self.next = next |
| 3563 | self.message = message |
| 3564 | \end{verbatim} |
| 3565 | |
| 3566 | Most exceptions are defined with names that end in ``Error,'' similar |
| 3567 | to the naming of the standard exceptions. |
| 3568 | |
| 3569 | Many standard modules define their own exceptions to report errors |
| 3570 | that may occur in functions they define. More information on classes |
| 3571 | is presented in chapter \ref{classes}, ``Classes.'' |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3572 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3573 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3574 | \section{Defining Clean-up Actions \label{cleanup}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3575 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3576 | The \keyword{try} statement has another optional clause which is |
| 3577 | intended to define clean-up actions that must be executed under all |
| 3578 | circumstances. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3579 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3580 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3581 | >>> try: |
| 3582 | ... raise KeyboardInterrupt |
| 3583 | ... finally: |
| 3584 | ... print 'Goodbye, world!' |
| 3585 | ... |
| 3586 | Goodbye, world! |
Fred Drake | 162c6a6 | 2001-02-14 03:20:18 +0000 | [diff] [blame] | 3587 | Traceback (most recent call last): |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3588 | File "<stdin>", line 2, in ? |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3589 | KeyboardInterrupt |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3590 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3591 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3592 | A \emph{finally clause} is executed whether or not an exception has |
| 3593 | occurred in the try clause. When an exception has occurred, it is |
| 3594 | re-raised after the finally clause is executed. The finally clause is |
| 3595 | also executed ``on the way out'' when the \keyword{try} statement is |
| 3596 | left via a \keyword{break} or \keyword{return} statement. |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 3597 | |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3598 | The code in the finally clause is useful for releasing external |
| 3599 | resources (such as files or network connections), regardless of |
| 3600 | whether or not the use of the resource was successful. |
| 3601 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3602 | A \keyword{try} statement must either have one or more except clauses |
| 3603 | or one finally clause, but not both. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3604 | |
Fred Drake | 13af428 | 2001-09-21 21:10:05 +0000 | [diff] [blame] | 3605 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3606 | \chapter{Classes \label{classes}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3607 | |
| 3608 | Python's class mechanism adds classes to the language with a minimum |
| 3609 | of new syntax and semantics. It is a mixture of the class mechanisms |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 3610 | found in \Cpp{} and Modula-3. As is true for modules, classes in Python |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3611 | do not put an absolute barrier between definition and user, but rather |
| 3612 | rely on the politeness of the user not to ``break into the |
| 3613 | definition.'' The most important features of classes are retained |
| 3614 | with full power, however: the class inheritance mechanism allows |
| 3615 | multiple base classes, a derived class can override any methods of its |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3616 | base class or classes, a method can call the method of a base class with the |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3617 | same name. Objects can contain an arbitrary amount of private data. |
| 3618 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 3619 | In \Cpp{} terminology, all class members (including the data members) are |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3620 | \emph{public}, and all member functions are \emph{virtual}. There are |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3621 | no special constructors or destructors. As in Modula-3, there are no |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3622 | shorthands for referencing the object's members from its methods: the |
| 3623 | method function is declared with an explicit first argument |
| 3624 | representing the object, which is provided implicitly by the call. As |
| 3625 | in Smalltalk, classes themselves are objects, albeit in the wider |
| 3626 | sense of the word: in Python, all data types are objects. This |
Neal Norwitz | 8ed69e3 | 2003-10-25 14:15:54 +0000 | [diff] [blame] | 3627 | provides semantics for importing and renaming. Unlike |
| 3628 | \Cpp{} and Modula-3, built-in types can be used as base classes for |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 3629 | extension by the user. Also, like in \Cpp{} but unlike in Modula-3, most |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3630 | built-in operators with special syntax (arithmetic operators, |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3631 | subscripting etc.) can be redefined for class instances. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3632 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3633 | \section{A Word About Terminology \label{terminology}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3634 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3635 | Lacking universally accepted terminology to talk about classes, I will |
| 3636 | make occasional use of Smalltalk and \Cpp{} terms. (I would use Modula-3 |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3637 | terms, since its object-oriented semantics are closer to those of |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 3638 | Python than \Cpp, but I expect that few readers have heard of it.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3639 | |
| 3640 | I also have to warn you that there's a terminological pitfall for |
| 3641 | object-oriented readers: the word ``object'' in Python does not |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3642 | necessarily mean a class instance. Like \Cpp{} and Modula-3, and |
| 3643 | unlike Smalltalk, not all types in Python are classes: the basic |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3644 | built-in types like integers and lists are not, and even somewhat more |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3645 | exotic types like files aren't. However, \emph{all} Python types |
| 3646 | share a little bit of common semantics that is best described by using |
| 3647 | the word object. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3648 | |
| 3649 | Objects have individuality, and multiple names (in multiple scopes) |
| 3650 | can be bound to the same object. This is known as aliasing in other |
| 3651 | languages. This is usually not appreciated on a first glance at |
| 3652 | Python, and can be safely ignored when dealing with immutable basic |
| 3653 | types (numbers, strings, tuples). However, aliasing has an |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3654 | (intended!) effect on the semantics of Python code involving mutable |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3655 | objects such as lists, dictionaries, and most types representing |
| 3656 | entities outside the program (files, windows, etc.). This is usually |
| 3657 | used to the benefit of the program, since aliases behave like pointers |
| 3658 | in some respects. For example, passing an object is cheap since only |
| 3659 | a pointer is passed by the implementation; and if a function modifies |
| 3660 | an object passed as an argument, the caller will see the change --- this |
Raymond Hettinger | ccd615c | 2003-06-30 04:27:31 +0000 | [diff] [blame] | 3661 | eliminates the need for two different argument passing mechanisms as in |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3662 | Pascal. |
| 3663 | |
| 3664 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3665 | \section{Python Scopes and Name Spaces \label{scopes}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3666 | |
| 3667 | Before introducing classes, I first have to tell you something about |
| 3668 | Python's scope rules. Class definitions play some neat tricks with |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3669 | namespaces, and you need to know how scopes and namespaces work to |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3670 | fully understand what's going on. Incidentally, knowledge about this |
| 3671 | subject is useful for any advanced Python programmer. |
| 3672 | |
| 3673 | Let's begin with some definitions. |
| 3674 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3675 | A \emph{namespace} is a mapping from names to objects. Most |
| 3676 | namespaces are currently implemented as Python dictionaries, but |
| 3677 | that's normally not noticeable in any way (except for performance), |
| 3678 | and it may change in the future. Examples of namespaces are: the set |
| 3679 | of built-in names (functions such as \function{abs()}, and built-in |
| 3680 | exception names); the global names in a module; and the local names in |
| 3681 | a function invocation. In a sense the set of attributes of an object |
| 3682 | also form a namespace. The important thing to know about namespaces |
| 3683 | is that there is absolutely no relation between names in different |
| 3684 | namespaces; for instance, two different modules may both define a |
| 3685 | function ``maximize'' without confusion --- users of the modules must |
| 3686 | prefix it with the module name. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3687 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3688 | By the way, I use the word \emph{attribute} for any name following a |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3689 | dot --- for example, in the expression \code{z.real}, \code{real} is |
| 3690 | an attribute of the object \code{z}. Strictly speaking, references to |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3691 | names in modules are attribute references: in the expression |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3692 | \code{modname.funcname}, \code{modname} is a module object and |
| 3693 | \code{funcname} is an attribute of it. In this case there happens to |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3694 | be a straightforward mapping between the module's attributes and the |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3695 | global names defined in the module: they share the same namespace! |
| 3696 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3697 | Except for one thing. Module objects have a secret read-only |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3698 | attribute called \member{__dict__} which returns the dictionary |
| 3699 | used to implement the module's namespace; the name |
| 3700 | \member{__dict__} is an attribute but not a global name. |
| 3701 | Obviously, using this violates the abstraction of namespace |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3702 | implementation, and should be restricted to things like |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3703 | post-mortem debuggers. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3704 | } |
| 3705 | |
| 3706 | Attributes may be read-only or writable. In the latter case, |
| 3707 | assignment to attributes is possible. Module attributes are writable: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3708 | you can write \samp{modname.the_answer = 42}. Writable attributes may |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 3709 | also be deleted with the \keyword{del} statement. For example, |
| 3710 | \samp{del modname.the_answer} will remove the attribute |
| 3711 | \member{the_answer} from the object named by \code{modname}. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3712 | |
| 3713 | Name spaces are created at different moments and have different |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3714 | lifetimes. The namespace containing the built-in names is created |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3715 | when the Python interpreter starts up, and is never deleted. The |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3716 | global namespace for a module is created when the module definition |
| 3717 | is read in; normally, module namespaces also last until the |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3718 | interpreter quits. The statements executed by the top-level |
| 3719 | invocation of the interpreter, either read from a script file or |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3720 | interactively, are considered part of a module called |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3721 | \module{__main__}, so they have their own global namespace. (The |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3722 | built-in names actually also live in a module; this is called |
| 3723 | \module{__builtin__}.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3724 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3725 | The local namespace for a function is created when the function is |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3726 | called, and deleted when the function returns or raises an exception |
| 3727 | that is not handled within the function. (Actually, forgetting would |
| 3728 | be a better way to describe what actually happens.) Of course, |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3729 | recursive invocations each have their own local namespace. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3730 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3731 | A \emph{scope} is a textual region of a Python program where a |
| 3732 | namespace is directly accessible. ``Directly accessible'' here means |
| 3733 | that an unqualified reference to a name attempts to find the name in |
| 3734 | the namespace. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3735 | |
| 3736 | Although scopes are determined statically, they are used dynamically. |
Raymond Hettinger | 861bb02 | 2002-08-07 16:09:48 +0000 | [diff] [blame] | 3737 | At any time during execution, there are at least three nested scopes whose |
| 3738 | namespaces are directly accessible: the innermost scope, which is searched |
Raymond Hettinger | ae7ef57 | 2002-08-07 20:20:52 +0000 | [diff] [blame] | 3739 | first, contains the local names; the namespaces of any enclosing |
| 3740 | functions, which are searched starting with the nearest enclosing scope; |
| 3741 | the middle scope, searched next, contains the current module's global names; |
| 3742 | and the outermost scope (searched last) is the namespace containing built-in |
| 3743 | names. |
Raymond Hettinger | 861bb02 | 2002-08-07 16:09:48 +0000 | [diff] [blame] | 3744 | |
| 3745 | If a name is declared global, then all references and assignments go |
| 3746 | directly to the middle scope containing the module's global names. |
| 3747 | Otherwise, all variables found outside of the innermost scope are read-only. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3748 | |
| 3749 | Usually, the local scope references the local names of the (textually) |
Guido van Rossum | 96628a9 | 1995-04-10 11:34:00 +0000 | [diff] [blame] | 3750 | current function. Outside of functions, the local scope references |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3751 | the same namespace as the global scope: the module's namespace. |
| 3752 | Class definitions place yet another namespace in the local scope. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3753 | |
| 3754 | It is important to realize that scopes are determined textually: the |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3755 | global scope of a function defined in a module is that module's |
| 3756 | namespace, no matter from where or by what alias the function is |
| 3757 | called. On the other hand, the actual search for names is done |
| 3758 | dynamically, at run time --- however, the language definition is |
| 3759 | evolving towards static name resolution, at ``compile'' time, so don't |
| 3760 | rely on dynamic name resolution! (In fact, local variables are |
| 3761 | already determined statically.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3762 | |
| 3763 | A special quirk of Python is that assignments always go into the |
| 3764 | innermost scope. Assignments do not copy data --- they just |
| 3765 | bind names to objects. The same is true for deletions: the statement |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3766 | \samp{del x} removes the binding of \code{x} from the namespace |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3767 | referenced by the local scope. In fact, all operations that introduce |
| 3768 | new names use the local scope: in particular, import statements and |
| 3769 | function definitions bind the module or function name in the local |
| 3770 | scope. (The \keyword{global} statement can be used to indicate that |
| 3771 | particular variables live in the global scope.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3772 | |
| 3773 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3774 | \section{A First Look at Classes \label{firstClasses}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3775 | |
| 3776 | Classes introduce a little bit of new syntax, three new object types, |
| 3777 | and some new semantics. |
| 3778 | |
| 3779 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3780 | \subsection{Class Definition Syntax \label{classDefinition}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3781 | |
| 3782 | The simplest form of class definition looks like this: |
| 3783 | |
| 3784 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3785 | class ClassName: |
| 3786 | <statement-1> |
| 3787 | . |
| 3788 | . |
| 3789 | . |
| 3790 | <statement-N> |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3791 | \end{verbatim} |
| 3792 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3793 | Class definitions, like function definitions |
| 3794 | (\keyword{def} statements) must be executed before they have any |
| 3795 | effect. (You could conceivably place a class definition in a branch |
| 3796 | of an \keyword{if} statement, or inside a function.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3797 | |
| 3798 | In practice, the statements inside a class definition will usually be |
| 3799 | function definitions, but other statements are allowed, and sometimes |
| 3800 | useful --- we'll come back to this later. The function definitions |
| 3801 | inside a class normally have a peculiar form of argument list, |
| 3802 | dictated by the calling conventions for methods --- again, this is |
| 3803 | explained later. |
| 3804 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3805 | When a class definition is entered, a new namespace is created, and |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3806 | used as the local scope --- thus, all assignments to local variables |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3807 | go into this new namespace. In particular, function definitions bind |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3808 | the name of the new function here. |
| 3809 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3810 | When a class definition is left normally (via the end), a \emph{class |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3811 | object} is created. This is basically a wrapper around the contents |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3812 | of the namespace created by the class definition; we'll learn more |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3813 | about class objects in the next section. The original local scope |
| 3814 | (the one in effect just before the class definitions was entered) is |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 3815 | reinstated, and the class object is bound here to the class name given |
| 3816 | in the class definition header (\class{ClassName} in the example). |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3817 | |
| 3818 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3819 | \subsection{Class Objects \label{classObjects}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3820 | |
| 3821 | Class objects support two kinds of operations: attribute references |
| 3822 | and instantiation. |
| 3823 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3824 | \emph{Attribute references} use the standard syntax used for all |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3825 | attribute references in Python: \code{obj.name}. Valid attribute |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3826 | names are all the names that were in the class's namespace when the |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3827 | class object was created. So, if the class definition looked like |
| 3828 | this: |
| 3829 | |
| 3830 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3831 | class MyClass: |
| 3832 | "A simple example class" |
| 3833 | i = 12345 |
Fred Drake | 88e6625 | 2001-06-29 17:50:57 +0000 | [diff] [blame] | 3834 | def f(self): |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3835 | return 'hello world' |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3836 | \end{verbatim} |
| 3837 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3838 | then \code{MyClass.i} and \code{MyClass.f} are valid attribute |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3839 | references, returning an integer and a method object, respectively. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3840 | Class attributes can also be assigned to, so you can change the value |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3841 | of \code{MyClass.i} by assignment. \member{__doc__} is also a valid |
| 3842 | attribute, returning the docstring belonging to the class: \code{"A |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 3843 | simple example class"}. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3844 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3845 | Class \emph{instantiation} uses function notation. Just pretend that |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3846 | the class object is a parameterless function that returns a new |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3847 | instance of the class. For example (assuming the above class): |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3848 | |
| 3849 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3850 | x = MyClass() |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3851 | \end{verbatim} |
| 3852 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3853 | creates a new \emph{instance} of the class and assigns this object to |
| 3854 | the local variable \code{x}. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3855 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3856 | The instantiation operation (``calling'' a class object) creates an |
| 3857 | empty object. Many classes like to create objects in a known initial |
| 3858 | state. Therefore a class may define a special method named |
| 3859 | \method{__init__()}, like this: |
| 3860 | |
| 3861 | \begin{verbatim} |
| 3862 | def __init__(self): |
| 3863 | self.data = [] |
| 3864 | \end{verbatim} |
| 3865 | |
| 3866 | When a class defines an \method{__init__()} method, class |
| 3867 | instantiation automatically invokes \method{__init__()} for the |
| 3868 | newly-created class instance. So in this example, a new, initialized |
| 3869 | instance can be obtained by: |
| 3870 | |
| 3871 | \begin{verbatim} |
| 3872 | x = MyClass() |
| 3873 | \end{verbatim} |
| 3874 | |
| 3875 | Of course, the \method{__init__()} method may have arguments for |
| 3876 | greater flexibility. In that case, arguments given to the class |
| 3877 | instantiation operator are passed on to \method{__init__()}. For |
| 3878 | example, |
| 3879 | |
| 3880 | \begin{verbatim} |
| 3881 | >>> class Complex: |
| 3882 | ... def __init__(self, realpart, imagpart): |
| 3883 | ... self.r = realpart |
| 3884 | ... self.i = imagpart |
| 3885 | ... |
Tim Peters | bd695a7 | 2001-05-22 06:54:14 +0000 | [diff] [blame] | 3886 | >>> x = Complex(3.0, -4.5) |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3887 | >>> x.r, x.i |
| 3888 | (3.0, -4.5) |
| 3889 | \end{verbatim} |
| 3890 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3891 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3892 | \subsection{Instance Objects \label{instanceObjects}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3893 | |
| 3894 | Now what can we do with instance objects? The only operations |
| 3895 | understood by instance objects are attribute references. There are |
| 3896 | two kinds of valid attribute names. |
| 3897 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3898 | The first I'll call \emph{data attributes}. These correspond to |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3899 | ``instance variables'' in Smalltalk, and to ``data members'' in |
Fred Drake | c37b65e | 2001-11-28 07:26:15 +0000 | [diff] [blame] | 3900 | \Cpp. Data attributes need not be declared; like local variables, |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3901 | they spring into existence when they are first assigned to. For |
| 3902 | example, if \code{x} is the instance of \class{MyClass} created above, |
| 3903 | the following piece of code will print the value \code{16}, without |
| 3904 | leaving a trace: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3905 | |
| 3906 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3907 | x.counter = 1 |
| 3908 | while x.counter < 10: |
| 3909 | x.counter = x.counter * 2 |
| 3910 | print x.counter |
| 3911 | del x.counter |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3912 | \end{verbatim} |
| 3913 | |
| 3914 | The second kind of attribute references understood by instance objects |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3915 | are \emph{methods}. A method is a function that ``belongs to'' an |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3916 | object. (In Python, the term method is not unique to class instances: |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 3917 | other object types can have methods as well. For example, list objects have |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3918 | methods called append, insert, remove, sort, and so on. However, |
| 3919 | below, we'll use the term method exclusively to mean methods of class |
| 3920 | instance objects, unless explicitly stated otherwise.) |
| 3921 | |
| 3922 | Valid method names of an instance object depend on its class. By |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3923 | definition, all attributes of a class that are (user-defined) function |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3924 | objects define corresponding methods of its instances. So in our |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3925 | example, \code{x.f} is a valid method reference, since |
| 3926 | \code{MyClass.f} is a function, but \code{x.i} is not, since |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3927 | \code{MyClass.i} is not. But \code{x.f} is not the same thing as |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3928 | \code{MyClass.f} --- it is a \obindex{method}\emph{method object}, not |
| 3929 | a function object. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3930 | |
| 3931 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3932 | \subsection{Method Objects \label{methodObjects}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3933 | |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 3934 | Usually, a method is called immediately: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3935 | |
| 3936 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3937 | x.f() |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3938 | \end{verbatim} |
| 3939 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3940 | In our example, this will return the string \code{'hello world'}. |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3941 | However, it is not necessary to call a method right away: |
| 3942 | \code{x.f} is a method object, and can be stored away and called at a |
| 3943 | later time. For example: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3944 | |
| 3945 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3946 | xf = x.f |
Raymond Hettinger | a6e16a8 | 2002-08-21 04:54:00 +0000 | [diff] [blame] | 3947 | while True: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3948 | print xf() |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3949 | \end{verbatim} |
| 3950 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3951 | will continue to print \samp{hello world} until the end of time. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3952 | |
| 3953 | What exactly happens when a method is called? You may have noticed |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3954 | that \code{x.f()} was called without an argument above, even though |
| 3955 | the function definition for \method{f} specified an argument. What |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3956 | happened to the argument? Surely Python raises an exception when a |
| 3957 | function that requires an argument is called without any --- even if |
| 3958 | the argument isn't actually used... |
| 3959 | |
| 3960 | Actually, you may have guessed the answer: the special thing about |
| 3961 | methods is that the object is passed as the first argument of the |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3962 | function. In our example, the call \code{x.f()} is exactly equivalent |
| 3963 | to \code{MyClass.f(x)}. In general, calling a method with a list of |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3964 | \var{n} arguments is equivalent to calling the corresponding function |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3965 | with an argument list that is created by inserting the method's object |
| 3966 | before the first argument. |
| 3967 | |
| 3968 | If you still don't understand how methods work, a look at the |
| 3969 | implementation can perhaps clarify matters. When an instance |
| 3970 | attribute is referenced that isn't a data attribute, its class is |
| 3971 | searched. If the name denotes a valid class attribute that is a |
| 3972 | function object, a method object is created by packing (pointers to) |
| 3973 | the instance object and the function object just found together in an |
| 3974 | abstract object: this is the method object. When the method object is |
| 3975 | called with an argument list, it is unpacked again, a new argument |
| 3976 | list is constructed from the instance object and the original argument |
| 3977 | list, and the function object is called with this new argument list. |
| 3978 | |
| 3979 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3980 | \section{Random Remarks \label{remarks}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3981 | |
Raymond Hettinger | d446230 | 2003-11-26 17:52:45 +0000 | [diff] [blame] | 3982 | % [These should perhaps be placed more carefully...] |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3983 | |
| 3984 | |
| 3985 | Data attributes override method attributes with the same name; to |
| 3986 | avoid accidental name conflicts, which may cause hard-to-find bugs in |
| 3987 | large programs, it is wise to use some kind of convention that |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 3988 | minimizes the chance of conflicts. Possible conventions include |
| 3989 | capitalizing method names, prefixing data attribute names with a small |
| 3990 | unique string (perhaps just an underscore), or using verbs for methods |
| 3991 | and nouns for data attributes. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3992 | |
| 3993 | |
| 3994 | Data attributes may be referenced by methods as well as by ordinary |
| 3995 | users (``clients'') of an object. In other words, classes are not |
| 3996 | usable to implement pure abstract data types. In fact, nothing in |
| 3997 | Python makes it possible to enforce data hiding --- it is all based |
| 3998 | upon convention. (On the other hand, the Python implementation, |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3999 | written in C, can completely hide implementation details and control |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4000 | access to an object if necessary; this can be used by extensions to |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 4001 | Python written in C.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4002 | |
| 4003 | |
| 4004 | Clients should use data attributes with care --- clients may mess up |
| 4005 | invariants maintained by the methods by stamping on their data |
| 4006 | attributes. Note that clients may add data attributes of their own to |
| 4007 | an instance object without affecting the validity of the methods, as |
| 4008 | long as name conflicts are avoided --- again, a naming convention can |
| 4009 | save a lot of headaches here. |
| 4010 | |
| 4011 | |
| 4012 | There is no shorthand for referencing data attributes (or other |
| 4013 | methods!) from within methods. I find that this actually increases |
| 4014 | the readability of methods: there is no chance of confusing local |
| 4015 | variables and instance variables when glancing through a method. |
| 4016 | |
| 4017 | |
| 4018 | Conventionally, the first argument of methods is often called |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4019 | \code{self}. This is nothing more than a convention: the name |
| 4020 | \code{self} has absolutely no special meaning to Python. (Note, |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4021 | however, that by not following the convention your code may be less |
| 4022 | readable by other Python programmers, and it is also conceivable that |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 4023 | a \emph{class browser} program be written which relies upon such a |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4024 | convention.) |
| 4025 | |
| 4026 | |
| 4027 | Any function object that is a class attribute defines a method for |
| 4028 | instances of that class. It is not necessary that the function |
| 4029 | definition is textually enclosed in the class definition: assigning a |
| 4030 | function object to a local variable in the class is also ok. For |
| 4031 | example: |
| 4032 | |
| 4033 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4034 | # Function defined outside the class |
| 4035 | def f1(self, x, y): |
| 4036 | return min(x, x+y) |
| 4037 | |
| 4038 | class C: |
| 4039 | f = f1 |
| 4040 | def g(self): |
| 4041 | return 'hello world' |
| 4042 | h = g |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4043 | \end{verbatim} |
| 4044 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4045 | Now \code{f}, \code{g} and \code{h} are all attributes of class |
| 4046 | \class{C} that refer to function objects, and consequently they are all |
| 4047 | methods of instances of \class{C} --- \code{h} being exactly equivalent |
| 4048 | to \code{g}. Note that this practice usually only serves to confuse |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4049 | the reader of a program. |
| 4050 | |
| 4051 | |
| 4052 | Methods may call other methods by using method attributes of the |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 4053 | \code{self} argument: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4054 | |
| 4055 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4056 | class Bag: |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 4057 | def __init__(self): |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4058 | self.data = [] |
| 4059 | def add(self, x): |
| 4060 | self.data.append(x) |
| 4061 | def addtwice(self, x): |
| 4062 | self.add(x) |
| 4063 | self.add(x) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4064 | \end{verbatim} |
| 4065 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4066 | Methods may reference global names in the same way as ordinary |
| 4067 | functions. The global scope associated with a method is the module |
| 4068 | containing the class definition. (The class itself is never used as a |
| 4069 | global scope!) While one rarely encounters a good reason for using |
| 4070 | global data in a method, there are many legitimate uses of the global |
| 4071 | scope: for one thing, functions and modules imported into the global |
| 4072 | scope can be used by methods, as well as functions and classes defined |
| 4073 | in it. Usually, the class containing the method is itself defined in |
| 4074 | this global scope, and in the next section we'll find some good |
| 4075 | reasons why a method would want to reference its own class! |
| 4076 | |
| 4077 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 4078 | \section{Inheritance \label{inheritance}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4079 | |
| 4080 | Of course, a language feature would not be worthy of the name ``class'' |
| 4081 | without supporting inheritance. The syntax for a derived class |
| 4082 | definition looks as follows: |
| 4083 | |
| 4084 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4085 | class DerivedClassName(BaseClassName): |
| 4086 | <statement-1> |
| 4087 | . |
| 4088 | . |
| 4089 | . |
| 4090 | <statement-N> |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4091 | \end{verbatim} |
| 4092 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4093 | The name \class{BaseClassName} must be defined in a scope containing |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4094 | the derived class definition. Instead of a base class name, an |
| 4095 | expression is also allowed. This is useful when the base class is |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 4096 | defined in another module, |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4097 | |
| 4098 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4099 | class DerivedClassName(modname.BaseClassName): |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4100 | \end{verbatim} |
| 4101 | |
| 4102 | Execution of a derived class definition proceeds the same as for a |
| 4103 | base class. When the class object is constructed, the base class is |
| 4104 | remembered. This is used for resolving attribute references: if a |
| 4105 | requested attribute is not found in the class, it is searched in the |
| 4106 | base class. This rule is applied recursively if the base class itself |
| 4107 | is derived from some other class. |
| 4108 | |
| 4109 | There's nothing special about instantiation of derived classes: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4110 | \code{DerivedClassName()} creates a new instance of the class. Method |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4111 | references are resolved as follows: the corresponding class attribute |
| 4112 | is searched, descending down the chain of base classes if necessary, |
| 4113 | and the method reference is valid if this yields a function object. |
| 4114 | |
| 4115 | Derived classes may override methods of their base classes. Because |
| 4116 | methods have no special privileges when calling other methods of the |
| 4117 | same object, a method of a base class that calls another method |
| 4118 | defined in the same base class, may in fact end up calling a method of |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 4119 | a derived class that overrides it. (For \Cpp{} programmers: all methods |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 4120 | in Python are effectively \keyword{virtual}.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4121 | |
| 4122 | An overriding method in a derived class may in fact want to extend |
| 4123 | rather than simply replace the base class method of the same name. |
| 4124 | There is a simple way to call the base class method directly: just |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4125 | call \samp{BaseClassName.methodname(self, arguments)}. This is |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4126 | occasionally useful to clients as well. (Note that this only works if |
| 4127 | the base class is defined or imported directly in the global scope.) |
| 4128 | |
| 4129 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 4130 | \subsection{Multiple Inheritance \label{multiple}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4131 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 4132 | Python supports a limited form of multiple inheritance as well. A |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4133 | class definition with multiple base classes looks as follows: |
| 4134 | |
| 4135 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4136 | class DerivedClassName(Base1, Base2, Base3): |
| 4137 | <statement-1> |
| 4138 | . |
| 4139 | . |
| 4140 | . |
| 4141 | <statement-N> |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4142 | \end{verbatim} |
| 4143 | |
| 4144 | The only rule necessary to explain the semantics is the resolution |
| 4145 | rule used for class attribute references. This is depth-first, |
| 4146 | left-to-right. Thus, if an attribute is not found in |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4147 | \class{DerivedClassName}, it is searched in \class{Base1}, then |
| 4148 | (recursively) in the base classes of \class{Base1}, and only if it is |
| 4149 | not found there, it is searched in \class{Base2}, and so on. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4150 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4151 | (To some people breadth first --- searching \class{Base2} and |
| 4152 | \class{Base3} before the base classes of \class{Base1} --- looks more |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4153 | natural. However, this would require you to know whether a particular |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4154 | attribute of \class{Base1} is actually defined in \class{Base1} or in |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4155 | one of its base classes before you can figure out the consequences of |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4156 | a name conflict with an attribute of \class{Base2}. The depth-first |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4157 | rule makes no differences between direct and inherited attributes of |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4158 | \class{Base1}.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4159 | |
| 4160 | It is clear that indiscriminate use of multiple inheritance is a |
| 4161 | maintenance nightmare, given the reliance in Python on conventions to |
| 4162 | avoid accidental name conflicts. A well-known problem with multiple |
| 4163 | inheritance is a class derived from two classes that happen to have a |
| 4164 | common base class. While it is easy enough to figure out what happens |
| 4165 | in this case (the instance will have a single copy of ``instance |
| 4166 | variables'' or data attributes used by the common base class), it is |
| 4167 | not clear that these semantics are in any way useful. |
| 4168 | |
| 4169 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 4170 | \section{Private Variables \label{private}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4171 | |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 4172 | There is limited support for class-private |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4173 | identifiers. Any identifier of the form \code{__spam} (at least two |
Andrew M. Kuchling | cbddabf | 2004-03-21 22:12:45 +0000 | [diff] [blame] | 4174 | leading underscores, at most one trailing underscore) is textually |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4175 | replaced with \code{_classname__spam}, where \code{classname} is the |
| 4176 | current class name with leading underscore(s) stripped. This mangling |
| 4177 | is done without regard of the syntactic position of the identifier, so |
| 4178 | it can be used to define class-private instance and class variables, |
| 4179 | methods, as well as globals, and even to store instance variables |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 4180 | private to this class on instances of \emph{other} classes. Truncation |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4181 | may occur when the mangled name would be longer than 255 characters. |
| 4182 | Outside classes, or when the class name consists of only underscores, |
| 4183 | no mangling occurs. |
| 4184 | |
| 4185 | Name mangling is intended to give classes an easy way to define |
| 4186 | ``private'' instance variables and methods, without having to worry |
| 4187 | about instance variables defined by derived classes, or mucking with |
| 4188 | instance variables by code outside the class. Note that the mangling |
| 4189 | rules are designed mostly to avoid accidents; it still is possible for |
| 4190 | a determined soul to access or modify a variable that is considered |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 4191 | private. This can even be useful in special circumstances, such as in |
| 4192 | the debugger, and that's one reason why this loophole is not closed. |
| 4193 | (Buglet: derivation of a class with the same name as the base class |
| 4194 | makes use of private variables of the base class possible.) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4195 | |
| 4196 | Notice that code passed to \code{exec}, \code{eval()} or |
| 4197 | \code{evalfile()} does not consider the classname of the invoking |
| 4198 | class to be the current class; this is similar to the effect of the |
| 4199 | \code{global} statement, the effect of which is likewise restricted to |
| 4200 | code that is byte-compiled together. The same restriction applies to |
| 4201 | \code{getattr()}, \code{setattr()} and \code{delattr()}, as well as |
| 4202 | when referencing \code{__dict__} directly. |
| 4203 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4204 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 4205 | \section{Odds and Ends \label{odds}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4206 | |
| 4207 | Sometimes it is useful to have a data type similar to the Pascal |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 4208 | ``record'' or C ``struct'', bundling together a couple of named data |
Fred Drake | ed51494 | 2001-07-06 17:28:39 +0000 | [diff] [blame] | 4209 | items. An empty class definition will do nicely: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4210 | |
| 4211 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4212 | class Employee: |
| 4213 | pass |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4214 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4215 | john = Employee() # Create an empty employee record |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4216 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4217 | # Fill the fields of the record |
| 4218 | john.name = 'John Doe' |
| 4219 | john.dept = 'computer lab' |
| 4220 | john.salary = 1000 |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4221 | \end{verbatim} |
| 4222 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4223 | A piece of Python code that expects a particular abstract data type |
| 4224 | can often be passed a class that emulates the methods of that data |
| 4225 | type instead. For instance, if you have a function that formats some |
| 4226 | data from a file object, you can define a class with methods |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4227 | \method{read()} and \method{readline()} that gets the data from a string |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 4228 | buffer instead, and pass it as an argument.% (Unfortunately, this |
| 4229 | %technique has its limitations: a class can't define operations that |
| 4230 | %are accessed by special syntax such as sequence subscripting or |
| 4231 | %arithmetic operators, and assigning such a ``pseudo-file'' to |
| 4232 | %\code{sys.stdin} will not cause the interpreter to read further input |
| 4233 | %from it.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4234 | |
| 4235 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4236 | Instance method objects have attributes, too: \code{m.im_self} is the |
| 4237 | object of which the method is an instance, and \code{m.im_func} is the |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 4238 | function object corresponding to the method. |
| 4239 | |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4240 | |
| 4241 | \section{Exceptions Are Classes Too\label{exceptionClasses}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4242 | |
Raymond Hettinger | 8ee0060 | 2003-07-01 06:19:34 +0000 | [diff] [blame] | 4243 | User-defined exceptions are identified by classes as well. Using this |
| 4244 | mechanism it is possible to create extensible hierarchies of exceptions. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4245 | |
| 4246 | There are two new valid (semantic) forms for the raise statement: |
| 4247 | |
| 4248 | \begin{verbatim} |
| 4249 | raise Class, instance |
| 4250 | |
| 4251 | raise instance |
| 4252 | \end{verbatim} |
| 4253 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 4254 | In the first form, \code{instance} must be an instance of |
| 4255 | \class{Class} or of a class derived from it. The second form is a |
| 4256 | shorthand for: |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4257 | |
| 4258 | \begin{verbatim} |
| 4259 | raise instance.__class__, instance |
| 4260 | \end{verbatim} |
| 4261 | |
Raymond Hettinger | 8ee0060 | 2003-07-01 06:19:34 +0000 | [diff] [blame] | 4262 | A class in an except clause is compatible with an exception if it is the same |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4263 | class or a base class thereof (but not the other way around --- an |
| 4264 | except clause listing a derived class is not compatible with a base |
| 4265 | class). For example, the following code will print B, C, D in that |
| 4266 | order: |
| 4267 | |
| 4268 | \begin{verbatim} |
| 4269 | class B: |
| 4270 | pass |
| 4271 | class C(B): |
| 4272 | pass |
| 4273 | class D(C): |
| 4274 | pass |
| 4275 | |
| 4276 | for c in [B, C, D]: |
| 4277 | try: |
| 4278 | raise c() |
| 4279 | except D: |
| 4280 | print "D" |
| 4281 | except C: |
| 4282 | print "C" |
| 4283 | except B: |
| 4284 | print "B" |
| 4285 | \end{verbatim} |
| 4286 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 4287 | Note that if the except clauses were reversed (with |
| 4288 | \samp{except B} first), it would have printed B, B, B --- the first |
| 4289 | matching except clause is triggered. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4290 | |
| 4291 | When an error message is printed for an unhandled exception which is a |
| 4292 | class, the class name is printed, then a colon and a space, and |
| 4293 | finally the instance converted to a string using the built-in function |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4294 | \function{str()}. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4295 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4296 | |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4297 | \section{Iterators\label{iterators}} |
| 4298 | |
Raymond Hettinger | b1e5b50 | 2004-02-12 09:50:42 +0000 | [diff] [blame] | 4299 | By now, you've probably noticed that most container objects can be looped |
Fred Drake | e6ed33a | 2004-02-12 14:35:18 +0000 | [diff] [blame] | 4300 | over using a \keyword{for} statement: |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4301 | |
| 4302 | \begin{verbatim} |
| 4303 | for element in [1, 2, 3]: |
| 4304 | print element |
| 4305 | for element in (1, 2, 3): |
| 4306 | print element |
| 4307 | for key in {'one':1, 'two':2}: |
| 4308 | print key |
| 4309 | for char in "123": |
| 4310 | print char |
| 4311 | for line in open("myfile.txt"): |
| 4312 | print line |
| 4313 | \end{verbatim} |
| 4314 | |
| 4315 | This style of access is clear, concise, and convenient. The use of iterators |
Fred Drake | e6ed33a | 2004-02-12 14:35:18 +0000 | [diff] [blame] | 4316 | pervades and unifies Python. Behind the scenes, the \keyword{for} |
| 4317 | statement calls \function{iter()} on the container object. The |
| 4318 | function returns an iterator object that defines the method |
| 4319 | \method{next()} which accesses elements in the container one at a |
| 4320 | time. When there are no more elements, \method{next()} raises a |
| 4321 | \exception{StopIteration} exception which tells the \keyword{for} loop |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4322 | to terminate. This example shows how it all works: |
| 4323 | |
| 4324 | \begin{verbatim} |
| 4325 | >>> s = 'abc' |
| 4326 | >>> it = iter(s) |
| 4327 | >>> it |
| 4328 | <iterator object at 0x00A1DB50> |
| 4329 | >>> it.next() |
| 4330 | 'a' |
| 4331 | >>> it.next() |
| 4332 | 'b' |
| 4333 | >>> it.next() |
| 4334 | 'c' |
| 4335 | >>> it.next() |
| 4336 | |
| 4337 | Traceback (most recent call last): |
| 4338 | File "<pyshell#6>", line 1, in -toplevel- |
| 4339 | it.next() |
| 4340 | StopIteration |
| 4341 | \end{verbatim} |
| 4342 | |
| 4343 | Having seen the mechanics behind the iterator protocol, it is easy to add |
| 4344 | iterator behavior to your classes. Define a \method{__iter__()} method |
| 4345 | which returns an object with a \method{next()} method. If the class defines |
| 4346 | \method{next()}, then \method{__iter__()} can just return \code{self}: |
| 4347 | |
| 4348 | \begin{verbatim} |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 4349 | class Reverse: |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4350 | "Iterator for looping over a sequence backwards" |
| 4351 | def __init__(self, data): |
| 4352 | self.data = data |
| 4353 | self.index = len(data) |
| 4354 | def __iter__(self): |
| 4355 | return self |
| 4356 | def next(self): |
| 4357 | if self.index == 0: |
| 4358 | raise StopIteration |
| 4359 | self.index = self.index - 1 |
| 4360 | return self.data[self.index] |
| 4361 | |
| 4362 | >>> for char in Reverse('spam'): |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 4363 | ... print char |
| 4364 | ... |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4365 | m |
| 4366 | a |
| 4367 | p |
| 4368 | s |
| 4369 | \end{verbatim} |
| 4370 | |
| 4371 | |
| 4372 | \section{Generators\label{generators}} |
| 4373 | |
| 4374 | Generators are a simple and powerful tool for creating iterators. They are |
| 4375 | written like regular functions but use the \keyword{yield} statement whenever |
Raymond Hettinger | 21f9fce | 2004-07-10 16:11:03 +0000 | [diff] [blame] | 4376 | they want to return data. Each time \method{next()} is called, the |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4377 | generator resumes where it left-off (it remembers all the data values and |
| 4378 | which statement was last executed). An example shows that generators can |
| 4379 | be trivially easy to create: |
| 4380 | |
| 4381 | \begin{verbatim} |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 4382 | def reverse(data): |
| 4383 | for index in range(len(data)-1, -1, -1): |
| 4384 | yield data[index] |
| 4385 | |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4386 | >>> for char in reverse('golf'): |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 4387 | ... print char |
| 4388 | ... |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4389 | f |
| 4390 | l |
| 4391 | o |
| 4392 | g |
| 4393 | \end{verbatim} |
| 4394 | |
| 4395 | Anything that can be done with generators can also be done with class based |
| 4396 | iterators as described in the previous section. What makes generators so |
| 4397 | compact is that the \method{__iter__()} and \method{next()} methods are |
| 4398 | created automatically. |
| 4399 | |
Raymond Hettinger | b233e54 | 2003-07-15 23:16:01 +0000 | [diff] [blame] | 4400 | Another key feature is that the local variables and execution state |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4401 | are automatically saved between calls. This made the function easier to write |
| 4402 | and much more clear than an approach using class variables like |
| 4403 | \code{self.index} and \code{self.data}. |
| 4404 | |
| 4405 | In addition to automatic method creation and saving program state, when |
| 4406 | generators terminate, they automatically raise \exception{StopIteration}. |
| 4407 | In combination, these features make it easy to create iterators with no |
| 4408 | more effort than writing a regular function. |
| 4409 | |
Raymond Hettinger | 170a622 | 2004-05-19 19:45:19 +0000 | [diff] [blame] | 4410 | \section{Generator Expressions\label{genexps}} |
| 4411 | |
| 4412 | Some simple generators can be coded succinctly as expressions using a syntax |
Raymond Hettinger | 2d1a2aa | 2004-06-03 14:13:04 +0000 | [diff] [blame] | 4413 | similar to list comprehensions but with parentheses instead of brackets. These |
Raymond Hettinger | 170a622 | 2004-05-19 19:45:19 +0000 | [diff] [blame] | 4414 | expressions are designed for situations where the generator is used right |
| 4415 | away by an enclosing function. Generator expressions are more compact but |
Fred Drake | 22ec5c3 | 2004-06-03 17:19:25 +0000 | [diff] [blame] | 4416 | less versatile than full generator definitions and tend to be more memory |
Raymond Hettinger | 170a622 | 2004-05-19 19:45:19 +0000 | [diff] [blame] | 4417 | friendly than equivalent list comprehensions. |
| 4418 | |
| 4419 | Examples: |
| 4420 | |
| 4421 | \begin{verbatim} |
| 4422 | >>> sum(i*i for i in range(10)) # sum of squares |
| 4423 | 285 |
| 4424 | |
| 4425 | >>> xvec = [10, 20, 30] |
| 4426 | >>> yvec = [7, 5, 3] |
| 4427 | >>> sum(x*y for x,y in zip(xvec, yvec)) # dot product |
| 4428 | 260 |
| 4429 | |
| 4430 | >>> from math import pi, sin |
| 4431 | >>> sine_table = dict((x, sin(x*pi/180)) for x in range(0, 91)) |
| 4432 | |
| 4433 | >>> unique_words = set(word for line in page for word in line.split()) |
| 4434 | |
| 4435 | >>> valedictorian = max((student.gpa, student.name) for student in graduates) |
| 4436 | |
| 4437 | >>> data = 'golf' |
| 4438 | >>> list(data[i] for i in range(len(data)-1,-1,-1)) |
| 4439 | ['f', 'l', 'o', 'g'] |
| 4440 | |
| 4441 | \end{verbatim} |
| 4442 | |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 4443 | |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4444 | |
| 4445 | \chapter{Brief Tour of the Standard Library \label{briefTour}} |
| 4446 | |
| 4447 | |
| 4448 | \section{Operating System Interface\label{os-interface}} |
| 4449 | |
| 4450 | The \ulink{\module{os}}{../lib/module-os.html} |
| 4451 | module provides dozens of functions for interacting with the |
| 4452 | operating system: |
| 4453 | |
| 4454 | \begin{verbatim} |
| 4455 | >>> import os |
Raymond Hettinger | b7a10d1 | 2003-12-06 20:12:00 +0000 | [diff] [blame] | 4456 | >>> os.system('time 0:02') |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4457 | 0 |
| 4458 | >>> os.getcwd() # Return the current working directory |
| 4459 | 'C:\\Python24' |
| 4460 | >>> os.chdir('/server/accesslogs') |
| 4461 | \end{verbatim} |
| 4462 | |
| 4463 | Be sure to use the \samp{import os} style instead of |
| 4464 | \samp{from os import *}. This will keep \function{os.open()} from |
| 4465 | shadowing the builtin \function{open()} function which operates much |
| 4466 | differently. |
| 4467 | |
| 4468 | The builtin \function{dir()} and \function{help()} functions are useful |
| 4469 | as interactive aids for working with large modules like \module{os}: |
| 4470 | |
| 4471 | \begin{verbatim} |
| 4472 | >>> import os |
| 4473 | >>> dir(os) |
Raymond Hettinger | f62444a | 2003-12-05 07:53:50 +0000 | [diff] [blame] | 4474 | <returns a list of all module functions> |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4475 | >>> help(os) |
| 4476 | <returns an extensive manual page created from the module's docstrings> |
| 4477 | \end{verbatim} |
| 4478 | |
| 4479 | For daily file and directory management tasks, the |
| 4480 | \ulink{\module{shutil}}{../lib/module-shutil.html} |
| 4481 | module provides a higher level interface that is easier to use: |
| 4482 | |
| 4483 | \begin{verbatim} |
| 4484 | >>> import shutil |
| 4485 | >>> shutil.copyfile('data.db', 'archive.db') |
Raymond Hettinger | f62444a | 2003-12-05 07:53:50 +0000 | [diff] [blame] | 4486 | >>> shutil.move('/build/executables', 'installdir') |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4487 | \end{verbatim} |
| 4488 | |
| 4489 | |
| 4490 | \section{File Wildcards\label{file-wildcards}} |
| 4491 | |
| 4492 | The \ulink{\module{glob}}{../lib/module-glob.html} |
| 4493 | module provides a function for making file lists from directory |
| 4494 | wildcard searches: |
| 4495 | |
| 4496 | \begin{verbatim} |
| 4497 | >>> import glob |
| 4498 | >>> glob.glob('*.py') |
| 4499 | ['primes.py', 'random.py', 'quote.py'] |
| 4500 | \end{verbatim} |
| 4501 | |
| 4502 | |
| 4503 | \section{Command Line Arguments\label{command-line-arguments}} |
| 4504 | |
| 4505 | Common utility scripts often invoke processing command line arguments. |
| 4506 | These arguments are stored in the |
| 4507 | \ulink{\module{sys}}{../lib/module-sys.html}\ module's \var{argv} |
| 4508 | attribute as a list. For instance the following output results from |
| 4509 | running \samp{python demo.py one two three} at the command line: |
| 4510 | |
| 4511 | \begin{verbatim} |
| 4512 | >>> import sys |
Raymond Hettinger | ec3402f | 2003-12-05 06:39:54 +0000 | [diff] [blame] | 4513 | >>> print sys.argv |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4514 | ['demo.py', 'one', 'two', 'three'] |
| 4515 | \end{verbatim} |
| 4516 | |
| 4517 | The \ulink{\module{getopt}}{../lib/module-getopt.html} |
| 4518 | module processes \var{sys.argv} using the conventions of the \UNIX{} |
| 4519 | \function{getopt()} function. More powerful and flexible command line |
| 4520 | processing is provided by the |
| 4521 | \ulink{\module{optparse}}{../lib/module-optparse.html} module. |
| 4522 | |
| 4523 | |
| 4524 | \section{Error Output Redirection and Program Termination\label{stderr}} |
| 4525 | |
| 4526 | The \ulink{\module{sys}}{../lib/module-sys.html} |
| 4527 | module also has attributes for \var{stdin}, \var{stdout}, and |
| 4528 | \var{stderr}. The latter is useful for emitting warnings and error |
| 4529 | messages to make them visible even when \var{stdout} has been redirected: |
| 4530 | |
| 4531 | \begin{verbatim} |
| 4532 | >>> sys.stderr.write('Warning, log file not found starting a new one') |
| 4533 | Warning, log file not found starting a new one |
| 4534 | \end{verbatim} |
| 4535 | |
| 4536 | The most direct way to terminate a script is to use \samp{sys.exit()}. |
| 4537 | |
| 4538 | |
| 4539 | \section{String Pattern Matching\label{string-pattern-matching}} |
| 4540 | |
| 4541 | The \ulink{\module{re}}{../lib/module-re.html} |
| 4542 | module provides regular expression tools for advanced string processing. |
Raymond Hettinger | b7a10d1 | 2003-12-06 20:12:00 +0000 | [diff] [blame] | 4543 | For complex matching and manipulation, regular expressions offer succinct, |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4544 | optimized solutions: |
| 4545 | |
| 4546 | \begin{verbatim} |
| 4547 | >>> import re |
| 4548 | >>> re.findall(r'\bf[a-z]*', 'which foot or hand fell fastest') |
| 4549 | ['foot', 'fell', 'fastest'] |
| 4550 | >>> re.sub(r'(\b[a-z]+) \1', r'\1', 'cat in the the hat') |
| 4551 | 'cat in the hat' |
| 4552 | \end{verbatim} |
| 4553 | |
Raymond Hettinger | b7a10d1 | 2003-12-06 20:12:00 +0000 | [diff] [blame] | 4554 | When only simple capabilities are needed, string methods are preferred |
| 4555 | because they are easier to read and debug: |
| 4556 | |
| 4557 | \begin{verbatim} |
| 4558 | >>> 'tea for too'.replace('too', 'two') |
| 4559 | 'tea for two' |
| 4560 | \end{verbatim} |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4561 | |
| 4562 | \section{Mathematics\label{mathematics}} |
| 4563 | |
Raymond Hettinger | ec3402f | 2003-12-05 06:39:54 +0000 | [diff] [blame] | 4564 | The \ulink{\module{math}}{../lib/module-math.html} module gives |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4565 | access to the underlying C library functions for floating point math: |
| 4566 | |
| 4567 | \begin{verbatim} |
| 4568 | >>> import math |
| 4569 | >>> math.cos(math.pi / 4.0) |
| 4570 | 0.70710678118654757 |
| 4571 | >>> math.log(1024, 2) |
| 4572 | 10.0 |
| 4573 | \end{verbatim} |
| 4574 | |
| 4575 | The \ulink{\module{random}}{../lib/module-random.html} |
| 4576 | module provides tools for making random selections: |
| 4577 | |
| 4578 | \begin{verbatim} |
| 4579 | >>> import random |
| 4580 | >>> random.choice(['apple', 'pear', 'banana']) |
| 4581 | 'apple' |
| 4582 | >>> random.sample(xrange(100), 10) # sampling without replacement |
| 4583 | [30, 83, 16, 4, 8, 81, 41, 50, 18, 33] |
| 4584 | >>> random.random() # random float |
| 4585 | 0.17970987693706186 |
| 4586 | >>> random.randrange(6) # random integer chosen from range(6) |
| 4587 | 4 |
| 4588 | \end{verbatim} |
| 4589 | |
| 4590 | |
| 4591 | \section{Internet Access\label{internet-access}} |
| 4592 | |
| 4593 | There are a number of modules for accessing the internet and processing |
| 4594 | internet protocols. Two of the simplest are |
| 4595 | \ulink{\module{urllib2}}{../lib/module-urllib2.html} |
| 4596 | for retrieving data from urls and |
| 4597 | \ulink{\module{smtplib}}{../lib/module-smtplib.html} |
| 4598 | for sending mail: |
| 4599 | |
| 4600 | \begin{verbatim} |
| 4601 | >>> import urllib2 |
| 4602 | >>> for line in urllib2.urlopen('http://tycho.usno.navy.mil/cgi-bin/timer.pl'): |
Raymond Hettinger | e148595 | 2004-05-31 22:53:25 +0000 | [diff] [blame] | 4603 | ... if 'EST' in line: # look for Eastern Standard Time |
| 4604 | ... print line |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4605 | |
| 4606 | <BR>Nov. 25, 09:43:32 PM EST |
| 4607 | |
| 4608 | >>> import smtplib |
| 4609 | >>> server = smtplib.SMTP('localhost') |
Raymond Hettinger | a8aebce | 2004-05-25 16:08:28 +0000 | [diff] [blame] | 4610 | >>> server.sendmail('soothsayer@example.org', 'jceasar@example.org', |
| 4611 | """To: jceasar@example.org |
| 4612 | From: soothsayer@example.org |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4613 | |
| 4614 | Beware the Ides of March. |
| 4615 | """) |
| 4616 | >>> server.quit() |
| 4617 | \end{verbatim} |
| 4618 | |
| 4619 | |
| 4620 | \section{Dates and Times\label{dates-and-times}} |
| 4621 | |
| 4622 | The \ulink{\module{datetime}}{../lib/module-datetime.html} module |
| 4623 | supplies classes for manipulating dates and times in both simple |
| 4624 | and complex ways. While date and time arithmetic is supported, the |
| 4625 | focus of the implementation is on efficient member extraction for |
| 4626 | output formatting and manipulation. The module also supports objects |
| 4627 | that are time zone aware. |
| 4628 | |
| 4629 | \begin{verbatim} |
| 4630 | # dates are easily constructed and formatted |
| 4631 | >>> from datetime import date |
| 4632 | >>> now = date.today() |
| 4633 | >>> now |
| 4634 | datetime.date(2003, 12, 2) |
| 4635 | >>> now.strftime("%m-%d-%y or %d%b %Y is a %A on the %d day of %B") |
| 4636 | '12-02-03 or 02Dec 2003 is a Tuesday on the 02 day of December' |
| 4637 | |
| 4638 | # dates support calendar arithmetic |
| 4639 | >>> birthday = date(1964, 7, 31) |
| 4640 | >>> age = now - birthday |
| 4641 | >>> age.days |
| 4642 | 14368 |
| 4643 | \end{verbatim} |
| 4644 | |
| 4645 | |
| 4646 | \section{Data Compression\label{data-compression}} |
| 4647 | |
| 4648 | Common data archiving and compression formats are directly supported |
Raymond Hettinger | f62444a | 2003-12-05 07:53:50 +0000 | [diff] [blame] | 4649 | by modules including: |
| 4650 | \ulink{\module{zlib}}{../lib/module-zlib.html}, |
| 4651 | \ulink{\module{gzip}}{../lib/module-gzip.html}, |
| 4652 | \ulink{\module{bz2}}{../lib/module-bz2.html}, |
| 4653 | \ulink{\module{zipfile}}{../lib/module-zipfile.html}, and |
| 4654 | \ulink{\module{tarfile}}{../lib/module-tarfile.html}. |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4655 | |
| 4656 | \begin{verbatim} |
| 4657 | >>> import zlib |
| 4658 | >>> s = 'witch which has which witches wrist watch' |
| 4659 | >>> len(s) |
| 4660 | 41 |
| 4661 | >>> t = zlib.compress(s) |
| 4662 | >>> len(t) |
| 4663 | 37 |
| 4664 | >>> zlib.decompress(t) |
| 4665 | 'witch which has which witches wrist watch' |
| 4666 | >>> zlib.crc32(t) |
| 4667 | -1438085031 |
| 4668 | \end{verbatim} |
| 4669 | |
| 4670 | |
| 4671 | \section{Performance Measurement\label{performance-measurement}} |
| 4672 | |
| 4673 | Some Python users develop a deep interest in knowing the relative |
| 4674 | performance between different approaches to the same problem. |
| 4675 | Python provides a measurement tool that answers those questions |
| 4676 | immediately. |
| 4677 | |
| 4678 | For example, it may be tempting to use the tuple packing and unpacking |
| 4679 | feature instead of the traditional approach to swapping arguments. |
| 4680 | The \ulink{\module{timeit}}{../lib/module-timeit.html} module |
Raymond Hettinger | 707483f | 2004-03-26 07:56:23 +0000 | [diff] [blame] | 4681 | quickly demonstrates a modest performance advantage: |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4682 | |
| 4683 | \begin{verbatim} |
| 4684 | >>> from timeit import Timer |
Raymond Hettinger | ec3402f | 2003-12-05 06:39:54 +0000 | [diff] [blame] | 4685 | >>> Timer('t=a; a=b; b=t', 'a=1; b=2').timeit() |
Raymond Hettinger | 707483f | 2004-03-26 07:56:23 +0000 | [diff] [blame] | 4686 | 0.57535828626024577 |
Raymond Hettinger | ec3402f | 2003-12-05 06:39:54 +0000 | [diff] [blame] | 4687 | >>> Timer('a,b = b,a', 'a=1; b=2').timeit() |
Raymond Hettinger | 707483f | 2004-03-26 07:56:23 +0000 | [diff] [blame] | 4688 | 0.54962537085770791 |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4689 | \end{verbatim} |
| 4690 | |
| 4691 | In contrast to \module{timeit}'s fine level of granularity, the |
Johannes Gijsbers | 24f141a | 2004-09-25 00:55:38 +0000 | [diff] [blame] | 4692 | \ulink{\module{profile}}{../lib/module-profile.html} and \module{pstats} |
| 4693 | modules provide tools for identifying time critical sections in larger blocks |
| 4694 | of code. |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4695 | |
| 4696 | |
| 4697 | \section{Quality Control\label{quality-control}} |
| 4698 | |
| 4699 | One approach for developing high quality software is to write tests for |
| 4700 | each function as it is developed and to run those tests frequently during |
| 4701 | the development process. |
| 4702 | |
| 4703 | The \ulink{\module{doctest}}{../lib/module-doctest.html} module provides |
| 4704 | a tool for scanning a module and validating tests embedded in a program's |
| 4705 | docstrings. Test construction is as simple as cutting-and-pasting a |
| 4706 | typical call along with its results into the docstring. This improves |
| 4707 | the documentation by providing the user with an example and it allows the |
| 4708 | doctest module to make sure the code remains true to the documentation: |
| 4709 | |
| 4710 | \begin{verbatim} |
| 4711 | def average(values): |
| 4712 | """Computes the arithmetic mean of a list of numbers. |
| 4713 | |
| 4714 | >>> print average([20, 30, 70]) |
| 4715 | 40.0 |
| 4716 | """ |
| 4717 | return sum(values, 0.0) / len(values) |
| 4718 | |
| 4719 | import doctest |
| 4720 | doctest.testmod() # automatically validate the embedded tests |
| 4721 | \end{verbatim} |
| 4722 | |
| 4723 | The \ulink{\module{unittest}}{../lib/module-unittest.html} module is not |
| 4724 | as effortless as the \module{doctest} module, but it allows a more |
| 4725 | comprehensive set of tests to be maintained in a separate file: |
| 4726 | |
| 4727 | \begin{verbatim} |
| 4728 | import unittest |
| 4729 | |
| 4730 | class TestStatisticalFunctions(unittest.TestCase): |
| 4731 | |
| 4732 | def test_average(self): |
| 4733 | self.assertEqual(average([20, 30, 70]), 40.0) |
| 4734 | self.assertEqual(round(average([1, 5, 7]), 1), 4.3) |
| 4735 | self.assertRaises(ZeroDivisionError, average, []) |
| 4736 | self.assertRaises(TypeError, average, 20, 30, 70) |
| 4737 | |
| 4738 | unittest.main() # Calling from the command line invokes all tests |
| 4739 | \end{verbatim} |
| 4740 | |
| 4741 | \section{Batteries Included\label{batteries-included}} |
| 4742 | |
Raymond Hettinger | f62444a | 2003-12-05 07:53:50 +0000 | [diff] [blame] | 4743 | Python has a ``batteries included'' philosophy. This is best seen |
| 4744 | through the sophisticated and robust capabilities of its larger |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4745 | packages. For example: |
| 4746 | |
Johannes Gijsbers | 27ebcae | 2004-09-24 23:25:25 +0000 | [diff] [blame] | 4747 | \begin{itemize} |
| 4748 | \item The \ulink{\module{xmlrpclib}}{../lib/module-xmlrpclib.html} and |
| 4749 | \ulink{\module{SimpleXMLRPCServer}}{../lib/module-SimpleXMLRPCServer.html} |
| 4750 | modules make implementing remote procedure calls into an almost trivial task. |
| 4751 | Despite the names, no direct knowledge or handling of XML is needed. |
| 4752 | \item The \ulink{\module{email}}{../lib/module-email.html} package is a library |
| 4753 | for managing email messages, including MIME and other RFC 2822-based message |
Johannes Gijsbers | 24f141a | 2004-09-25 00:55:38 +0000 | [diff] [blame] | 4754 | documents. Unlike \module{smptlib} and \module{poplib} which actually send |
| 4755 | and receive messages, the email package has a complete toolset for building |
| 4756 | or decoding complex message structures (including attachments) and for |
Johannes Gijsbers | 27ebcae | 2004-09-24 23:25:25 +0000 | [diff] [blame] | 4757 | implementing internet encoding and header protocols. |
| 4758 | \item The \ulink{\module{xml.dom}}{../lib/module-xml.dom.html} and |
| 4759 | \ulink{\module{xml.sax}}{../lib/module-xml.sax.html} packages provide robust |
| 4760 | support for parsing this popular data interchange format. Likewise, the |
| 4761 | \ulink{\module{csv}}{../lib/module-csv.html} module supports direct reads and |
| 4762 | writes in a common database format. Together, these modules and packages |
| 4763 | greatly simplify data interchange between python applications and other |
| 4764 | tools. |
| 4765 | \item Internationalization is supported by a number of modules including |
| 4766 | \ulink{\module{gettext}}{../lib/module-gettext.html}, |
| 4767 | \ulink{\module{locale}}{../lib/module-locale.html}, and the |
| 4768 | \ulink{\module{codecs}}{../lib/module-codecs.html} package. |
| 4769 | \end{itemize} |
Raymond Hettinger | 8772d4e | 2003-12-03 22:23:46 +0000 | [diff] [blame] | 4770 | |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4771 | \chapter{Brief Tour of the Standard Library -- Part II\label{briefTourTwo}} |
| 4772 | |
Raymond Hettinger | 4ccf336 | 2004-05-26 13:57:54 +0000 | [diff] [blame] | 4773 | This second tour covers more advanced modules that support professional |
| 4774 | programming needs. These modules rarely occur in small scripts. |
| 4775 | |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4776 | |
| 4777 | \section{Output Formatting\label{output-formatting}} |
| 4778 | |
| 4779 | The \ulink{\module{repr}}{../lib/module-repr.html} module provides an |
| 4780 | version of \function{repr()} for abbreviated displays of large or deeply |
| 4781 | nested containers: |
| 4782 | |
| 4783 | \begin{verbatim} |
| 4784 | >>> import repr |
| 4785 | >>> repr.repr(set('supercalifragilisticexpialidocious')) |
| 4786 | "set(['a', 'c', 'd', 'e', 'f', 'g', ...])" |
| 4787 | \end{verbatim} |
| 4788 | |
| 4789 | The \ulink{\module{pprint}}{../lib/module-pprint.html} module offers |
| 4790 | more sophisticated control over printing both built-in and user defined |
| 4791 | objects in a way that is readable by the interpreter. When the result |
| 4792 | is longer than one line, the ``pretty printer'' adds line breaks and |
| 4793 | indentation to more clearly reveal data structure: |
| 4794 | |
| 4795 | \begin{verbatim} |
| 4796 | >>> import pprint |
| 4797 | >>> t = [[[['black', 'cyan'], 'white', ['green', 'red']], [['magenta', |
| 4798 | ... 'yellow'], 'blue']]] |
| 4799 | ... |
| 4800 | >>> pprint.pprint(t, width=30) |
| 4801 | [[[['black', 'cyan'], |
| 4802 | 'white', |
| 4803 | ['green', 'red']], |
| 4804 | [['magenta', 'yellow'], |
| 4805 | 'blue']]] |
| 4806 | \end{verbatim} |
| 4807 | |
| 4808 | The \ulink{\module{textwrap}}{../lib/module-textwrap.html} module |
| 4809 | formats paragraphs of text to fit a given screen width: |
| 4810 | |
| 4811 | \begin{verbatim} |
| 4812 | >>> import textwrap |
| 4813 | >>> doc = """The wrap() method is just like fill() except that it returns |
| 4814 | ... a list of strings instead of one big string with newlines to separate |
| 4815 | ... the wrapped lines.""" |
| 4816 | ... |
| 4817 | >>> print textwrap.fill(doc, width=40) |
| 4818 | The wrap() method is just like fill() |
| 4819 | except that it returns a list of strings |
| 4820 | instead of one big string with newlines |
| 4821 | to separate the wrapped lines. |
| 4822 | \end{verbatim} |
| 4823 | |
| 4824 | The \ulink{\module{locale}}{../lib/module-locale.html} module accesses |
| 4825 | a database of culture specific data formats. The grouping attribute |
| 4826 | of locale's format function provides a direct way of formatting numbers |
| 4827 | with group separators: |
| 4828 | |
| 4829 | \begin{verbatim} |
| 4830 | >>> import locale |
| 4831 | >>> locale.setlocale(locale.LC_ALL, 'English_United States.1252') |
| 4832 | 'English_United States.1252' |
| 4833 | >>> conv = locale.localeconv() # get a mapping of conventions |
| 4834 | >>> x = 1234567.8 |
| 4835 | >>> locale.format("%d", x, grouping=True) |
| 4836 | '1,234,567' |
| 4837 | >>> locale.format("%s%.*f", (conv['currency_symbol'], |
| 4838 | ... conv['int_frac_digits'], x), grouping=True) |
| 4839 | '$1,234,567.80' |
| 4840 | \end{verbatim} |
| 4841 | |
| 4842 | |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4843 | \section{Templating\label{templating}} |
| 4844 | |
| 4845 | The \ulink{\module{string}}{../lib/module-string.html} module includes a |
| 4846 | versatile \class{Template} class with a simplified syntax suitable for |
| 4847 | editing by end-users. This allows users to customize their applications |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4848 | without having to alter the application. |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4849 | |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4850 | The format uses placeholder names formed by \samp{\$} with valid Python |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4851 | identifiers (alphanumeric characters and underscores). Surrounding the |
| 4852 | placeholder with braces allows it to be followed by more alphanumeric letters |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4853 | with no intervening spaces. Writing \samp{\$\$} creates a single escaped |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4854 | \samp{\$}: |
| 4855 | |
| 4856 | \begin{verbatim} |
| 4857 | >>> from string import Template |
| 4858 | >>> t = Template('${village}folk send $$10 to $cause.') |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4859 | >>> t.substitute(village='Nottingham', cause='the ditch fund') |
| 4860 | 'Nottinghamfolk send $10 to the ditch fund.' |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4861 | \end{verbatim} |
| 4862 | |
| 4863 | The \method{substitute} method raises a \exception{KeyError} when a |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4864 | placeholder is not supplied in a dictionary or a keyword argument. For |
| 4865 | mail-merge style applications, user supplied data may be incomplete and the |
| 4866 | \method{safe_substitute} method may be more appropriate --- it will leave |
| 4867 | placeholders unchanged if data is missing: |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4868 | |
| 4869 | \begin{verbatim} |
| 4870 | >>> t = Template('Return the $item to $owner.') |
| 4871 | >>> d = dict(item='unladen swallow') |
| 4872 | >>> t.substitute(d) |
| 4873 | Traceback (most recent call last): |
| 4874 | . . . |
| 4875 | KeyError: 'owner' |
| 4876 | >>> t.safe_substitute(d) |
| 4877 | 'Return the unladen swallow to $owner.' |
| 4878 | \end{verbatim} |
| 4879 | |
| 4880 | Template subclasses can specify a custom delimiter. For example, a batch |
| 4881 | renaming utility for a photo browser may elect to use percent signs for |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4882 | placeholders such as the current date, image sequence number, or file format: |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4883 | |
| 4884 | \begin{verbatim} |
| 4885 | >>> import time, os.path |
| 4886 | >>> photofiles = ['img_1074.jpg', 'img_1076.jpg', 'img_1077.jpg'] |
| 4887 | >>> class BatchRename(Template): |
| 4888 | ... delimiter = '%' |
| 4889 | >>> fmt = raw_input('Enter rename style (%d-date %n-seqnum %f-format): ') |
| 4890 | Enter rename style (%d-date %n-seqnum %f-format): Ashley_%n%f |
| 4891 | |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4892 | >>> t = BatchRename(fmt) |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4893 | >>> date = time.strftime('%d%b%y') |
| 4894 | >>> for i, filename in enumerate(photofiles): |
| 4895 | ... base, ext = os.path.splitext(filename) |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4896 | ... newname = t.substitute(d=date, n=i, f=ext) |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4897 | ... print '%s --> %s' % (filename, newname) |
| 4898 | |
| 4899 | img_1074.jpg --> Ashley_0.jpg |
| 4900 | img_1076.jpg --> Ashley_1.jpg |
| 4901 | img_1077.jpg --> Ashley_2.jpg |
| 4902 | \end{verbatim} |
| 4903 | |
Raymond Hettinger | 879ddf3 | 2004-09-14 06:32:20 +0000 | [diff] [blame] | 4904 | Another application for templating is separating program logic from the |
| 4905 | details of multiple output formats. The makes it possible to substitute |
| 4906 | custom templates for XML files, plain text reports, and HMTL web reports. |
Raymond Hettinger | 29c6a79 | 2004-09-14 05:21:42 +0000 | [diff] [blame] | 4907 | |
| 4908 | |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4909 | \section{Working with Binary Data Record Layouts\label{binary-formats}} |
| 4910 | |
| 4911 | The \ulink{\module{struct}}{../lib/module-struct.html} module provides |
| 4912 | \function{pack()} and \function{unpack()} functions for working with |
| 4913 | variable length binary record formats. The following example shows how |
| 4914 | to loop through header information in a ZIP file (with pack codes |
| 4915 | \code{"H"} and \code{"L"} representing two and four byte unsigned |
| 4916 | numbers respectively): |
| 4917 | |
| 4918 | \begin{verbatim} |
| 4919 | import struct |
| 4920 | |
| 4921 | data = open('myfile.zip', 'rb').read() |
| 4922 | start = 0 |
| 4923 | for i in range(3): # show the first 3 file headers |
| 4924 | start += 14 |
| 4925 | fields = struct.unpack('LLLHH', data[start:start+16]) |
| 4926 | crc32, comp_size, uncomp_size, filenamesize, extra_size = fields |
| 4927 | |
| 4928 | start += 16 |
| 4929 | filename = data[start:start+filenamesize] |
| 4930 | start += filenamesize |
| 4931 | extra = data[start:start+extra_size] |
| 4932 | print filename, hex(crc32), comp_size, uncomp_size |
| 4933 | |
| 4934 | start += extra_size + comp_size # skip to the next header |
| 4935 | \end{verbatim} |
| 4936 | |
| 4937 | |
| 4938 | \section{Multi-threading\label{multi-threading}} |
| 4939 | |
| 4940 | Threading is a technique for decoupling tasks which are not sequentially |
Raymond Hettinger | d3fe239 | 2004-08-16 05:11:04 +0000 | [diff] [blame] | 4941 | dependent. Threads can be used to improve the responsiveness of |
| 4942 | applications that accept user input while other tasks run in the |
| 4943 | background. A related use case is running I/O in parallel with |
| 4944 | computations in another thread. |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4945 | |
Raymond Hettinger | d3fe239 | 2004-08-16 05:11:04 +0000 | [diff] [blame] | 4946 | The following code shows how the high level |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4947 | \ulink{\module{threading}}{../lib/module-threading.html} module can run |
| 4948 | tasks in background while the main program continues to run: |
| 4949 | |
| 4950 | \begin{verbatim} |
| 4951 | import threading, zipfile |
| 4952 | |
| 4953 | class AsyncZip(threading.Thread): |
| 4954 | def __init__(self, infile, outfile): |
| 4955 | threading.Thread.__init__(self) |
| 4956 | self.infile = infile |
| 4957 | self.outfile = outfile |
| 4958 | def run(self): |
| 4959 | f = zipfile.ZipFile(self.outfile, 'w', zipfile.ZIP_DEFLATED) |
| 4960 | f.write(self.infile) |
| 4961 | f.close() |
| 4962 | print 'Finished background zip of: ', self.infile |
| 4963 | |
Raymond Hettinger | d3fe239 | 2004-08-16 05:11:04 +0000 | [diff] [blame] | 4964 | background = AsyncZip('mydata.txt', 'myarchive.zip') |
| 4965 | background.start() |
| 4966 | print 'The main program continues to run in foreground.' |
| 4967 | |
| 4968 | background.join() # Wait for the background task to finish |
| 4969 | print 'Main program waited until background was done.' |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4970 | \end{verbatim} |
| 4971 | |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 4972 | The principal challenge of multi-threaded applications is coordinating |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4973 | threads that share data or other resources. To that end, the threading |
| 4974 | module provides a number of synchronization primitives including locks, |
| 4975 | events, condition variables, and semaphores. |
| 4976 | |
| 4977 | While those tools are powerful, minor design errors can result in |
Raymond Hettinger | d3fe239 | 2004-08-16 05:11:04 +0000 | [diff] [blame] | 4978 | problems that are difficult to reproduce. So, the preferred approach |
| 4979 | to task coordination is to concentrate all access to a resource |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4980 | in a single thread and then using the |
| 4981 | \ulink{\module{Queue}}{../lib/module-Queue.html} module to feed that |
Raymond Hettinger | d3fe239 | 2004-08-16 05:11:04 +0000 | [diff] [blame] | 4982 | thread with requests from other threads. Applications using |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4983 | \class{Queue} objects for inter-thread communication and coordination |
Raymond Hettinger | d3fe239 | 2004-08-16 05:11:04 +0000 | [diff] [blame] | 4984 | are easier to design, more readable, and more reliable. |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 4985 | |
| 4986 | |
| 4987 | \section{Logging\label{logging}} |
| 4988 | |
| 4989 | The \ulink{\module{logging}}{../lib/module-logging.html} module offers |
| 4990 | a full featured and flexible logging system. At its simplest, log |
| 4991 | messages are sent to a file or to \code{sys.stderr}: |
| 4992 | |
| 4993 | \begin{verbatim} |
| 4994 | import logging |
| 4995 | logging.debug('Debugging information') |
| 4996 | logging.info('Informational message') |
| 4997 | logging.warning('Warning:config file %s not found', 'server.conf') |
| 4998 | logging.error('Error occurred') |
| 4999 | logging.critical('Critical error -- shutting down') |
| 5000 | \end{verbatim} |
| 5001 | |
| 5002 | This produces the following output: |
| 5003 | |
| 5004 | \begin{verbatim} |
| 5005 | WARNING:root:Warning:config file server.conf not found |
| 5006 | ERROR:root:Error occurred |
| 5007 | CRITICAL:root:Critical error -- shutting down |
| 5008 | \end{verbatim} |
| 5009 | |
| 5010 | By default, informational and debugging messages are suppressed and the |
| 5011 | output is sent to standard error. Other output options include routing |
| 5012 | messages through email, datagrams, sockets, or to an HTTP Server. New |
Fred Drake | 1b89656 | 2004-07-01 14:26:31 +0000 | [diff] [blame] | 5013 | filters can select different routing based on message priority: |
| 5014 | \constant{DEBUG}, \constant{INFO}, \constant{WARNING}, \constant{ERROR}, |
| 5015 | and \constant{CRITICAL}. |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 5016 | |
| 5017 | The logging system can be configured directly from Python or can be |
| 5018 | loaded from a user editable configuration file for customized logging |
| 5019 | without altering the application. |
| 5020 | |
| 5021 | |
| 5022 | \section{Weak References\label{weak-references}} |
| 5023 | |
| 5024 | Python does automatic memory management (reference counting for most |
| 5025 | objects and garbage collection to eliminate cycles). The memory is |
| 5026 | freed shortly after the last reference to it has been eliminated. |
| 5027 | |
| 5028 | This approach works fine for most applications but occasionally there |
| 5029 | is a need to track objects only as long as they are being used by |
| 5030 | something else. Unfortunately, just tracking them creates a reference |
| 5031 | that makes them permanent. The |
| 5032 | \ulink{\module{weakref}}{../lib/module-weakref.html} module provides |
| 5033 | tools for tracking objects without creating a reference. When the |
| 5034 | object is no longer needed, it is automatically removed from a weakref |
| 5035 | table and a callback is triggered for weakref objects. Typical |
| 5036 | applications include caching objects that are expensive to create: |
| 5037 | |
| 5038 | \begin{verbatim} |
| 5039 | >>> import weakref, gc |
| 5040 | >>> class A: |
| 5041 | ... def __init__(self, value): |
| 5042 | ... self.value = value |
| 5043 | ... def __repr__(self): |
| 5044 | ... return str(self.value) |
| 5045 | ... |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5046 | >>> a = A(10) # create a reference |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 5047 | >>> d = weakref.WeakValueDictionary() |
| 5048 | >>> d['primary'] = a # does not create a reference |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5049 | >>> d['primary'] # fetch the object if it is still alive |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 5050 | 10 |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5051 | >>> del a # remove the one reference |
Raymond Hettinger | 846865b | 2004-05-26 13:52:59 +0000 | [diff] [blame] | 5052 | >>> gc.collect() # run garbage collection right away |
| 5053 | 0 |
| 5054 | >>> d['primary'] # entry was automatically removed |
| 5055 | Traceback (most recent call last): |
| 5056 | File "<pyshell#108>", line 1, in -toplevel- |
| 5057 | d['primary'] # entry was automatically removed |
| 5058 | File "C:/PY24/lib/weakref.py", line 46, in __getitem__ |
| 5059 | o = self.data[key]() |
| 5060 | KeyError: 'primary' |
| 5061 | \end{verbatim} |
| 5062 | |
| 5063 | \section{Tools for Working with Lists\label{list-tools}} |
| 5064 | |
| 5065 | Many data structure needs can be met with the built-in list type. |
| 5066 | However, sometimes there is a need for alternative implementations |
| 5067 | with different performance trade-offs. |
| 5068 | |
| 5069 | The \ulink{\module{array}}{../lib/module-array.html} module provides an |
| 5070 | \class{array()} object that is like a list that stores only homogenous |
| 5071 | data but stores it more compactly. The following example shows an array |
| 5072 | of numbers stored as two byte unsigned binary numbers (typecode |
| 5073 | \code{"H"}) rather than the usual 16 bytes per entry for regular lists |
| 5074 | of python int objects: |
| 5075 | |
| 5076 | \begin{verbatim} |
| 5077 | >>> from array import array |
| 5078 | >>> a = array('H', [4000, 10, 700, 22222]) |
| 5079 | >>> sum(a) |
| 5080 | 26932 |
| 5081 | >>> a[1:3] |
| 5082 | array('H', [10, 700]) |
| 5083 | \end{verbatim} |
| 5084 | |
| 5085 | The \ulink{\module{collections}}{../lib/module-collections.html} module |
| 5086 | provides a \class{deque()} object that is like a list with faster |
| 5087 | appends and pops from the left side but slower lookups in the middle. |
| 5088 | These objects are well suited for implementing queues and breadth first |
| 5089 | tree searches: |
| 5090 | |
| 5091 | \begin{verbatim} |
| 5092 | >>> from collections import deque |
| 5093 | >>> d = deque(["task1", "task2", "task3"]) |
| 5094 | >>> d.append("task4") |
| 5095 | >>> print "Handling", d.popleft() |
| 5096 | Handling task1 |
| 5097 | |
| 5098 | unsearched = deque([starting_node]) |
| 5099 | def breadth_first_search(unsearched): |
| 5100 | node = unsearched.popleft() |
| 5101 | for m in gen_moves(node): |
| 5102 | if is_goal(m): |
| 5103 | return m |
| 5104 | unsearched.append(m) |
| 5105 | \end{verbatim} |
| 5106 | |
| 5107 | In addition to alternative list implementations, the library also offers |
| 5108 | other tools such as the \ulink{\module{bisect}}{../lib/module-bisect.html} |
| 5109 | module with functions for manipulating sorted lists: |
| 5110 | |
| 5111 | \begin{verbatim} |
| 5112 | >>> import bisect |
| 5113 | >>> scores = [(100, 'perl'), (200, 'tcl'), (400, 'lua'), (500, 'python')] |
| 5114 | >>> bisect.insort(scores, (300, 'ruby')) |
| 5115 | >>> scores |
| 5116 | [(100, 'perl'), (200, 'tcl'), (300, 'ruby'), (400, 'lua'), (500, 'python')] |
| 5117 | \end{verbatim} |
| 5118 | |
| 5119 | The \ulink{\module{heapq}}{../lib/module-heapq.html} module provides |
| 5120 | functions for implementing heaps based on regular lists. The lowest |
| 5121 | valued entry is always kept at position zero. This is useful for |
| 5122 | applications which repeatedly access the smallest element but do not |
| 5123 | want to run a full list sort: |
| 5124 | |
| 5125 | \begin{verbatim} |
| 5126 | >>> from heapq import heapify, heappop, heappush |
| 5127 | >>> data = [1, 3, 5, 7, 9, 2, 4, 6, 8, 0] |
| 5128 | >>> heapify(data) # rearrange the list into heap order |
| 5129 | >>> heappush(data, -5) # add a new entry |
| 5130 | >>> [heappop(data) for i in range(3)] # fetch the three smallest entries |
| 5131 | [-5, 0, 1] |
| 5132 | \end{verbatim} |
| 5133 | |
| 5134 | |
Raymond Hettinger | 081483c | 2004-07-08 09:33:00 +0000 | [diff] [blame] | 5135 | \section{Decimal Floating Point Arithmetic\label{decimal-fp}} |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5136 | |
Raymond Hettinger | 9499658 | 2004-07-09 06:00:32 +0000 | [diff] [blame] | 5137 | The \ulink{\module{decimal}}{../lib/module-decimal.html} module offers a |
| 5138 | \class{Decimal} datatype for decimal floating point arithmetic. Compared to |
| 5139 | the built-in \class{float} implementation of binary floating point, the new |
| 5140 | class is especially helpful for financial applications and other uses which |
| 5141 | require exact decimal representation, control over precision, control over |
| 5142 | rounding to meet legal or regulatory requirements, tracking of significant |
| 5143 | decimal places, or for applications where the user expects the results to |
Raymond Hettinger | 44dc13b | 2004-07-11 12:49:47 +0000 | [diff] [blame] | 5144 | match calculations done by hand. |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5145 | |
Raymond Hettinger | 081483c | 2004-07-08 09:33:00 +0000 | [diff] [blame] | 5146 | For example, calculating a 5\%{} tax on a 70 cent phone charge gives |
| 5147 | different results in decimal floating point and binary floating point. |
| 5148 | The difference becomes significant if the results are rounded to the |
| 5149 | nearest cent: |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5150 | |
| 5151 | \begin{verbatim} |
| 5152 | >>> from decimal import * |
| 5153 | >>> Decimal('0.70') * Decimal('1.05') |
| 5154 | Decimal("0.7350") |
| 5155 | >>> .70 * 1.05 |
| 5156 | 0.73499999999999999 |
| 5157 | \end{verbatim} |
| 5158 | |
Raymond Hettinger | 44dc13b | 2004-07-11 12:49:47 +0000 | [diff] [blame] | 5159 | The \class{Decimal} result keeps a trailing zero, automatically inferring four |
| 5160 | place significance from the two digit multiplicands. Decimal reproduces |
| 5161 | mathematics as done by hand and avoids issues that can arise when binary |
| 5162 | floating point cannot exactly represent decimal quantities. |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5163 | |
| 5164 | Exact representation enables the \class{Decimal} class to perform |
| 5165 | modulo calculations and equality tests that are unsuitable for binary |
| 5166 | floating point: |
| 5167 | |
| 5168 | \begin{verbatim} |
| 5169 | >>> Decimal('1.00') % Decimal('.10') |
| 5170 | Decimal("0.00") |
| 5171 | >>> 1.00 % 0.10 |
| 5172 | 0.09999999999999995 |
| 5173 | |
| 5174 | >>> sum([Decimal('0.1')]*10) == Decimal('1.0') |
| 5175 | True |
| 5176 | >>> sum([0.1]*10) == 1.0 |
| 5177 | False |
| 5178 | \end{verbatim} |
| 5179 | |
Raymond Hettinger | 44dc13b | 2004-07-11 12:49:47 +0000 | [diff] [blame] | 5180 | The \module{decimal} module provides arithmetic with as much precision as |
| 5181 | needed: |
Raymond Hettinger | 68a37ac | 2004-07-01 12:56:54 +0000 | [diff] [blame] | 5182 | |
| 5183 | \begin{verbatim} |
| 5184 | >>> getcontext().prec = 36 |
| 5185 | >>> Decimal(1) / Decimal(7) |
| 5186 | Decimal("0.142857142857142857142857142857142857") |
| 5187 | \end{verbatim} |
| 5188 | |
| 5189 | |
| 5190 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 5191 | \chapter{What Now? \label{whatNow}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5192 | |
Fred Drake | 979d041 | 2001-04-03 17:41:56 +0000 | [diff] [blame] | 5193 | Reading this tutorial has probably reinforced your interest in using |
| 5194 | Python --- you should be eager to apply Python to solve your |
| 5195 | real-world problems. Now what should you do? |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5196 | |
Fred Drake | 979d041 | 2001-04-03 17:41:56 +0000 | [diff] [blame] | 5197 | You should read, or at least page through, the |
| 5198 | \citetitle[../lib/lib.html]{Python Library Reference}, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5199 | which gives complete (though terse) reference material about types, |
| 5200 | functions, and modules that can save you a lot of time when writing |
| 5201 | Python programs. The standard Python distribution includes a |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 5202 | \emph{lot} of code in both C and Python; there are modules to read |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5203 | \UNIX{} mailboxes, retrieve documents via HTTP, generate random |
| 5204 | numbers, parse command-line options, write CGI programs, compress |
| 5205 | data, and a lot more; skimming through the Library Reference will give |
| 5206 | you an idea of what's available. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5207 | |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 5208 | The major Python Web site is \url{http://www.python.org/}; it contains |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5209 | code, documentation, and pointers to Python-related pages around the |
Fred Drake | 17f690f | 2001-07-14 02:14:42 +0000 | [diff] [blame] | 5210 | Web. This Web site is mirrored in various places around the |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5211 | world, such as Europe, Japan, and Australia; a mirror may be faster |
| 5212 | than the main site, depending on your geographical location. A more |
Fred Drake | c0fcbc1 | 1999-04-29 02:30:04 +0000 | [diff] [blame] | 5213 | informal site is \url{http://starship.python.net/}, which contains a |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5214 | bunch of Python-related personal home pages; many people have |
Raymond Hettinger | 8ee0060 | 2003-07-01 06:19:34 +0000 | [diff] [blame] | 5215 | downloadable software there. Many more user-created Python modules |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 5216 | can be found in the \ulink{Python Package |
| 5217 | Index}{http://www.python.org/pypi} (PyPI). |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5218 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5219 | For Python-related questions and problem reports, you can post to the |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 5220 | newsgroup \newsgroup{comp.lang.python}, or send them to the mailing |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 5221 | list at \email{python-list@python.org}. The newsgroup and mailing list |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 5222 | are gatewayed, so messages posted to one will automatically be |
Raymond Hettinger | 8ee0060 | 2003-07-01 06:19:34 +0000 | [diff] [blame] | 5223 | forwarded to the other. There are around 120 postings a day (with peaks |
| 5224 | up to several hundred), |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 5225 | % Postings figure based on average of last six months activity as |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 5226 | % reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182 |
| 5227 | % days = 116.9 msgs / day and steadily increasing. |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 5228 | asking (and answering) questions, suggesting new features, and |
| 5229 | announcing new modules. Before posting, be sure to check the list of |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 5230 | \ulink{Frequently Asked Questions}{http://www.python.org/doc/faq/} (also called the FAQ), or look for it in the |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 5231 | \file{Misc/} directory of the Python source distribution. Mailing |
| 5232 | list archives are available at \url{http://www.python.org/pipermail/}. |
| 5233 | The FAQ answers many of the questions that come up again and again, |
| 5234 | and may already contain the solution for your problem. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5235 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5236 | |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 5237 | \appendix |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5238 | |
Fred Drake | d0c7137 | 2002-10-28 19:28:22 +0000 | [diff] [blame] | 5239 | \chapter{Interactive Input Editing and History Substitution\label{interacting}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5240 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5241 | Some versions of the Python interpreter support editing of the current |
| 5242 | input line and history substitution, similar to facilities found in |
| 5243 | the Korn shell and the GNU Bash shell. This is implemented using the |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 5244 | \emph{GNU Readline} library, which supports Emacs-style and vi-style |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5245 | editing. This library has its own documentation which I won't |
Fred Drake | cc09e8d | 1998-12-28 21:21:36 +0000 | [diff] [blame] | 5246 | duplicate here; however, the basics are easily explained. The |
| 5247 | interactive editing and history described here are optionally |
| 5248 | available in the \UNIX{} and CygWin versions of the interpreter. |
| 5249 | |
| 5250 | This chapter does \emph{not} document the editing facilities of Mark |
| 5251 | Hammond's PythonWin package or the Tk-based environment, IDLE, |
| 5252 | distributed with Python. The command line history recall which |
| 5253 | operates within DOS boxes on NT and some other DOS and Windows flavors |
| 5254 | is yet another beast. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5255 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 5256 | \section{Line Editing \label{lineEditing}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5257 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5258 | If supported, input line editing is active whenever the interpreter |
| 5259 | prints a primary or secondary prompt. The current line can be edited |
| 5260 | using the conventional Emacs control characters. The most important |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5261 | of these are: \kbd{C-A} (Control-A) moves the cursor to the beginning |
| 5262 | of the line, \kbd{C-E} to the end, \kbd{C-B} moves it one position to |
| 5263 | the left, \kbd{C-F} to the right. Backspace erases the character to |
| 5264 | the left of the cursor, \kbd{C-D} the character to its right. |
| 5265 | \kbd{C-K} kills (erases) the rest of the line to the right of the |
| 5266 | cursor, \kbd{C-Y} yanks back the last killed string. |
| 5267 | \kbd{C-underscore} undoes the last change you made; it can be repeated |
| 5268 | for cumulative effect. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5269 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 5270 | \section{History Substitution \label{history}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5271 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5272 | History substitution works as follows. All non-empty input lines |
| 5273 | issued are saved in a history buffer, and when a new prompt is given |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5274 | you are positioned on a new line at the bottom of this buffer. |
| 5275 | \kbd{C-P} moves one line up (back) in the history buffer, |
| 5276 | \kbd{C-N} moves one down. Any line in the history buffer can be |
| 5277 | edited; an asterisk appears in front of the prompt to mark a line as |
| 5278 | modified. Pressing the \kbd{Return} key passes the current line to |
| 5279 | the interpreter. \kbd{C-R} starts an incremental reverse search; |
| 5280 | \kbd{C-S} starts a forward search. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5281 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 5282 | \section{Key Bindings \label{keyBindings}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5283 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5284 | The key bindings and some other parameters of the Readline library can |
| 5285 | be customized by placing commands in an initialization file called |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5286 | \file{\~{}/.inputrc}. Key bindings have the form |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5287 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5288 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5289 | key-name: function-name |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5290 | \end{verbatim} |
| 5291 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5292 | or |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5293 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5294 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5295 | "string": function-name |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5296 | \end{verbatim} |
| 5297 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5298 | and options can be set with |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5299 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5300 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5301 | set option-name value |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5302 | \end{verbatim} |
| 5303 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5304 | For example: |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5305 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5306 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5307 | # I prefer vi-style editing: |
| 5308 | set editing-mode vi |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5309 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5310 | # Edit using a single line: |
| 5311 | set horizontal-scroll-mode On |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5312 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 5313 | # Rebind some keys: |
| 5314 | Meta-h: backward-kill-word |
| 5315 | "\C-u": universal-argument |
| 5316 | "\C-x\C-r": re-read-init-file |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5317 | \end{verbatim} |
| 5318 | |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5319 | Note that the default binding for \kbd{Tab} in Python is to insert a |
| 5320 | \kbd{Tab} character instead of Readline's default filename completion |
| 5321 | function. If you insist, you can override this by putting |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5322 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5323 | \begin{verbatim} |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5324 | Tab: complete |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 5325 | \end{verbatim} |
| 5326 | |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5327 | in your \file{\~{}/.inputrc}. (Of course, this makes it harder to |
Fred Drake | f5c87c4 | 2003-09-11 06:06:26 +0000 | [diff] [blame] | 5328 | type indented continuation lines if you're accustomed to using |
| 5329 | \kbd{Tab} for that purpose.) |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5330 | |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 5331 | Automatic completion of variable and module names is optionally |
| 5332 | available. To enable it in the interpreter's interactive mode, add |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5333 | the following to your startup file:\footnote{ |
| 5334 | Python will execute the contents of a file identified by the |
| 5335 | \envvar{PYTHONSTARTUP} environment variable when you start an |
| 5336 | interactive interpreter.} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 5337 | \refstmodindex{rlcompleter}\refbimodindex{readline} |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 5338 | |
| 5339 | \begin{verbatim} |
| 5340 | import rlcompleter, readline |
| 5341 | readline.parse_and_bind('tab: complete') |
| 5342 | \end{verbatim} |
| 5343 | |
Fred Drake | 0181552 | 2001-07-18 19:21:12 +0000 | [diff] [blame] | 5344 | This binds the \kbd{Tab} key to the completion function, so hitting |
| 5345 | the \kbd{Tab} key twice suggests completions; it looks at Python |
| 5346 | statement names, the current local variables, and the available module |
| 5347 | names. For dotted expressions such as \code{string.a}, it will |
Raymond Hettinger | c7a2656 | 2003-08-12 00:01:17 +0000 | [diff] [blame] | 5348 | evaluate the expression up to the final \character{.} and then |
Fred Drake | 0181552 | 2001-07-18 19:21:12 +0000 | [diff] [blame] | 5349 | suggest completions from the attributes of the resulting object. Note |
| 5350 | that this may execute application-defined code if an object with a |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 5351 | \method{__getattr__()} method is part of the expression. |
| 5352 | |
Fred Drake | 0181552 | 2001-07-18 19:21:12 +0000 | [diff] [blame] | 5353 | A more capable startup file might look like this example. Note that |
| 5354 | this deletes the names it creates once they are no longer needed; this |
| 5355 | is done since the startup file is executed in the same namespace as |
| 5356 | the interactive commands, and removing the names avoids creating side |
| 5357 | effects in the interactive environments. You may find it convenient |
Fred Drake | 626d472 | 2003-09-11 04:28:13 +0000 | [diff] [blame] | 5358 | to keep some of the imported modules, such as |
| 5359 | \ulink{\module{os}}{../lib/module-os.html}, which turn |
Fred Drake | 0181552 | 2001-07-18 19:21:12 +0000 | [diff] [blame] | 5360 | out to be needed in most sessions with the interpreter. |
| 5361 | |
| 5362 | \begin{verbatim} |
| 5363 | # Add auto-completion and a stored history file of commands to your Python |
| 5364 | # interactive interpreter. Requires Python 2.0+, readline. Autocomplete is |
| 5365 | # bound to the Esc key by default (you can change it - see readline docs). |
| 5366 | # |
| 5367 | # Store the file in ~/.pystartup, and set an environment variable to point |
Raymond Hettinger | fa6cce1 | 2003-07-11 18:58:11 +0000 | [diff] [blame] | 5368 | # to it: "export PYTHONSTARTUP=/max/home/itamar/.pystartup" in bash. |
Fred Drake | 0181552 | 2001-07-18 19:21:12 +0000 | [diff] [blame] | 5369 | # |
| 5370 | # Note that PYTHONSTARTUP does *not* expand "~", so you have to put in the |
| 5371 | # full path to your home directory. |
| 5372 | |
| 5373 | import atexit |
| 5374 | import os |
| 5375 | import readline |
| 5376 | import rlcompleter |
| 5377 | |
| 5378 | historyPath = os.path.expanduser("~/.pyhistory") |
| 5379 | |
| 5380 | def save_history(historyPath=historyPath): |
| 5381 | import readline |
| 5382 | readline.write_history_file(historyPath) |
| 5383 | |
| 5384 | if os.path.exists(historyPath): |
| 5385 | readline.read_history_file(historyPath) |
| 5386 | |
| 5387 | atexit.register(save_history) |
| 5388 | del os, atexit, readline, rlcompleter, save_history, historyPath |
| 5389 | \end{verbatim} |
| 5390 | |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 5391 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 5392 | \section{Commentary \label{commentary}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5393 | |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 5394 | This facility is an enormous step forward compared to earlier versions |
| 5395 | of the interpreter; however, some wishes are left: It would be nice if |
| 5396 | the proper indentation were suggested on continuation lines (the |
| 5397 | parser knows if an indent token is required next). The completion |
| 5398 | mechanism might use the interpreter's symbol table. A command to |
| 5399 | check (or even suggest) matching parentheses, quotes, etc., would also |
| 5400 | be useful. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 5401 | |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 5402 | |
Fred Drake | d0c7137 | 2002-10-28 19:28:22 +0000 | [diff] [blame] | 5403 | \chapter{Floating Point Arithmetic: Issues and Limitations\label{fp-issues}} |
Fred Drake | 4271310 | 2003-12-30 16:15:35 +0000 | [diff] [blame] | 5404 | \sectionauthor{Tim Peters}{tim_one@users.sourceforge.net} |
Fred Drake | 417d667 | 2001-06-08 16:24:58 +0000 | [diff] [blame] | 5405 | |
| 5406 | Floating-point numbers are represented in computer hardware as |
| 5407 | base 2 (binary) fractions. For example, the decimal fraction |
| 5408 | |
| 5409 | \begin{verbatim} |
| 5410 | 0.125 |
| 5411 | \end{verbatim} |
| 5412 | |
| 5413 | has value 1/10 + 2/100 + 5/1000, and in the same way the binary fraction |
| 5414 | |
| 5415 | \begin{verbatim} |
| 5416 | 0.001 |
| 5417 | \end{verbatim} |
| 5418 | |
| 5419 | has value 0/2 + 0/4 + 1/8. These two fractions have identical values, |
| 5420 | the only real difference being that the first is written in base 10 |
| 5421 | fractional notation, and the second in base 2. |
| 5422 | |
| 5423 | Unfortunately, most decimal fractions cannot be represented exactly as |
| 5424 | binary fractions. A consequence is that, in general, the decimal |
| 5425 | floating-point numbers you enter are only approximated by the binary |
| 5426 | floating-point numbers actually stored in the machine. |
| 5427 | |
| 5428 | The problem is easier to understand at first in base 10. Consider the |
| 5429 | fraction 1/3. You can approximate that as a base 10 fraction: |
| 5430 | |
| 5431 | \begin{verbatim} |
| 5432 | 0.3 |
| 5433 | \end{verbatim} |
| 5434 | |
| 5435 | or, better, |
| 5436 | |
| 5437 | \begin{verbatim} |
| 5438 | 0.33 |
| 5439 | \end{verbatim} |
| 5440 | |
| 5441 | or, better, |
| 5442 | |
| 5443 | \begin{verbatim} |
| 5444 | 0.333 |
| 5445 | \end{verbatim} |
| 5446 | |
| 5447 | and so on. No matter how many digits you're willing to write down, the |
| 5448 | result will never be exactly 1/3, but will be an increasingly better |
| 5449 | approximation to 1/3. |
| 5450 | |
| 5451 | In the same way, no matter how many base 2 digits you're willing to |
| 5452 | use, the decimal value 0.1 cannot be represented exactly as a base 2 |
| 5453 | fraction. In base 2, 1/10 is the infinitely repeating fraction |
| 5454 | |
| 5455 | \begin{verbatim} |
| 5456 | 0.0001100110011001100110011001100110011001100110011... |
| 5457 | \end{verbatim} |
| 5458 | |
| 5459 | Stop at any finite number of bits, and you get an approximation. This |
| 5460 | is why you see things like: |
| 5461 | |
| 5462 | \begin{verbatim} |
| 5463 | >>> 0.1 |
| 5464 | 0.10000000000000001 |
| 5465 | \end{verbatim} |
| 5466 | |
| 5467 | On most machines today, that is what you'll see if you enter 0.1 at |
| 5468 | a Python prompt. You may not, though, because the number of bits |
| 5469 | used by the hardware to store floating-point values can vary across |
| 5470 | machines, and Python only prints a decimal approximation to the true |
| 5471 | decimal value of the binary approximation stored by the machine. On |
| 5472 | most machines, if Python were to print the true decimal value of |
| 5473 | the binary approximation stored for 0.1, it would have to display |
| 5474 | |
| 5475 | \begin{verbatim} |
| 5476 | >>> 0.1 |
| 5477 | 0.1000000000000000055511151231257827021181583404541015625 |
| 5478 | \end{verbatim} |
| 5479 | |
| 5480 | instead! The Python prompt (implicitly) uses the builtin |
| 5481 | \function{repr()} function to obtain a string version of everything it |
| 5482 | displays. For floats, \code{repr(\var{float})} rounds the true |
| 5483 | decimal value to 17 significant digits, giving |
| 5484 | |
| 5485 | \begin{verbatim} |
| 5486 | 0.10000000000000001 |
| 5487 | \end{verbatim} |
| 5488 | |
| 5489 | \code{repr(\var{float})} produces 17 significant digits because it |
| 5490 | turns out that's enough (on most machines) so that |
| 5491 | \code{eval(repr(\var{x})) == \var{x}} exactly for all finite floats |
| 5492 | \var{x}, but rounding to 16 digits is not enough to make that true. |
| 5493 | |
| 5494 | Note that this is in the very nature of binary floating-point: this is |
| 5495 | not a bug in Python, it is not a bug in your code either, and you'll |
| 5496 | see the same kind of thing in all languages that support your |
Tim Peters | fa9e273 | 2001-06-17 21:57:17 +0000 | [diff] [blame] | 5497 | hardware's floating-point arithmetic (although some languages may |
| 5498 | not \emph{display} the difference by default, or in all output modes). |
Fred Drake | 417d667 | 2001-06-08 16:24:58 +0000 | [diff] [blame] | 5499 | |
| 5500 | Python's builtin \function{str()} function produces only 12 |
| 5501 | significant digits, and you may wish to use that instead. It's |
| 5502 | unusual for \code{eval(str(\var{x}))} to reproduce \var{x}, but the |
| 5503 | output may be more pleasant to look at: |
| 5504 | |
| 5505 | \begin{verbatim} |
| 5506 | >>> print str(0.1) |
| 5507 | 0.1 |
| 5508 | \end{verbatim} |
| 5509 | |
| 5510 | It's important to realize that this is, in a real sense, an illusion: |
| 5511 | the value in the machine is not exactly 1/10, you're simply rounding |
| 5512 | the \emph{display} of the true machine value. |
| 5513 | |
| 5514 | Other surprises follow from this one. For example, after seeing |
| 5515 | |
| 5516 | \begin{verbatim} |
| 5517 | >>> 0.1 |
| 5518 | 0.10000000000000001 |
| 5519 | \end{verbatim} |
| 5520 | |
| 5521 | you may be tempted to use the \function{round()} function to chop it |
| 5522 | back to the single digit you expect. But that makes no difference: |
| 5523 | |
| 5524 | \begin{verbatim} |
| 5525 | >>> round(0.1, 1) |
| 5526 | 0.10000000000000001 |
| 5527 | \end{verbatim} |
| 5528 | |
| 5529 | The problem is that the binary floating-point value stored for "0.1" |
| 5530 | was already the best possible binary approximation to 1/10, so trying |
| 5531 | to round it again can't make it better: it was already as good as it |
| 5532 | gets. |
| 5533 | |
| 5534 | Another consequence is that since 0.1 is not exactly 1/10, adding 0.1 |
| 5535 | to itself 10 times may not yield exactly 1.0, either: |
| 5536 | |
| 5537 | \begin{verbatim} |
| 5538 | >>> sum = 0.0 |
| 5539 | >>> for i in range(10): |
| 5540 | ... sum += 0.1 |
| 5541 | ... |
| 5542 | >>> sum |
| 5543 | 0.99999999999999989 |
| 5544 | \end{verbatim} |
| 5545 | |
| 5546 | Binary floating-point arithmetic holds many surprises like this. The |
| 5547 | problem with "0.1" is explained in precise detail below, in the |
| 5548 | "Representation Error" section. See |
| 5549 | \citetitle[http://www.lahey.com/float.htm]{The Perils of Floating |
| 5550 | Point} for a more complete account of other common surprises. |
| 5551 | |
| 5552 | As that says near the end, ``there are no easy answers.'' Still, |
| 5553 | don't be unduly wary of floating-point! The errors in Python float |
| 5554 | operations are inherited from the floating-point hardware, and on most |
| 5555 | machines are on the order of no more than 1 part in 2**53 per |
| 5556 | operation. That's more than adequate for most tasks, but you do need |
| 5557 | to keep in mind that it's not decimal arithmetic, and that every float |
| 5558 | operation can suffer a new rounding error. |
| 5559 | |
| 5560 | While pathological cases do exist, for most casual use of |
| 5561 | floating-point arithmetic you'll see the result you expect in the end |
| 5562 | if you simply round the display of your final results to the number of |
| 5563 | decimal digits you expect. \function{str()} usually suffices, and for |
Tim Peters | 7497966 | 2004-07-07 02:32:36 +0000 | [diff] [blame] | 5564 | finer control see the discussion of Python's \code{\%} format |
Fred Drake | 417d667 | 2001-06-08 16:24:58 +0000 | [diff] [blame] | 5565 | operator: the \code{\%g}, \code{\%f} and \code{\%e} format codes |
| 5566 | supply flexible and easy ways to round float results for display. |
| 5567 | |
| 5568 | |
| 5569 | \section{Representation Error |
| 5570 | \label{fp-error}} |
| 5571 | |
| 5572 | This section explains the ``0.1'' example in detail, and shows how |
| 5573 | you can perform an exact analysis of cases like this yourself. Basic |
| 5574 | familiarity with binary floating-point representation is assumed. |
| 5575 | |
| 5576 | \dfn{Representation error} refers to that some (most, actually) |
| 5577 | decimal fractions cannot be represented exactly as binary (base 2) |
| 5578 | fractions. This is the chief reason why Python (or Perl, C, \Cpp, |
| 5579 | Java, Fortran, and many others) often won't display the exact decimal |
| 5580 | number you expect: |
| 5581 | |
| 5582 | \begin{verbatim} |
| 5583 | >>> 0.1 |
| 5584 | 0.10000000000000001 |
| 5585 | \end{verbatim} |
| 5586 | |
| 5587 | Why is that? 1/10 is not exactly representable as a binary fraction. |
| 5588 | Almost all machines today (November 2000) use IEEE-754 floating point |
| 5589 | arithmetic, and almost all platforms map Python floats to IEEE-754 |
| 5590 | "double precision". 754 doubles contain 53 bits of precision, so on |
| 5591 | input the computer strives to convert 0.1 to the closest fraction it can |
| 5592 | of the form \var{J}/2**\var{N} where \var{J} is an integer containing |
| 5593 | exactly 53 bits. Rewriting |
| 5594 | |
| 5595 | \begin{verbatim} |
| 5596 | 1 / 10 ~= J / (2**N) |
| 5597 | \end{verbatim} |
| 5598 | |
| 5599 | as |
| 5600 | |
| 5601 | \begin{verbatim} |
| 5602 | J ~= 2**N / 10 |
| 5603 | \end{verbatim} |
| 5604 | |
| 5605 | and recalling that \var{J} has exactly 53 bits (is \code{>= 2**52} but |
| 5606 | \code{< 2**53}), the best value for \var{N} is 56: |
| 5607 | |
| 5608 | \begin{verbatim} |
| 5609 | >>> 2L**52 |
| 5610 | 4503599627370496L |
| 5611 | >>> 2L**53 |
| 5612 | 9007199254740992L |
| 5613 | >>> 2L**56/10 |
| 5614 | 7205759403792793L |
| 5615 | \end{verbatim} |
| 5616 | |
| 5617 | That is, 56 is the only value for \var{N} that leaves \var{J} with |
| 5618 | exactly 53 bits. The best possible value for \var{J} is then that |
| 5619 | quotient rounded: |
| 5620 | |
| 5621 | \begin{verbatim} |
| 5622 | >>> q, r = divmod(2L**56, 10) |
| 5623 | >>> r |
| 5624 | 6L |
| 5625 | \end{verbatim} |
| 5626 | |
| 5627 | Since the remainder is more than half of 10, the best approximation is |
| 5628 | obtained by rounding up: |
| 5629 | |
| 5630 | \begin{verbatim} |
| 5631 | >>> q+1 |
| 5632 | 7205759403792794L |
| 5633 | \end{verbatim} |
| 5634 | |
| 5635 | Therefore the best possible approximation to 1/10 in 754 double |
| 5636 | precision is that over 2**56, or |
| 5637 | |
| 5638 | \begin{verbatim} |
| 5639 | 7205759403792794 / 72057594037927936 |
| 5640 | \end{verbatim} |
| 5641 | |
| 5642 | Note that since we rounded up, this is actually a little bit larger than |
| 5643 | 1/10; if we had not rounded up, the quotient would have been a little |
Tim Peters | fa9e273 | 2001-06-17 21:57:17 +0000 | [diff] [blame] | 5644 | bit smaller than 1/10. But in no case can it be \emph{exactly} 1/10! |
Fred Drake | 417d667 | 2001-06-08 16:24:58 +0000 | [diff] [blame] | 5645 | |
| 5646 | So the computer never ``sees'' 1/10: what it sees is the exact |
| 5647 | fraction given above, the best 754 double approximation it can get: |
| 5648 | |
| 5649 | \begin{verbatim} |
| 5650 | >>> .1 * 2L**56 |
| 5651 | 7205759403792794.0 |
| 5652 | \end{verbatim} |
| 5653 | |
| 5654 | If we multiply that fraction by 10**30, we can see the (truncated) |
| 5655 | value of its 30 most significant decimal digits: |
| 5656 | |
| 5657 | \begin{verbatim} |
| 5658 | >>> 7205759403792794L * 10L**30 / 2L**56 |
| 5659 | 100000000000000005551115123125L |
| 5660 | \end{verbatim} |
| 5661 | |
| 5662 | meaning that the exact number stored in the computer is approximately |
| 5663 | equal to the decimal value 0.100000000000000005551115123125. Rounding |
| 5664 | that to 17 significant digits gives the 0.10000000000000001 that Python |
| 5665 | displays (well, will display on any 754-conforming platform that does |
| 5666 | best-possible input and output conversions in its C library --- yours may |
| 5667 | not!). |
| 5668 | |
Fred Drake | d5df09c | 2001-06-20 21:37:34 +0000 | [diff] [blame] | 5669 | \chapter{History and License} |
| 5670 | \input{license} |
| 5671 | |
Skip Montanaro | 40d4bc5 | 2003-09-24 16:53:02 +0000 | [diff] [blame] | 5672 | \input{glossary} |
| 5673 | |
| 5674 | \input{tut.ind} |
| 5675 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 5676 | \end{document} |