Fred Drake | 6659c30 | 1998-03-03 22:02:19 +0000 | [diff] [blame] | 1 | \documentclass{manual} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3 | % Things to do: |
| 4 | % Add a section on file I/O |
| 5 | % Write a chapter entitled ``Some Useful Modules'' |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 6 | % --re, math+cmath |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 7 | % Should really move the Python startup file info to an appendix |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 8 | |
Guido van Rossum | dccc298 | 1997-12-30 04:40:25 +0000 | [diff] [blame] | 9 | \title{Python Tutorial} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 10 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 11 | \input{boilerplate} |
Guido van Rossum | 83eb962 | 1993-11-23 16:28:45 +0000 | [diff] [blame] | 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 | ca6567f | 1998-01-22 20:44:18 +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 |
| 54 | \Cpp{}, read \citetitle[../ext/ext.html]{Extending and Embedding the |
| 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, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 107 | sockets, and even interfaces to GUI 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 |
| 124 | statement grouping is done by indentation instead of begin/end |
| 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 | b7833d3 | 1998-09-11 16:21:55 +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 | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 177 | Typing an \EOF{} character (\kbd{Control-D} on \UNIX, |
| 178 | \kbd{Control-Z} on DOS or Windows) at the primary prompt causes the |
| 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 | 3f20592 | 1998-01-13 18:56:38 +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 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 201 | A third 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 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 208 | Note that there is a difference between \samp{python file} and |
| 209 | \samp{python <file}. In the latter case, input requests from the |
| 210 | program, such as calls to \code{input()} and \code{raw_input()}, are |
| 211 | satisfied from \emph{file}. Since this file has already been read |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 212 | until the end by the parser before the program starts executing, the |
| 213 | program will encounter EOF immediately. In the former case (which is |
| 214 | usually what you want) they are satisfied from whatever file or device |
| 215 | is connected to standard input of the Python interpreter. |
| 216 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 217 | When a script file is used, it is sometimes useful to be able to run |
| 218 | the script and enter interactive mode afterwards. This can be done by |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 219 | passing \programopt{-i} before the script. (This does not work if the |
| 220 | script is read from standard input, for the same reason as explained |
| 221 | in the previous paragraph.) |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 222 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 223 | \subsection{Argument Passing \label{argPassing}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 224 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 225 | When known to the interpreter, the script name and additional |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 226 | arguments thereafter are passed to the script in the variable |
| 227 | \code{sys.argv}, which is a list of strings. Its length is at least |
| 228 | one; when no script and no arguments are given, \code{sys.argv[0]} is |
| 229 | an empty string. When the script name is given as \code{'-'} (meaning |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 230 | standard input), \code{sys.argv[0]} is set to \code{'-'}. When |
| 231 | \programopt{-c} \var{command} is used, \code{sys.argv[0]} is set to |
| 232 | \code{'-c'}. Options found after \programopt{-c} \var{command} are |
| 233 | not consumed by the Python interpreter's option processing but left in |
| 234 | \code{sys.argv} for the command to handle. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 235 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 236 | \subsection{Interactive Mode \label{interactive}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 237 | |
Guido van Rossum | dd01080 | 1991-06-07 14:31:11 +0000 | [diff] [blame] | 238 | 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] | 239 | \emph{interactive mode}. In this mode it prompts for the next command |
| 240 | with the \emph{primary prompt}, usually three greater-than signs |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 241 | (\samp{>\code{>}>~}); for continuation lines it prompts with the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 242 | \emph{secondary prompt}, by default three dots (\samp{...~}). |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 243 | The interpreter prints a welcome message stating its version number |
| 244 | and a copyright notice before printing the first prompt, e.g.: |
| 245 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 246 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 247 | python |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 248 | 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] | 249 | Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 250 | >>> |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 251 | \end{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 252 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 253 | Continuation lines are needed when entering a multi-line construct. |
| 254 | As an example, take a look at this \keyword{if} statement: |
| 255 | |
| 256 | \begin{verbatim} |
| 257 | >>> the_world_is_flat = 1 |
| 258 | >>> if the_world_is_flat: |
| 259 | ... print "Be careful not to fall off!" |
| 260 | ... |
| 261 | Be careful not to fall off! |
| 262 | \end{verbatim} |
| 263 | |
| 264 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 265 | \section{The Interpreter and Its Environment \label{interp}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 266 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 267 | \subsection{Error Handling \label{error}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 268 | |
| 269 | When an error occurs, the interpreter prints an error |
| 270 | message and a stack trace. In interactive mode, it then returns to |
| 271 | the primary prompt; when input came from a file, it exits with a |
| 272 | nonzero exit status after printing |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 273 | the stack trace. (Exceptions handled by an \code{except} clause in a |
| 274 | \code{try} statement are not errors in this context.) Some errors are |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 275 | unconditionally fatal and cause an exit with a nonzero exit; this |
| 276 | applies to internal inconsistencies and some cases of running out of |
| 277 | memory. All error messages are written to the standard error stream; |
| 278 | normal output from the executed commands is written to standard |
| 279 | output. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 280 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 281 | Typing the interrupt character (usually Control-C or DEL) to the |
| 282 | primary or secondary prompt cancels the input and returns to the |
Fred Drake | 93aa0f2 | 1999-04-05 21:39:17 +0000 | [diff] [blame] | 283 | primary prompt.\footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 284 | A problem with the GNU Readline package may prevent this. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 285 | } |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 286 | Typing an interrupt while a command is executing raises the |
| 287 | \code{KeyboardInterrupt} exception, which may be handled by a |
| 288 | \code{try} statement. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 289 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 290 | \subsection{Executable Python Scripts \label{scripts}} |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 291 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 292 | On BSD'ish \UNIX{} systems, Python scripts can be made directly |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 293 | executable, like shell scripts, by putting the line |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 294 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 295 | \begin{verbatim} |
Fred Drake | 9e63faa | 1997-10-15 14:37:24 +0000 | [diff] [blame] | 296 | #! /usr/bin/env python |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 297 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 298 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 299 | (assuming that the interpreter is on the user's \envvar{PATH}) at the |
| 300 | beginning of the script and giving the file an executable mode. The |
Fred Drake | bdadf0f | 1999-04-29 13:20:25 +0000 | [diff] [blame] | 301 | \samp{\#!} must be the first two characters of the file. Note that |
| 302 | the hash, or pound, character, \character{\#}, is used to start a |
| 303 | comment in Python. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 304 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 305 | \subsection{The Interactive Startup File \label{startup}} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 306 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 307 | % XXX This should probably be dumped in an appendix, since most people |
| 308 | % don't use Python interactively in non-trivial ways. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 309 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 310 | When you use Python interactively, it is frequently handy to have some |
| 311 | standard commands executed every time the interpreter is started. You |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 312 | can do this by setting an environment variable named |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 313 | \envvar{PYTHONSTARTUP} to the name of a file containing your start-up |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 314 | commands. This is similar to the \file{.profile} feature of the |
| 315 | \UNIX{} shells. |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 316 | |
| 317 | This file is only read in interactive sessions, not when Python reads |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 318 | 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] | 319 | explicit source of commands (which otherwise behaves like an |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 320 | interactive session). It is executed in the same namespace where |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 321 | interactive commands are executed, so that objects that it defines or |
| 322 | imports can be used without qualification in the interactive session. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 323 | 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] | 324 | this file. |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 325 | |
| 326 | If you want to read an additional start-up file from the current |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 327 | directory, you can program this in the global start-up file, |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 328 | e.g.\ \samp{if os.path.isfile('.pythonrc.py'): |
| 329 | execfile('.pythonrc.py')}. If you want to use the startup file in a |
| 330 | script, you must do this explicitly in the script: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 331 | |
| 332 | \begin{verbatim} |
| 333 | import os |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 334 | filename = os.environ.get('PYTHONSTARTUP') |
| 335 | if filename and os.path.isfile(filename): |
| 336 | execfile(filename) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 337 | \end{verbatim} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 338 | |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 339 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 340 | \chapter{An Informal Introduction to Python \label{informal}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 341 | |
| 342 | In the following examples, input and output are distinguished by the |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 343 | presence or absence of prompts (\samp{>\code{>}>~} and \samp{...~}): to repeat |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 344 | the example, you must type everything after the prompt, when the |
| 345 | 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] | 346 | the interpreter. % |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 347 | %\footnote{ |
| 348 | % I'd prefer to use different fonts to distinguish input |
| 349 | % from output, but the amount of LaTeX hacking that would require |
| 350 | % is currently beyond my ability. |
| 351 | %} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 352 | Note that a secondary prompt on a line by itself in an example means |
| 353 | 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] | 354 | |
Fred Drake | bdadf0f | 1999-04-29 13:20:25 +0000 | [diff] [blame] | 355 | Many of the examples in this manual, even those entered at the |
| 356 | interactive prompt, include comments. Comments in Python start with |
| 357 | the hash character, \character{\#}, and extend to the end of the |
| 358 | physical line. A comment may appear at the start of a line or |
| 359 | following whitespace or code, but not within a string literal. A hash |
| 360 | character within a string literal is just a hash character. |
| 361 | |
| 362 | Some examples: |
| 363 | |
| 364 | \begin{verbatim} |
| 365 | # this is the first comment |
| 366 | SPAM = 1 # and this is the second comment |
| 367 | # ... and now a third! |
| 368 | STRING = "# This is not a comment." |
| 369 | \end{verbatim} |
| 370 | |
| 371 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 372 | \section{Using Python as a Calculator \label{calculator}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 373 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 374 | Let's try some simple Python commands. Start the interpreter and wait |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 375 | for the primary prompt, \samp{>\code{>}>~}. (It shouldn't take long.) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 376 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 377 | \subsection{Numbers \label{numbers}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 378 | |
| 379 | The interpreter acts as a simple calculator: you can type an |
| 380 | expression at it and it will write the value. Expression syntax is |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 381 | straightforward: the operators \code{+}, \code{-}, \code{*} and |
| 382 | \code{/} work just like in most other languages (for example, Pascal |
| 383 | or C); parentheses can be used for grouping. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 384 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 385 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 386 | >>> 2+2 |
| 387 | 4 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 388 | >>> # This is a comment |
| 389 | ... 2+2 |
| 390 | 4 |
| 391 | >>> 2+2 # and a comment on the same line as code |
| 392 | 4 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 393 | >>> (50-5*6)/4 |
| 394 | 5 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 395 | >>> # Integer division returns the floor: |
| 396 | ... 7/3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 397 | 2 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 398 | >>> 7/-3 |
| 399 | -3 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 400 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 401 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 402 | 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] | 403 | variable. The value of an assignment is not written: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 404 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 405 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 406 | >>> width = 20 |
| 407 | >>> height = 5*9 |
| 408 | >>> width * height |
| 409 | 900 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 410 | \end{verbatim} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 411 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 412 | A value can be assigned to several variables simultaneously: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 413 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 414 | \begin{verbatim} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 415 | >>> x = y = z = 0 # Zero x, y and z |
| 416 | >>> x |
| 417 | 0 |
| 418 | >>> y |
| 419 | 0 |
| 420 | >>> z |
| 421 | 0 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 422 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 423 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 424 | There is full support for floating point; operators with mixed type |
| 425 | operands convert the integer operand to floating point: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 426 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 427 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 428 | >>> 4 * 2.5 / 3.3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 429 | 3.0303030303 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 430 | >>> 7.0 / 2 |
| 431 | 3.5 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 432 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 433 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 434 | Complex numbers are also supported; imaginary numbers are written with |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 435 | a suffix of \samp{j} or \samp{J}. Complex numbers with a nonzero |
| 436 | real component are written as \samp{(\var{real}+\var{imag}j)}, or can |
| 437 | be created with the \samp{complex(\var{real}, \var{imag})} function. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 438 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 439 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 440 | >>> 1j * 1J |
| 441 | (-1+0j) |
| 442 | >>> 1j * complex(0,1) |
| 443 | (-1+0j) |
| 444 | >>> 3+1j*3 |
| 445 | (3+3j) |
| 446 | >>> (3+1j)*3 |
| 447 | (9+3j) |
| 448 | >>> (1+2j)/(1+1j) |
| 449 | (1.5+0.5j) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 450 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 451 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 452 | Complex numbers are always represented as two floating point numbers, |
| 453 | the real and imaginary part. To extract these parts from a complex |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 454 | 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] | 455 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 456 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 457 | >>> a=1.5+0.5j |
| 458 | >>> a.real |
| 459 | 1.5 |
| 460 | >>> a.imag |
| 461 | 0.5 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 462 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 463 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 464 | The conversion functions to floating point and integer |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 465 | (\function{float()}, \function{int()} and \function{long()}) don't |
| 466 | work for complex numbers --- there is no one correct way to convert a |
| 467 | complex number to a real number. Use \code{abs(\var{z})} to get its |
| 468 | 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] | 469 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 470 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 471 | >>> a=1.5+0.5j |
| 472 | >>> float(a) |
| 473 | Traceback (innermost last): |
| 474 | File "<stdin>", line 1, in ? |
| 475 | TypeError: can't convert complex to float; use e.g. abs(z) |
| 476 | >>> a.real |
| 477 | 1.5 |
| 478 | >>> abs(a) |
| 479 | 1.58113883008 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 480 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 481 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 482 | In interactive mode, the last printed expression is assigned to the |
| 483 | variable \code{_}. This means that when you are using Python as a |
| 484 | desk calculator, it is somewhat easier to continue calculations, for |
| 485 | example: |
| 486 | |
| 487 | \begin{verbatim} |
| 488 | >>> tax = 17.5 / 100 |
| 489 | >>> price = 3.50 |
| 490 | >>> price * tax |
Fred Drake | 343ad7a | 2000-09-22 04:12:27 +0000 | [diff] [blame] | 491 | 0.61249999999999993 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 492 | >>> price + _ |
Fred Drake | 343ad7a | 2000-09-22 04:12:27 +0000 | [diff] [blame] | 493 | 4.1124999999999998 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 494 | >>> round(_, 2) |
Fred Drake | 343ad7a | 2000-09-22 04:12:27 +0000 | [diff] [blame] | 495 | 4.1100000000000003 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 496 | \end{verbatim} |
| 497 | |
| 498 | This variable should be treated as read-only by the user. Don't |
| 499 | explicitly assign a value to it --- you would create an independent |
| 500 | local variable with the same name masking the built-in variable with |
| 501 | its magic behavior. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 502 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 503 | \subsection{Strings \label{strings}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 504 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 505 | Besides numbers, Python can also manipulate strings, which can be |
| 506 | expressed in several ways. They can be enclosed in single quotes or |
| 507 | double quotes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 508 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 509 | \begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 510 | >>> 'spam eggs' |
| 511 | 'spam eggs' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 512 | >>> 'doesn\'t' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 513 | "doesn't" |
| 514 | >>> "doesn't" |
| 515 | "doesn't" |
| 516 | >>> '"Yes," he said.' |
| 517 | '"Yes," he said.' |
| 518 | >>> "\"Yes,\" he said." |
| 519 | '"Yes," he said.' |
| 520 | >>> '"Isn\'t," she said.' |
| 521 | '"Isn\'t," she said.' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 522 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 523 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 524 | String literals can span multiple lines in several ways. Newlines can |
| 525 | be escaped with backslashes, e.g.: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 526 | |
| 527 | \begin{verbatim} |
| 528 | hello = "This is a rather long string containing\n\ |
| 529 | several lines of text just as you would do in C.\n\ |
| 530 | Note that whitespace at the beginning of the line is\ |
| 531 | significant.\n" |
| 532 | print hello |
| 533 | \end{verbatim} |
| 534 | |
| 535 | which would print the following: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 536 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 537 | \begin{verbatim} |
| 538 | This is a rather long string containing |
| 539 | several lines of text just as you would do in C. |
| 540 | Note that whitespace at the beginning of the line is significant. |
| 541 | \end{verbatim} |
| 542 | |
| 543 | Or, strings can be surrounded in a pair of matching triple-quotes: |
| 544 | \code{"""} or \code {'''}. End of lines do not need to be escaped |
| 545 | when using triple-quotes, but they will be included in the string. |
| 546 | |
| 547 | \begin{verbatim} |
| 548 | print """ |
| 549 | Usage: thingy [OPTIONS] |
| 550 | -h Display this usage message |
| 551 | -H hostname Hostname to connect to |
| 552 | """ |
| 553 | \end{verbatim} |
| 554 | |
| 555 | produces the following output: |
| 556 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 557 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 558 | Usage: thingy [OPTIONS] |
| 559 | -h Display this usage message |
| 560 | -H hostname Hostname to connect to |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 561 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 562 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 563 | The interpreter prints the result of string operations in the same way |
| 564 | as they are typed for input: inside quotes, and with quotes and other |
| 565 | funny characters escaped by backslashes, to show the precise |
| 566 | value. The string is enclosed in double quotes if the string contains |
| 567 | 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] | 568 | quotes. (The \keyword{print} statement, described later, can be used |
| 569 | to write strings without quotes or escapes.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 570 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 571 | Strings can be concatenated (glued together) with the |
| 572 | \code{+} operator, and repeated with \code{*}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 573 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 574 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 575 | >>> word = 'Help' + 'A' |
| 576 | >>> word |
| 577 | 'HelpA' |
| 578 | >>> '<' + word*5 + '>' |
| 579 | '<HelpAHelpAHelpAHelpAHelpA>' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 580 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 581 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 582 | Two string literals next to each other are automatically concatenated; |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 583 | 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] | 584 | 'A'}; this only works with two literals, not with arbitrary string |
| 585 | expressions: |
| 586 | |
| 587 | \begin{verbatim} |
Fred Drake | 0ba5815 | 1999-09-14 18:00:49 +0000 | [diff] [blame] | 588 | >>> import string |
Guido van Rossum | e51aa5b | 1999-01-06 23:14:14 +0000 | [diff] [blame] | 589 | >>> 'str' 'ing' # <- This is ok |
| 590 | 'string' |
| 591 | >>> string.strip('str') + 'ing' # <- This is ok |
| 592 | 'string' |
| 593 | >>> string.strip('str') 'ing' # <- This is invalid |
| 594 | File "<stdin>", line 1 |
| 595 | string.strip('str') 'ing' |
| 596 | ^ |
| 597 | SyntaxError: invalid syntax |
| 598 | \end{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 599 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 600 | Strings can be subscripted (indexed); like in C, the first character |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 601 | of a string has subscript (index) 0. There is no separate character |
| 602 | 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] | 603 | substrings can be specified with the \emph{slice notation}: two indices |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 604 | separated by a colon. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 605 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 606 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 607 | >>> word[4] |
| 608 | 'A' |
| 609 | >>> word[0:2] |
| 610 | 'He' |
| 611 | >>> word[2:4] |
| 612 | 'lp' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 613 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 614 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 615 | Unlike a C string, Python strings cannot be changed. Assigning to an |
| 616 | indexed position in the string results in an error: |
| 617 | |
| 618 | \begin{verbatim} |
| 619 | >>> word[0] = 'x' |
| 620 | Traceback (innermost last): |
| 621 | File "<stdin>", line 1, in ? |
| 622 | TypeError: object doesn't support item assignment |
| 623 | >>> word[:-1] = 'Splat' |
| 624 | Traceback (innermost last): |
| 625 | File "<stdin>", line 1, in ? |
| 626 | TypeError: object doesn't support slice assignment |
| 627 | \end{verbatim} |
| 628 | |
| 629 | However, creating a new string with the combined content is easy and |
| 630 | efficient: |
| 631 | |
| 632 | \begin{verbatim} |
| 633 | >>> 'x' + word[1:] |
| 634 | 'xelpA' |
| 635 | >>> 'Splat' + word[-1:] |
| 636 | 'SplatA' |
| 637 | \end{verbatim} |
| 638 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 639 | Slice indices have useful defaults; an omitted first index defaults to |
| 640 | zero, an omitted second index defaults to the size of the string being |
| 641 | sliced. |
| 642 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 643 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 644 | >>> word[:2] # The first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 645 | 'He' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 646 | >>> word[2:] # All but the first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 647 | 'lpA' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 648 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 649 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 650 | Here's a useful invariant of slice operations: |
| 651 | \code{s[:i] + s[i:]} equals \code{s}. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 652 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 653 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 654 | >>> word[:2] + word[2:] |
| 655 | 'HelpA' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 656 | >>> word[:3] + word[3:] |
| 657 | 'HelpA' |
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 | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 660 | Degenerate slice indices are handled gracefully: an index that is too |
| 661 | large is replaced by the string size, an upper bound smaller than the |
| 662 | lower bound returns an empty string. |
| 663 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 664 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 665 | >>> word[1:100] |
| 666 | 'elpA' |
| 667 | >>> word[10:] |
| 668 | '' |
| 669 | >>> word[2:1] |
| 670 | '' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 671 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 672 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 673 | Indices may be negative numbers, to start counting from the right. |
| 674 | For example: |
| 675 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 676 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 677 | >>> word[-1] # The last character |
| 678 | 'A' |
| 679 | >>> word[-2] # The last-but-one character |
| 680 | 'p' |
| 681 | >>> word[-2:] # The last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 682 | 'pA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 683 | >>> word[:-2] # All but the last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 684 | 'Hel' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 685 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 686 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 687 | But note that -0 is really the same as 0, so it does not count from |
| 688 | the right! |
| 689 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 690 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 691 | >>> word[-0] # (since -0 equals 0) |
| 692 | 'H' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 693 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 694 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 695 | Out-of-range negative slice indices are truncated, but don't try this |
| 696 | for single-element (non-slice) indices: |
| 697 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 698 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 699 | >>> word[-100:] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 700 | 'HelpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 701 | >>> word[-10] # error |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 702 | Traceback (innermost last): |
| 703 | File "<stdin>", line 1 |
| 704 | IndexError: string index out of range |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 705 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 706 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 707 | 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] | 708 | pointing \emph{between} characters, with the left edge of the first |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 709 | 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] | 710 | string of \var{n} characters has index \var{n}, for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 711 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 712 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 713 | +---+---+---+---+---+ |
| 714 | | H | e | l | p | A | |
| 715 | +---+---+---+---+---+ |
| 716 | 0 1 2 3 4 5 |
| 717 | -5 -4 -3 -2 -1 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 718 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 719 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 720 | The first row of numbers gives the position of the indices 0...5 in |
| 721 | the string; the second row gives the corresponding negative indices. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 722 | The slice from \var{i} to \var{j} consists of all characters between |
| 723 | the edges labeled \var{i} and \var{j}, respectively. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 724 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 725 | For non-negative indices, the length of a slice is the difference of |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 726 | the indices, if both are within bounds, e.g., the length of |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 727 | \code{word[1:3]} is 2. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 728 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 729 | 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] | 730 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 731 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 732 | >>> s = 'supercalifragilisticexpialidocious' |
| 733 | >>> len(s) |
| 734 | 34 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 735 | \end{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 736 | |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 737 | |
| 738 | \subsection{Unicode Strings \label{unicodeStrings}} |
| 739 | \sectionauthor{Marc-Andre Lemburg}{mal@lemburg.com} |
| 740 | |
Fred Drake | 30f76ff | 2000-06-30 16:06:19 +0000 | [diff] [blame] | 741 | 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] | 742 | available to the programmer: the Unicode object. It can be used to |
| 743 | store and manipulate Unicode data (see \url{http://www.unicode.org}) |
Thomas Wouters | f9b526d | 2000-07-16 19:05:38 +0000 | [diff] [blame] | 744 | and integrates well with the existing string objects providing |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 745 | auto-conversions where necessary. |
| 746 | |
| 747 | Unicode has the advantage of providing one ordinal for every character |
| 748 | in every script used in modern and ancient texts. Previously, there |
| 749 | were only 256 possible ordinals for script characters and texts were |
| 750 | typically bound to a code page which mapped the ordinals to script |
| 751 | characters. This lead to very much confusion especially with respect |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 752 | to internationalization (usually written as \samp{i18n} --- |
| 753 | \character{i} + 18 characters + \character{n}) of software. Unicode |
| 754 | solves these problems by defining one code page for all scripts. |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 755 | |
| 756 | Creating Unicode strings in Python is just as simple as creating |
| 757 | normal strings: |
| 758 | |
| 759 | \begin{verbatim} |
| 760 | >>> u'Hello World !' |
| 761 | u'Hello World !' |
| 762 | \end{verbatim} |
| 763 | |
| 764 | The small \character{u} in front of the quote indicates that an |
| 765 | Unicode string is supposed to be created. If you want to include |
| 766 | special characters in the string, you can do so by using the Python |
| 767 | \emph{Unicode-Escape} encoding. The following example shows how: |
| 768 | |
| 769 | \begin{verbatim} |
| 770 | >>> u'Hello\\u0020World !' |
| 771 | u'Hello World !' |
| 772 | \end{verbatim} |
| 773 | |
| 774 | The escape sequence \code{\\u0020} indicates to insert the Unicode |
| 775 | character with the HEX ordinal 0x0020 (the space character) at the |
| 776 | given position. |
| 777 | |
| 778 | Other characters are interpreted by using their respective ordinal |
| 779 | value directly as Unicode ordinal. Due to the fact that the lower 256 |
| 780 | Unicode are the same as the standard Latin-1 encoding used in many |
| 781 | western countries, the process of entering Unicode is greatly |
| 782 | simplified. |
| 783 | |
| 784 | For experts, there is also a raw mode just like for normal |
| 785 | strings. You have to prepend the string with a small 'r' to have |
| 786 | Python use the \emph{Raw-Unicode-Escape} encoding. It will only apply |
| 787 | the above \code{\\uXXXX} conversion if there is an uneven number of |
| 788 | backslashes in front of the small 'u'. |
| 789 | |
| 790 | \begin{verbatim} |
| 791 | >>> ur'Hello\u0020World !' |
| 792 | u'Hello World !' |
| 793 | >>> ur'Hello\\u0020World !' |
| 794 | u'Hello\\\\u0020World !' |
| 795 | \end{verbatim} |
| 796 | |
| 797 | The raw mode is most useful when you have to enter lots of backslashes |
| 798 | e.g. in regular expressions. |
| 799 | |
| 800 | Apart from these standard encodings, Python provides a whole set of |
Thomas Wouters | f9b526d | 2000-07-16 19:05:38 +0000 | [diff] [blame] | 801 | other ways of creating Unicode strings on the basis of a known |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 802 | encoding. |
| 803 | |
| 804 | The builtin \function{unicode()}\bifuncindex{unicode} provides access |
| 805 | to all registered Unicode codecs (COders and DECoders). Some of the |
| 806 | more well known encodings which these codecs can convert are |
| 807 | \emph{Latin-1}, \emph{ASCII}, \emph{UTF-8} and \emph{UTF-16}. The latter two |
| 808 | are variable length encodings which permit to store Unicode characters |
| 809 | in 8 or 16 bits. Python uses UTF-8 as default encoding. This becomes |
Thomas Wouters | f9b526d | 2000-07-16 19:05:38 +0000 | [diff] [blame] | 810 | noticeable when printing Unicode strings or writing them to files. |
Fred Drake | 9dc30bb | 2000-04-06 14:17:03 +0000 | [diff] [blame] | 811 | |
| 812 | \begin{verbatim} |
| 813 | >>> u"äöü" |
| 814 | u'\344\366\374' |
| 815 | >>> str(u"äöü") |
| 816 | '\303\244\303\266\303\274' |
| 817 | \end{verbatim} |
| 818 | |
| 819 | If you have data in a specific encoding and want to produce a |
| 820 | corresponding Unicode string from it, you can use the |
| 821 | \function{unicode()} builtin with the encoding name as second |
| 822 | argument. |
| 823 | |
| 824 | \begin{verbatim} |
| 825 | >>> unicode('\303\244\303\266\303\274','UTF-8') |
| 826 | u'\344\366\374' |
| 827 | \end{verbatim} |
| 828 | |
| 829 | To convert the Unicode string back into a string using the original |
| 830 | encoding, the objects provide an \method{encode()} method. |
| 831 | |
| 832 | \begin{verbatim} |
| 833 | >>> u"äöü".encode('UTF-8') |
| 834 | '\303\244\303\266\303\274' |
| 835 | \end{verbatim} |
| 836 | |
| 837 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 838 | \subsection{Lists \label{lists}} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 839 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 840 | Python knows a number of \emph{compound} data types, used to group |
| 841 | together other values. The most versatile is the \emph{list}, which |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 842 | can be written as a list of comma-separated values (items) between |
| 843 | square brackets. List items need not all have the same type. |
| 844 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 845 | \begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 846 | >>> a = ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 847 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 848 | ['spam', 'eggs', 100, 1234] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 849 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 850 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 851 | Like string indices, list indices start at 0, and lists can be sliced, |
| 852 | concatenated and so on: |
| 853 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 854 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 855 | >>> a[0] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 856 | 'spam' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 857 | >>> a[3] |
| 858 | 1234 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 859 | >>> a[-2] |
| 860 | 100 |
| 861 | >>> a[1:-1] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 862 | ['eggs', 100] |
| 863 | >>> a[:2] + ['bacon', 2*2] |
| 864 | ['spam', 'eggs', 'bacon', 4] |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 865 | >>> 3*a[:3] + ['Boe!'] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 866 | ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 867 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 868 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 869 | Unlike strings, which are \emph{immutable}, it is possible to change |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 870 | individual elements of a list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 871 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 872 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 873 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 874 | ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 875 | >>> a[2] = a[2] + 23 |
| 876 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 877 | ['spam', 'eggs', 123, 1234] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 878 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 879 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 880 | 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] | 881 | of the list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 882 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 883 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 884 | >>> # Replace some items: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 885 | ... a[0:2] = [1, 12] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 886 | >>> a |
| 887 | [1, 12, 123, 1234] |
| 888 | >>> # Remove some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 889 | ... a[0:2] = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 890 | >>> a |
| 891 | [123, 1234] |
| 892 | >>> # Insert some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 893 | ... a[1:1] = ['bletch', 'xyzzy'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 894 | >>> a |
| 895 | [123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 896 | >>> a[:0] = a # Insert (a copy of) itself at the beginning |
| 897 | >>> a |
| 898 | [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 899 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 900 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 901 | The built-in function \function{len()} also applies to lists: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 902 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 903 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 904 | >>> len(a) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 905 | 8 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 906 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 907 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 908 | It is possible to nest lists (create lists containing other lists), |
| 909 | for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 910 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 911 | \begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 912 | >>> q = [2, 3] |
| 913 | >>> p = [1, q, 4] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 914 | >>> len(p) |
| 915 | 3 |
| 916 | >>> p[1] |
| 917 | [2, 3] |
| 918 | >>> p[1][0] |
| 919 | 2 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 920 | >>> p[1].append('xtra') # See section 5.1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 921 | >>> p |
| 922 | [1, [2, 3, 'xtra'], 4] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 923 | >>> q |
| 924 | [2, 3, 'xtra'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 925 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 926 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 927 | Note that in the last example, \code{p[1]} and \code{q} really refer to |
| 928 | 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] | 929 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 930 | \section{First Steps Towards Programming \label{firstSteps}} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 931 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 932 | Of course, we can use Python for more complicated tasks than adding |
| 933 | two and two together. For instance, we can write an initial |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 934 | subsequence of the \emph{Fibonacci} series as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 935 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 936 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 937 | >>> # Fibonacci series: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 938 | ... # the sum of two elements defines the next |
| 939 | ... a, b = 0, 1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 940 | >>> while b < 10: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 941 | ... print b |
| 942 | ... a, b = b, a+b |
| 943 | ... |
| 944 | 1 |
| 945 | 1 |
| 946 | 2 |
| 947 | 3 |
| 948 | 5 |
| 949 | 8 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 950 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 951 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 952 | This example introduces several new features. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 953 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 954 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 955 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 956 | \item |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 957 | The first line contains a \emph{multiple assignment}: the variables |
| 958 | \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] | 959 | last line this is used again, demonstrating that the expressions on |
| 960 | the right-hand side are all evaluated first before any of the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 961 | assignments take place. The right-hand side expressions are evaluated |
| 962 | from the left to the right. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 963 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 964 | \item |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 965 | The \keyword{while} loop executes as long as the condition (here: |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 966 | \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] | 967 | integer value is true; zero is false. The condition may also be a |
| 968 | string or list value, in fact any sequence; anything with a non-zero |
| 969 | length is true, empty sequences are false. The test used in the |
| 970 | example is a simple comparison. The standard comparison operators are |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 971 | written the same as in C: \code{<} (less than), \code{>} (greater than), |
| 972 | \code{==} (equal to), \code{<=} (less than or equal to), |
| 973 | \code{>=} (greater than or equal to) and \code{!=} (not equal to). |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 974 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 975 | \item |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 976 | 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] | 977 | way of grouping statements. Python does not (yet!) provide an |
| 978 | intelligent input line editing facility, so you have to type a tab or |
| 979 | space(s) for each indented line. In practice you will prepare more |
| 980 | complicated input for Python with a text editor; most text editors have |
| 981 | an auto-indent facility. When a compound statement is entered |
| 982 | interactively, it must be followed by a blank line to indicate |
| 983 | completion (since the parser cannot guess when you have typed the last |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 984 | line). Note that each line within a basic block must be indented by |
| 985 | the same amount. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 986 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 987 | \item |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 988 | 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] | 989 | given. It differs from just writing the expression you want to write |
| 990 | (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] | 991 | multiple expressions and strings. Strings are printed without quotes, |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 992 | and a space is inserted between items, so you can format things nicely, |
| 993 | like this: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 994 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 995 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 996 | >>> i = 256*256 |
| 997 | >>> print 'The value of i is', i |
| 998 | The value of i is 65536 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 999 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1000 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1001 | A trailing comma avoids the newline after the output: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1002 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1003 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1004 | >>> a, b = 0, 1 |
| 1005 | >>> while b < 1000: |
| 1006 | ... print b, |
| 1007 | ... a, b = b, a+b |
| 1008 | ... |
| 1009 | 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] | 1010 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1011 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1012 | Note that the interpreter inserts a newline before it prints the next |
| 1013 | prompt if the last line was not completed. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1014 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1015 | \end{itemize} |
| 1016 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1017 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1018 | \chapter{More Control Flow Tools \label{moreControl}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1019 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1020 | Besides the \keyword{while} statement just introduced, Python knows |
| 1021 | the usual control flow statements known from other languages, with |
| 1022 | some twists. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1023 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1024 | \section{\keyword{if} Statements \label{if}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1025 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1026 | Perhaps the most well-known statement type is the |
| 1027 | \keyword{if} statement. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1028 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1029 | \begin{verbatim} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1030 | >>> x = int(raw_input("Please enter a number: ")) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1031 | >>> if x < 0: |
| 1032 | ... x = 0 |
| 1033 | ... print 'Negative changed to zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1034 | ... elif x == 0: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1035 | ... print 'Zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1036 | ... elif x == 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1037 | ... print 'Single' |
| 1038 | ... else: |
| 1039 | ... print 'More' |
| 1040 | ... |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1041 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1042 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1043 | There can be zero or more \keyword{elif} parts, and the |
| 1044 | \keyword{else} part is optional. The keyword `\keyword{elif}' is |
| 1045 | short for `else if', and is useful to avoid excessive indentation. An |
| 1046 | \keyword{if} \ldots\ \keyword{elif} \ldots\ \keyword{elif} \ldots\ sequence |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1047 | % Weird spacings happen here if the wrapping of the source text |
| 1048 | % gets changed in the wrong way. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1049 | is a substitute for the \emph{switch} or |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1050 | \emph{case} statements found in other languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1051 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1052 | |
| 1053 | \section{\keyword{for} Statements \label{for}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1054 | |
Fred Drake | f790b16 | 1998-11-30 20:37:24 +0000 | [diff] [blame] | 1055 | The \keyword{for}\stindex{for} statement in Python differs a bit from |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1056 | 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] | 1057 | iterating over an arithmetic progression of numbers (like in Pascal), |
| 1058 | 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] | 1059 | halting condition (as C), Python's |
| 1060 | \keyword{for}\stindex{for} statement iterates over the items of any |
| 1061 | sequence (e.g., a list or a string), in the order that they appear in |
| 1062 | the sequence. For example (no pun intended): |
Fred Drake | f790b16 | 1998-11-30 20:37:24 +0000 | [diff] [blame] | 1063 | % One suggestion was to give a real C example here, but that may only |
| 1064 | % serve to confuse non-C programmers. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1065 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1066 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1067 | >>> # Measure some strings: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1068 | ... a = ['cat', 'window', 'defenestrate'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1069 | >>> for x in a: |
| 1070 | ... print x, len(x) |
| 1071 | ... |
| 1072 | cat 3 |
| 1073 | window 6 |
| 1074 | defenestrate 12 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1075 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1076 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1077 | It is not safe to modify the sequence being iterated over in the loop |
| 1078 | (this can only happen for mutable sequence types, i.e., lists). If |
| 1079 | you need to modify the list you are iterating over, e.g., duplicate |
| 1080 | selected items, you must iterate over a copy. The slice notation |
| 1081 | makes this particularly convenient: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1082 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1083 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1084 | >>> for x in a[:]: # make a slice copy of the entire list |
| 1085 | ... if len(x) > 6: a.insert(0, x) |
| 1086 | ... |
| 1087 | >>> a |
| 1088 | ['defenestrate', 'cat', 'window', 'defenestrate'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1089 | \end{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1090 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1091 | |
| 1092 | \section{The \function{range()} Function \label{range}} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1093 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1094 | 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] | 1095 | function \function{range()} comes in handy. It generates lists |
| 1096 | containing arithmetic progressions, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1097 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1098 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1099 | >>> range(10) |
| 1100 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
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 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1103 | The given end point is never part of the generated list; |
| 1104 | \code{range(10)} generates a list of 10 values, exactly the legal |
| 1105 | indices for items of a sequence of length 10. It is possible to let |
| 1106 | the range start at another number, or to specify a different increment |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1107 | (even negative; sometimes this is called the `step'): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1108 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1109 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1110 | >>> range(5, 10) |
| 1111 | [5, 6, 7, 8, 9] |
| 1112 | >>> range(0, 10, 3) |
| 1113 | [0, 3, 6, 9] |
| 1114 | >>> range(-10, -100, -30) |
| 1115 | [-10, -40, -70] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1116 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1117 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1118 | To iterate over the indices of a sequence, combine |
| 1119 | \function{range()} and \function{len()} as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1120 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1121 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1122 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1123 | >>> for i in range(len(a)): |
| 1124 | ... print i, a[i] |
| 1125 | ... |
| 1126 | 0 Mary |
| 1127 | 1 had |
| 1128 | 2 a |
| 1129 | 3 little |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1130 | 4 lamb |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1131 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1132 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1133 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 1134 | \section{\keyword{break} and \keyword{continue} Statements, and |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1135 | \keyword{else} Clauses on Loops |
| 1136 | \label{break}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1137 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1138 | The \keyword{break} statement, like in C, breaks out of the smallest |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1139 | enclosing \keyword{for} or \keyword{while} loop. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1140 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1141 | The \keyword{continue} statement, also borrowed from C, continues |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1142 | with the next iteration of the loop. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1143 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1144 | Loop statements may have an \code{else} clause; it is executed when |
| 1145 | the loop terminates through exhaustion of the list (with |
| 1146 | \keyword{for}) or when the condition becomes false (with |
| 1147 | \keyword{while}), but not when the loop is terminated by a |
| 1148 | \keyword{break} statement. This is exemplified by the following loop, |
| 1149 | which searches for prime numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1150 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1151 | \begin{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1152 | >>> for n in range(2, 10): |
| 1153 | ... for x in range(2, n): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1154 | ... if n % x == 0: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1155 | ... print n, 'equals', x, '*', n/x |
| 1156 | ... break |
| 1157 | ... else: |
| 1158 | ... print n, 'is a prime number' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1159 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1160 | 2 is a prime number |
| 1161 | 3 is a prime number |
| 1162 | 4 equals 2 * 2 |
| 1163 | 5 is a prime number |
| 1164 | 6 equals 2 * 3 |
| 1165 | 7 is a prime number |
| 1166 | 8 equals 2 * 4 |
| 1167 | 9 equals 3 * 3 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1168 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1169 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1170 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1171 | \section{\keyword{pass} Statements \label{pass}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1172 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1173 | The \keyword{pass} statement does nothing. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1174 | It can be used when a statement is required syntactically but the |
| 1175 | program requires no action. |
| 1176 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1177 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1178 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1179 | >>> while 1: |
| 1180 | ... pass # Busy-wait for keyboard interrupt |
| 1181 | ... |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1182 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1183 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1184 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1185 | \section{Defining Functions \label{functions}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1186 | |
| 1187 | We can create a function that writes the Fibonacci series to an |
| 1188 | arbitrary boundary: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1189 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1190 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1191 | >>> def fib(n): # write Fibonacci series up to n |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1192 | ... "Print a Fibonacci series up to n" |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1193 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1194 | ... while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1195 | ... print b, |
| 1196 | ... a, b = b, a+b |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1197 | ... |
| 1198 | >>> # Now call the function we just defined: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1199 | ... fib(2000) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1200 | 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] | 1201 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1202 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1203 | The keyword \keyword{def} introduces a function \emph{definition}. It |
| 1204 | must be followed by the function name and the parenthesized list of |
| 1205 | formal parameters. The statements that form the body of the function |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1206 | start at the next line, and must be indented. The first statement of |
| 1207 | the function body can optionally be a string literal; this string |
| 1208 | literal is the function's \index{documentation strings}documentation |
| 1209 | string, or \dfn{docstring}.\index{docstrings}\index{strings, documentation} |
| 1210 | |
| 1211 | There are tools which use docstrings to automatically produce online |
| 1212 | or printed documentation, or to let the user interactively browse |
| 1213 | through code; it's good practice to include docstrings in code that |
| 1214 | you write, so try to make a habit of it. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1215 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1216 | 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] | 1217 | for the local variables of the function. More precisely, all variable |
| 1218 | 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] | 1219 | whereas variable references first look in the local symbol table, then |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1220 | 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] | 1221 | Thus, global variables cannot be directly assigned a value within a |
| 1222 | function (unless named in a \keyword{global} statement), although |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1223 | they may be referenced. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1224 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1225 | The actual parameters (arguments) to a function call are introduced in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1226 | 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] | 1227 | arguments are passed using \emph{call by value} (where the |
| 1228 | \emph{value} is always an object \emph{reference}, not the value of |
| 1229 | the object).\footnote{ |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1230 | Actually, \emph{call by object reference} would be a better |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1231 | description, since if a mutable object is passed, the caller |
| 1232 | will see any changes the callee makes to it (e.g., items |
| 1233 | inserted into a list). |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1234 | } 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] | 1235 | created for that call. |
| 1236 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1237 | A function definition introduces the function name in the current |
| 1238 | symbol table. The value of the function name |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1239 | has a type that is recognized by the interpreter as a user-defined |
| 1240 | function. This value can be assigned to another name which can then |
| 1241 | also be used as a function. This serves as a general renaming |
| 1242 | mechanism: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1243 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1244 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1245 | >>> fib |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1246 | <function object at 10042ed0> |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1247 | >>> f = fib |
| 1248 | >>> f(100) |
| 1249 | 1 1 2 3 5 8 13 21 34 55 89 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1250 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1251 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1252 | 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] | 1253 | 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] | 1254 | value. In fact, technically speaking, procedures do return a value, |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1255 | albeit a rather boring one. This value is called \code{None} (it's a |
| 1256 | 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] | 1257 | the interpreter if it would be the only value written. You can see it |
| 1258 | if you really want to: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1259 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1260 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1261 | >>> print fib(0) |
| 1262 | None |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1263 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1264 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1265 | It is simple to write a function that returns a list of the numbers of |
| 1266 | the Fibonacci series, instead of printing it: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1267 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1268 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1269 | >>> def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1270 | ... "Return a list containing the Fibonacci series up to n" |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1271 | ... result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1272 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1273 | ... while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1274 | ... result.append(b) # see below |
| 1275 | ... a, b = b, a+b |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1276 | ... return result |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1277 | ... |
| 1278 | >>> f100 = fib2(100) # call it |
| 1279 | >>> f100 # write the result |
| 1280 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1281 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1282 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1283 | This example, as usual, demonstrates some new Python features: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1284 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1285 | \begin{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1286 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1287 | \item |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1288 | The \keyword{return} statement returns with a value from a function. |
| 1289 | \keyword{return} without an expression argument is used to return from |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1290 | the middle of a procedure (falling off the end also returns from a |
| 1291 | procedure), in which case the \code{None} value is returned. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1292 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1293 | \item |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1294 | The statement \code{result.append(b)} calls a \emph{method} of the list |
| 1295 | object \code{result}. A method is a function that `belongs' to an |
| 1296 | object and is named \code{obj.methodname}, where \code{obj} is some |
| 1297 | 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] | 1298 | of a method that is defined by the object's type. Different types |
| 1299 | define different methods. Methods of different types may have the |
| 1300 | same name without causing ambiguity. (It is possible to define your |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1301 | own object types and methods, using \emph{classes}, as discussed later |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1302 | in this tutorial.) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1303 | The method \method{append()} shown in the example, is defined for |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1304 | 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] | 1305 | example it is equivalent to \samp{result = result + [b]}, but more |
| 1306 | efficient. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1307 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1308 | \end{itemize} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1309 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1310 | \section{More on Defining Functions \label{defining}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1311 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1312 | It is also possible to define functions with a variable number of |
| 1313 | arguments. There are three forms, which can be combined. |
| 1314 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1315 | \subsection{Default Argument Values \label{defaultArgs}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1316 | |
| 1317 | The most useful form is to specify a default value for one or more |
| 1318 | arguments. This creates a function that can be called with fewer |
| 1319 | arguments than it is defined, e.g. |
| 1320 | |
| 1321 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1322 | def ask_ok(prompt, retries=4, complaint='Yes or no, please!'): |
| 1323 | while 1: |
| 1324 | ok = raw_input(prompt) |
| 1325 | if ok in ('y', 'ye', 'yes'): return 1 |
| 1326 | if ok in ('n', 'no', 'nop', 'nope'): return 0 |
| 1327 | retries = retries - 1 |
| 1328 | if retries < 0: raise IOError, 'refusenik user' |
| 1329 | print complaint |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1330 | \end{verbatim} |
| 1331 | |
| 1332 | This function can be called either like this: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1333 | \code{ask_ok('Do you really want to quit?')} or like this: |
| 1334 | \code{ask_ok('OK to overwrite the file?', 2)}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1335 | |
| 1336 | The default values are evaluated at the point of function definition |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1337 | in the \emph{defining} scope, so that e.g. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1338 | |
| 1339 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1340 | i = 5 |
| 1341 | def f(arg = i): print arg |
| 1342 | i = 6 |
| 1343 | f() |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1344 | \end{verbatim} |
| 1345 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1346 | will print \code{5}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1347 | |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1348 | \strong{Important warning:} The default value is evaluated only once. |
| 1349 | This makes a difference when the default is a mutable object such as a |
| 1350 | list or dictionary. For example, the following function accumulates |
| 1351 | the arguments passed to it on subsequent calls: |
| 1352 | |
| 1353 | \begin{verbatim} |
| 1354 | def f(a, l = []): |
| 1355 | l.append(a) |
Guido van Rossum | c62cf36 | 1998-10-24 13:15:28 +0000 | [diff] [blame] | 1356 | return l |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1357 | print f(1) |
| 1358 | print f(2) |
| 1359 | print f(3) |
| 1360 | \end{verbatim} |
| 1361 | |
| 1362 | This will print |
| 1363 | |
| 1364 | \begin{verbatim} |
| 1365 | [1] |
| 1366 | [1, 2] |
| 1367 | [1, 2, 3] |
| 1368 | \end{verbatim} |
| 1369 | |
| 1370 | If you don't want the default to be shared between subsequent calls, |
| 1371 | you can write the function like this instead: |
| 1372 | |
| 1373 | \begin{verbatim} |
| 1374 | def f(a, l = None): |
| 1375 | if l is None: |
| 1376 | l = [] |
| 1377 | l.append(a) |
Guido van Rossum | c62cf36 | 1998-10-24 13:15:28 +0000 | [diff] [blame] | 1378 | return l |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1379 | \end{verbatim} |
| 1380 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1381 | \subsection{Keyword Arguments \label{keywordArgs}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1382 | |
| 1383 | Functions can also be called using |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1384 | keyword arguments of the form \samp{\var{keyword} = \var{value}}. For |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1385 | instance, the following function: |
| 1386 | |
| 1387 | \begin{verbatim} |
| 1388 | def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): |
| 1389 | print "-- This parrot wouldn't", action, |
| 1390 | print "if you put", voltage, "Volts through it." |
| 1391 | print "-- Lovely plumage, the", type |
| 1392 | print "-- It's", state, "!" |
| 1393 | \end{verbatim} |
| 1394 | |
| 1395 | could be called in any of the following ways: |
| 1396 | |
| 1397 | \begin{verbatim} |
| 1398 | parrot(1000) |
| 1399 | parrot(action = 'VOOOOOM', voltage = 1000000) |
| 1400 | parrot('a thousand', state = 'pushing up the daisies') |
| 1401 | parrot('a million', 'bereft of life', 'jump') |
| 1402 | \end{verbatim} |
| 1403 | |
| 1404 | but the following calls would all be invalid: |
| 1405 | |
| 1406 | \begin{verbatim} |
| 1407 | parrot() # required argument missing |
| 1408 | parrot(voltage=5.0, 'dead') # non-keyword argument following keyword |
| 1409 | parrot(110, voltage=220) # duplicate value for argument |
| 1410 | parrot(actor='John Cleese') # unknown keyword |
| 1411 | \end{verbatim} |
| 1412 | |
| 1413 | In general, an argument list must have any positional arguments |
| 1414 | followed by any keyword arguments, where the keywords must be chosen |
| 1415 | from the formal parameter names. It's not important whether a formal |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1416 | 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] | 1417 | value more than once --- formal parameter names corresponding to |
| 1418 | positional arguments cannot be used as keywords in the same calls. |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1419 | Here's an example that fails due to this restriction: |
| 1420 | |
| 1421 | \begin{verbatim} |
| 1422 | >>> def function(a): |
| 1423 | ... pass |
| 1424 | ... |
| 1425 | >>> function(0, a=0) |
| 1426 | Traceback (innermost last): |
| 1427 | File "<stdin>", line 1, in ? |
| 1428 | TypeError: keyword parameter redefined |
| 1429 | \end{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1430 | |
| 1431 | When a final formal parameter of the form \code{**\var{name}} is |
| 1432 | present, it receives a dictionary containing all keyword arguments |
| 1433 | whose keyword doesn't correspond to a formal parameter. This may be |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1434 | combined with a formal parameter of the form |
| 1435 | \code{*\var{name}} (described in the next subsection) which receives a |
| 1436 | tuple containing the positional arguments beyond the formal parameter |
| 1437 | list. (\code{*\var{name}} must occur before \code{**\var{name}}.) |
| 1438 | For example, if we define a function like this: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1439 | |
| 1440 | \begin{verbatim} |
| 1441 | def cheeseshop(kind, *arguments, **keywords): |
| 1442 | print "-- Do you have any", kind, '?' |
| 1443 | print "-- I'm sorry, we're all out of", kind |
| 1444 | for arg in arguments: print arg |
| 1445 | print '-'*40 |
| 1446 | for kw in keywords.keys(): print kw, ':', keywords[kw] |
| 1447 | \end{verbatim} |
| 1448 | |
| 1449 | It could be called like this: |
| 1450 | |
| 1451 | \begin{verbatim} |
| 1452 | cheeseshop('Limburger', "It's very runny, sir.", |
| 1453 | "It's really very, VERY runny, sir.", |
| 1454 | client='John Cleese', |
| 1455 | shopkeeper='Michael Palin', |
| 1456 | sketch='Cheese Shop Sketch') |
| 1457 | \end{verbatim} |
| 1458 | |
| 1459 | and of course it would print: |
| 1460 | |
| 1461 | \begin{verbatim} |
| 1462 | -- Do you have any Limburger ? |
| 1463 | -- I'm sorry, we're all out of Limburger |
| 1464 | It's very runny, sir. |
| 1465 | It's really very, VERY runny, sir. |
| 1466 | ---------------------------------------- |
| 1467 | client : John Cleese |
| 1468 | shopkeeper : Michael Palin |
| 1469 | sketch : Cheese Shop Sketch |
| 1470 | \end{verbatim} |
| 1471 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1472 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1473 | \subsection{Arbitrary Argument Lists \label{arbitraryArgs}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1474 | |
| 1475 | Finally, the least frequently used option is to specify that a |
| 1476 | function can be called with an arbitrary number of arguments. These |
| 1477 | arguments will be wrapped up in a tuple. Before the variable number |
| 1478 | of arguments, zero or more normal arguments may occur. |
| 1479 | |
| 1480 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1481 | def fprintf(file, format, *args): |
| 1482 | file.write(format % args) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1483 | \end{verbatim} |
| 1484 | |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1485 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1486 | \subsection{Lambda Forms \label{lambda}} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1487 | |
| 1488 | By popular demand, a few features commonly found in functional |
| 1489 | programming languages and Lisp have been added to Python. With the |
| 1490 | \keyword{lambda} keyword, small anonymous functions can be created. |
| 1491 | Here's a function that returns the sum of its two arguments: |
| 1492 | \samp{lambda a, b: a+b}. Lambda forms can be used wherever function |
| 1493 | objects are required. They are syntactically restricted to a single |
| 1494 | expression. Semantically, they are just syntactic sugar for a normal |
| 1495 | function definition. Like nested function definitions, lambda forms |
| 1496 | cannot reference variables from the containing scope, but this can be |
| 1497 | overcome through the judicious use of default argument values, e.g. |
| 1498 | |
| 1499 | \begin{verbatim} |
| 1500 | def make_incrementor(n): |
| 1501 | return lambda x, incr=n: x+incr |
| 1502 | \end{verbatim} |
| 1503 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1504 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1505 | \subsection{Documentation Strings \label{docstrings}} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1506 | |
| 1507 | There are emerging conventions about the content and formatting of |
| 1508 | documentation strings. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1509 | \index{docstrings}\index{documentation strings} |
| 1510 | \index{strings, documentation} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1511 | |
| 1512 | The first line should always be a short, concise summary of the |
| 1513 | object's purpose. For brevity, it should not explicitly state the |
| 1514 | object's name or type, since these are available by other means |
| 1515 | (except if the name happens to be a verb describing a function's |
| 1516 | operation). This line should begin with a capital letter and end with |
| 1517 | a period. |
| 1518 | |
| 1519 | If there are more lines in the documentation string, the second line |
| 1520 | should be blank, visually separating the summary from the rest of the |
Fred Drake | 4b1a07a | 1999-03-12 18:21:32 +0000 | [diff] [blame] | 1521 | description. The following lines should be one or more paragraphs |
| 1522 | describing the object's calling conventions, its side effects, etc. |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1523 | |
| 1524 | The Python parser does not strip indentation from multi-line string |
| 1525 | literals in Python, so tools that process documentation have to strip |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1526 | indentation if desired. This is done using the following convention. |
| 1527 | The first non-blank line \emph{after} the first line of the string |
| 1528 | determines the amount of indentation for the entire documentation |
| 1529 | string. (We can't use the first line since it is generally adjacent |
| 1530 | to the string's opening quotes so its indentation is not apparent in |
| 1531 | the string literal.) Whitespace ``equivalent'' to this indentation is |
| 1532 | then stripped from the start of all lines of the string. Lines that |
| 1533 | are indented less should not occur, but if they occur all their |
| 1534 | leading whitespace should be stripped. Equivalence of whitespace |
| 1535 | should be tested after expansion of tabs (to 8 spaces, normally). |
| 1536 | |
| 1537 | Here is an example of a multi-line docstring: |
| 1538 | |
| 1539 | \begin{verbatim} |
| 1540 | >>> def my_function(): |
| 1541 | ... """Do nothing, but document it. |
| 1542 | ... |
| 1543 | ... No, really, it doesn't do anything. |
| 1544 | ... """ |
| 1545 | ... pass |
| 1546 | ... |
| 1547 | >>> print my_function.__doc__ |
| 1548 | Do nothing, but document it. |
| 1549 | |
| 1550 | No, really, it doesn't do anything. |
| 1551 | |
| 1552 | \end{verbatim} |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 1553 | |
| 1554 | |
| 1555 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1556 | \chapter{Data Structures \label{structures}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1557 | |
| 1558 | This chapter describes some things you've learned about already in |
| 1559 | more detail, and adds some new things as well. |
| 1560 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1561 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1562 | \section{More on Lists \label{moreLists}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1563 | |
| 1564 | 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] | 1565 | of list objects: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1566 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1567 | \begin{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1568 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1569 | \item[\code{append(x)}] |
| 1570 | Add an item to the end of the list; |
| 1571 | equivalent to \code{a[len(a):] = [x]}. |
| 1572 | |
| 1573 | \item[\code{extend(L)}] |
| 1574 | Extend the list by appending all the items in the given list; |
| 1575 | equivalent to \code{a[len(a):] = L}. |
| 1576 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1577 | \item[\code{insert(i, x)}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1578 | Insert an item at a given position. The first argument is the index of |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1579 | the element before which to insert, so \code{a.insert(0, x)} inserts at |
| 1580 | the front of the list, and \code{a.insert(len(a), x)} is equivalent to |
| 1581 | \code{a.append(x)}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1582 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1583 | \item[\code{remove(x)}] |
| 1584 | Remove the first item from the list whose value is \code{x}. |
| 1585 | It is an error if there is no such item. |
| 1586 | |
| 1587 | \item[\code{pop(\optional{i})}] |
| 1588 | Remove the item at the given position in the list, and return it. If |
| 1589 | no index is specified, \code{a.pop()} returns the last item in the |
| 1590 | list. The item is also removed from the list. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1591 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1592 | \item[\code{index(x)}] |
| 1593 | Return the index in the list of the first item whose value is \code{x}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1594 | It is an error if there is no such item. |
| 1595 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1596 | \item[\code{count(x)}] |
| 1597 | Return the number of times \code{x} appears in the list. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1598 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1599 | \item[\code{sort()}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1600 | Sort the items of the list, in place. |
| 1601 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1602 | \item[\code{reverse()}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1603 | Reverse the elements of the list, in place. |
| 1604 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1605 | \end{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1606 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1607 | An example that uses most of the list methods: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1608 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1609 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1610 | >>> a = [66.6, 333, 333, 1, 1234.5] |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1611 | >>> print a.count(333), a.count(66.6), a.count('x') |
| 1612 | 2 1 0 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1613 | >>> a.insert(2, -1) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1614 | >>> a.append(333) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1615 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1616 | [66.6, 333, -1, 333, 1, 1234.5, 333] |
| 1617 | >>> a.index(333) |
| 1618 | 1 |
| 1619 | >>> a.remove(333) |
| 1620 | >>> a |
| 1621 | [66.6, -1, 333, 1, 1234.5, 333] |
| 1622 | >>> a.reverse() |
| 1623 | >>> a |
| 1624 | [333, 1234.5, 1, 333, -1, 66.6] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1625 | >>> a.sort() |
| 1626 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1627 | [-1, 1, 66.6, 333, 333, 1234.5] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1628 | \end{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1629 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1630 | |
| 1631 | \subsection{Using Lists as Stacks \label{lists-as-stacks}} |
| 1632 | \sectionauthor{Ka-Ping Yee}{ping@lfs.org} |
| 1633 | |
| 1634 | The list methods make it very easy to use a list as a stack, where the |
| 1635 | last element added is the first element retrieved (``last-in, |
| 1636 | first-out''). To add an item to the top of the stack, use |
| 1637 | \method{append()}. To retrieve an item from the top of the stack, use |
| 1638 | \method{pop()} without an explicit index. For example: |
| 1639 | |
| 1640 | \begin{verbatim} |
| 1641 | >>> stack = [3, 4, 5] |
| 1642 | >>> stack.append(6) |
| 1643 | >>> stack.append(7) |
| 1644 | >>> stack |
| 1645 | [3, 4, 5, 6, 7] |
| 1646 | >>> stack.pop() |
| 1647 | 7 |
| 1648 | >>> stack |
| 1649 | [3, 4, 5, 6] |
| 1650 | >>> stack.pop() |
| 1651 | 6 |
| 1652 | >>> stack.pop() |
| 1653 | 5 |
| 1654 | >>> stack |
| 1655 | [3, 4] |
| 1656 | \end{verbatim} |
| 1657 | |
| 1658 | |
| 1659 | \subsection{Using Lists as Queues \label{lists-as-queues}} |
| 1660 | \sectionauthor{Ka-Ping Yee}{ping@lfs.org} |
| 1661 | |
| 1662 | You can also use a list conveniently as a queue, where the first |
| 1663 | element added is the first element retrieved (``first-in, |
| 1664 | first-out''). To add an item to the back of the queue, use |
| 1665 | \method{append()}. To retrieve an item from the front of the queue, |
| 1666 | use \method{pop()} with \code{0} as the index. For example: |
| 1667 | |
| 1668 | \begin{verbatim} |
| 1669 | >>> queue = ["Eric", "John", "Michael"] |
| 1670 | >>> queue.append("Terry") # Terry arrives |
| 1671 | >>> queue.append("Graham") # Graham arrives |
| 1672 | >>> queue.pop(0) |
| 1673 | 'Eric' |
| 1674 | >>> queue.pop(0) |
| 1675 | 'John' |
| 1676 | >>> queue |
| 1677 | ['Michael', 'Terry', 'Graham'] |
| 1678 | \end{verbatim} |
| 1679 | |
| 1680 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1681 | \subsection{Functional Programming Tools \label{functional}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1682 | |
| 1683 | 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] | 1684 | lists: \function{filter()}, \function{map()}, and \function{reduce()}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1685 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1686 | \samp{filter(\var{function}, \var{sequence})} returns a sequence (of |
| 1687 | the same type, if possible) consisting of those items from the |
| 1688 | sequence for which \code{\var{function}(\var{item})} is true. For |
| 1689 | example, to compute some primes: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1690 | |
| 1691 | \begin{verbatim} |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 1692 | >>> def f(x): return x % 2 != 0 and x % 3 != 0 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1693 | ... |
| 1694 | >>> filter(f, range(2, 25)) |
| 1695 | [5, 7, 11, 13, 17, 19, 23] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1696 | \end{verbatim} |
| 1697 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1698 | \samp{map(\var{function}, \var{sequence})} calls |
| 1699 | \code{\var{function}(\var{item})} for each of the sequence's items and |
| 1700 | returns a list of the return values. For example, to compute some |
| 1701 | cubes: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1702 | |
| 1703 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1704 | >>> def cube(x): return x*x*x |
| 1705 | ... |
| 1706 | >>> map(cube, range(1, 11)) |
| 1707 | [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1708 | \end{verbatim} |
| 1709 | |
| 1710 | More than one sequence may be passed; the function must then have as |
| 1711 | many arguments as there are sequences and is called with the |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1712 | corresponding item from each sequence (or \code{None} if some sequence |
| 1713 | is shorter than another). If \code{None} is passed for the function, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1714 | a function returning its argument(s) is substituted. |
| 1715 | |
| 1716 | Combining these two special cases, we see that |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1717 | \samp{map(None, \var{list1}, \var{list2})} is a convenient way of |
| 1718 | turning a pair of lists into a list of pairs. For example: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1719 | |
| 1720 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1721 | >>> seq = range(8) |
| 1722 | >>> def square(x): return x*x |
| 1723 | ... |
| 1724 | >>> map(None, seq, map(square, seq)) |
| 1725 | [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1726 | \end{verbatim} |
| 1727 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1728 | \samp{reduce(\var{func}, \var{sequence})} returns a single value |
| 1729 | constructed by calling the binary function \var{func} on the first two |
| 1730 | items of the sequence, then on the result and the next item, and so |
| 1731 | 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] | 1732 | |
| 1733 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1734 | >>> def add(x,y): return x+y |
| 1735 | ... |
| 1736 | >>> reduce(add, range(1, 11)) |
| 1737 | 55 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1738 | \end{verbatim} |
| 1739 | |
| 1740 | If there's only one item in the sequence, its value is returned; if |
| 1741 | the sequence is empty, an exception is raised. |
| 1742 | |
| 1743 | A third argument can be passed to indicate the starting value. In this |
| 1744 | case the starting value is returned for an empty sequence, and the |
| 1745 | function is first applied to the starting value and the first sequence |
| 1746 | item, then to the result and the next item, and so on. For example, |
| 1747 | |
| 1748 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1749 | >>> def sum(seq): |
| 1750 | ... def add(x,y): return x+y |
| 1751 | ... return reduce(add, seq, 0) |
| 1752 | ... |
| 1753 | >>> sum(range(1, 11)) |
| 1754 | 55 |
| 1755 | >>> sum([]) |
| 1756 | 0 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1757 | \end{verbatim} |
| 1758 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1759 | |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1760 | \subsection{List Comprehensions} |
| 1761 | |
Skip Montanaro | 46dfa5f | 2000-08-22 02:43:07 +0000 | [diff] [blame] | 1762 | List comprehensions provide a concise way to create lists without resorting |
| 1763 | to use of \function{map()}, \function{filter()} and/or \keyword{lambda}. |
| 1764 | The resulting list definition tends often to be clearer than lists built |
| 1765 | using those constructs. Each list comprehension consists of an expression |
| 1766 | following by a \keyword{for} clause, then zero or more \keyword{for} or |
| 1767 | \keyword{if} clauses. The result will be a list resulting from evaluating |
| 1768 | the expression in the context of the \keyword{for} and \keyword{if} clauses |
| 1769 | which follow it. If the expression would evaluate to a tuple, it must be |
| 1770 | parenthesized. |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1771 | |
| 1772 | \begin{verbatim} |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1773 | >>> freshfruit = [' banana', ' loganberry ', 'passion fruit '] |
| 1774 | >>> [weapon.strip() for weapon in freshfruit] |
| 1775 | ['banana', 'loganberry', 'passion fruit'] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1776 | >>> vec = [2, 4, 6] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1777 | >>> [3*x for x in vec] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1778 | [6, 12, 18] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1779 | >>> [3*x for x in vec if x > 3] |
| 1780 | [12, 18] |
| 1781 | >>> [3*x for x in vec if x < 2] |
| 1782 | [] |
Skip Montanaro | 46dfa5f | 2000-08-22 02:43:07 +0000 | [diff] [blame] | 1783 | >>> [{x: x**2} for x in vec] |
| 1784 | [{2: 4}, {4: 16}, {6: 36}] |
| 1785 | >>> [[x,x**2] for x in vec] |
| 1786 | [[2, 4], [4, 16], [6, 36]] |
| 1787 | >>> [x, x**2 for x in vec] # error - parens required for tuples |
| 1788 | File "<stdin>", line 1 |
| 1789 | [x, x**2 for x in vec] |
| 1790 | ^ |
| 1791 | SyntaxError: invalid syntax |
| 1792 | >>> [(x, x**2) for x in vec] |
| 1793 | [(2, 4), (4, 16), (6, 36)] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1794 | >>> vec1 = [2, 4, 6] |
| 1795 | >>> vec2 = [4, 3, -9] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1796 | >>> [x*y for x in vec1 for y in vec2] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1797 | [8, 6, -18, 16, 12, -36, 24, 18, -54] |
Fred Drake | 1aebadf | 2000-08-16 21:44:03 +0000 | [diff] [blame] | 1798 | >>> [x+y for x in vec1 for y in vec2] |
Skip Montanaro | 803d6e5 | 2000-08-12 18:09:51 +0000 | [diff] [blame] | 1799 | [6, 5, -7, 8, 7, -5, 10, 9, -3] |
| 1800 | \end{verbatim} |
| 1801 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1802 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1803 | \section{The \keyword{del} statement \label{del}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1804 | |
| 1805 | 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] | 1806 | 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] | 1807 | remove slices from a list (which we did earlier by assignment of an |
| 1808 | empty list to the slice). For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1809 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1810 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1811 | >>> a |
| 1812 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1813 | >>> del a[0] |
| 1814 | >>> a |
| 1815 | [1, 66.6, 333, 333, 1234.5] |
| 1816 | >>> del a[2:4] |
| 1817 | >>> a |
| 1818 | [1, 66.6, 1234.5] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1819 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1820 | |
| 1821 | \keyword{del} can also be used to delete entire variables: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1822 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1823 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1824 | >>> del a |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1825 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1826 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1827 | Referencing the name \code{a} hereafter is an error (at least until |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1828 | another value is assigned to it). We'll find other uses for |
| 1829 | \keyword{del} later. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1830 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1831 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1832 | \section{Tuples and Sequences \label{tuples}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1833 | |
| 1834 | We saw that lists and strings have many common properties, e.g., |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1835 | indexing and slicing operations. They are two examples of |
| 1836 | \emph{sequence} data types. Since Python is an evolving language, |
| 1837 | other sequence data types may be added. There is also another |
| 1838 | standard sequence data type: the \emph{tuple}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1839 | |
| 1840 | A tuple consists of a number of values separated by commas, for |
| 1841 | instance: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1842 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1843 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1844 | >>> t = 12345, 54321, 'hello!' |
| 1845 | >>> t[0] |
| 1846 | 12345 |
| 1847 | >>> t |
| 1848 | (12345, 54321, 'hello!') |
| 1849 | >>> # Tuples may be nested: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1850 | ... u = t, (1, 2, 3, 4, 5) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1851 | >>> u |
| 1852 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1853 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1854 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1855 | As you see, on output tuples are alway enclosed in parentheses, so |
| 1856 | that nested tuples are interpreted correctly; they may be input with |
| 1857 | or without surrounding parentheses, although often parentheses are |
| 1858 | necessary anyway (if the tuple is part of a larger expression). |
| 1859 | |
| 1860 | Tuples have many uses, e.g., (x, y) coordinate pairs, employee records |
| 1861 | from a database, etc. Tuples, like strings, are immutable: it is not |
| 1862 | possible to assign to the individual items of a tuple (you can |
| 1863 | simulate much of the same effect with slicing and concatenation, |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1864 | though). It is also possible to create tuples which contain mutable |
| 1865 | objects, such as lists. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1866 | |
| 1867 | 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] | 1868 | items: the syntax has some extra quirks to accommodate these. Empty |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1869 | tuples are constructed by an empty pair of parentheses; a tuple with |
| 1870 | one item is constructed by following a value with a comma |
| 1871 | (it is not sufficient to enclose a single value in parentheses). |
| 1872 | Ugly, but effective. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1873 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1874 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1875 | >>> empty = () |
| 1876 | >>> singleton = 'hello', # <-- note trailing comma |
| 1877 | >>> len(empty) |
| 1878 | 0 |
| 1879 | >>> len(singleton) |
| 1880 | 1 |
| 1881 | >>> singleton |
| 1882 | ('hello',) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1883 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1884 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1885 | The statement \code{t = 12345, 54321, 'hello!'} is an example of |
| 1886 | \emph{tuple packing}: the values \code{12345}, \code{54321} and |
| 1887 | \code{'hello!'} are packed together in a tuple. The reverse operation |
| 1888 | is also possible, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1889 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1890 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1891 | >>> x, y, z = t |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1892 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 1893 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1894 | This is called, appropriately enough, \emph{sequence unpacking}. |
| 1895 | Sequence unpacking requires that the list of variables on the left |
| 1896 | have the same number of elements as the length of the sequence. Note |
| 1897 | that multiple assignment is really just a combination of tuple packing |
| 1898 | and sequence unpacking! |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1899 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1900 | There is a small bit of asymmetry here: packing multiple values |
| 1901 | always creates a tuple, and unpacking works for any sequence. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1902 | |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1903 | % XXX Add a bit on the difference between tuples and lists. |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1904 | |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 1905 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1906 | \section{Dictionaries \label{dictionaries}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1907 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1908 | Another useful data type built into Python is the \emph{dictionary}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1909 | Dictionaries are sometimes found in other languages as ``associative |
| 1910 | memories'' or ``associative arrays''. Unlike sequences, which are |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1911 | indexed by a range of numbers, dictionaries are indexed by \emph{keys}, |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1912 | 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] | 1913 | keys. Tuples can be used as keys if they contain only strings, |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 1914 | numbers, or tuples; if a tuple contains any mutable object either |
| 1915 | directly or indirectly, it cannot be used as a key. You can't use |
| 1916 | lists as keys, since lists can be modified in place using their |
| 1917 | \method{append()} and \method{extend()} methods, as well as slice and |
| 1918 | indexed assignments. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 1919 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1920 | 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] | 1921 | \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] | 1922 | (within one dictionary). |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1923 | A pair of braces creates an empty dictionary: \code{\{\}}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1924 | Placing a comma-separated list of key:value pairs within the |
| 1925 | braces adds initial key:value pairs to the dictionary; this is also the |
| 1926 | way dictionaries are written on output. |
| 1927 | |
| 1928 | The main operations on a dictionary are storing a value with some key |
| 1929 | and extracting the value given the key. It is also possible to delete |
| 1930 | a key:value pair |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1931 | with \code{del}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1932 | If you store using a key that is already in use, the old value |
| 1933 | 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] | 1934 | value using a non-existent key. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1935 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 1936 | The \code{keys()} method of a dictionary object returns a list of all |
| 1937 | the keys used in the dictionary, in random order (if you want it |
| 1938 | sorted, just apply the \code{sort()} method to the list of keys). To |
| 1939 | check whether a single key is in the dictionary, use the |
| 1940 | \code{has_key()} method of the dictionary. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1941 | |
| 1942 | Here is a small example using a dictionary: |
| 1943 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1944 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1945 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 1946 | >>> tel['guido'] = 4127 |
| 1947 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1948 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1949 | >>> tel['jack'] |
| 1950 | 4098 |
| 1951 | >>> del tel['sape'] |
| 1952 | >>> tel['irv'] = 4127 |
| 1953 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1954 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1955 | >>> tel.keys() |
| 1956 | ['guido', 'irv', 'jack'] |
| 1957 | >>> tel.has_key('guido') |
| 1958 | 1 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1959 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1960 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 1961 | \section{More on Conditions \label{conditions}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1962 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1963 | The conditions used in \code{while} and \code{if} statements above can |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1964 | contain other operators besides comparisons. |
| 1965 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1966 | The comparison operators \code{in} and \code{not in} check whether a value |
| 1967 | occurs (does not occur) in a sequence. The operators \code{is} and |
| 1968 | \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] | 1969 | only matters for mutable objects like lists. All comparison operators |
| 1970 | have the same priority, which is lower than that of all numerical |
| 1971 | operators. |
| 1972 | |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 1973 | Comparisons can be chained: e.g., \code{a < b == c} tests whether |
| 1974 | \code{a} is less than \code{b} and moreover \code{b} equals \code{c}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1975 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1976 | Comparisons may be combined by the Boolean operators \code{and} and |
| 1977 | \code{or}, and the outcome of a comparison (or of any other Boolean |
| 1978 | expression) may be negated with \code{not}. These all have lower |
| 1979 | priorities than comparison operators again; between them, \code{not} has |
| 1980 | the highest priority, and \code{or} the lowest, so that |
| 1981 | \code{A and not B or C} is equivalent to \code{(A and (not B)) or C}. Of |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1982 | course, parentheses can be used to express the desired composition. |
| 1983 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 1984 | The Boolean operators \code{and} and \code{or} are so-called |
| 1985 | \emph{shortcut} operators: their arguments are evaluated from left to |
| 1986 | right, and evaluation stops as soon as the outcome is determined. |
| 1987 | E.g., if \code{A} and \code{C} are true but \code{B} is false, \code{A |
| 1988 | and B and C} does not evaluate the expression C. In general, the |
| 1989 | return value of a shortcut operator, when used as a general value and |
| 1990 | not as a Boolean, is the last evaluated argument. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1991 | |
| 1992 | 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] | 1993 | expression to a variable. For example, |
| 1994 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 1995 | \begin{verbatim} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1996 | >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' |
| 1997 | >>> non_null = string1 or string2 or string3 |
| 1998 | >>> non_null |
| 1999 | 'Trondheim' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2000 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2001 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2002 | Note that in Python, unlike C, assignment cannot occur inside expressions. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2003 | C programmers may grumble about this, but it avoids a common class of |
| 2004 | problems encountered in C programs: typing \code{=} in an expression when |
| 2005 | \code{==} was intended. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2006 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2007 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2008 | \section{Comparing Sequences and Other Types \label{comparing}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2009 | |
| 2010 | Sequence objects may be compared to other objects with the same |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2011 | sequence type. The comparison uses \emph{lexicographical} ordering: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2012 | first the first two items are compared, and if they differ this |
| 2013 | determines the outcome of the comparison; if they are equal, the next |
| 2014 | two items are compared, and so on, until either sequence is exhausted. |
| 2015 | 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] | 2016 | the lexicographical comparison is carried out recursively. If all |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2017 | items of two sequences compare equal, the sequences are considered |
| 2018 | equal. If one sequence is an initial subsequence of the other, the |
| 2019 | shorted sequence is the smaller one. Lexicographical ordering for |
Guido van Rossum | 47b4c0f | 1995-03-15 11:25:32 +0000 | [diff] [blame] | 2020 | strings uses the \ASCII{} ordering for individual characters. Some |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2021 | examples of comparisons between sequences with the same types: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2022 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2023 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2024 | (1, 2, 3) < (1, 2, 4) |
| 2025 | [1, 2, 3] < [1, 2, 4] |
| 2026 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 2027 | (1, 2, 3, 4) < (1, 2, 4) |
| 2028 | (1, 2) < (1, 2, -1) |
Fred Drake | 511281a | 1999-04-16 13:17:04 +0000 | [diff] [blame] | 2029 | (1, 2, 3) == (1.0, 2.0, 3.0) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2030 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2031 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2032 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2033 | Note that comparing objects of different types is legal. The outcome |
| 2034 | is deterministic but arbitrary: the types are ordered by their name. |
| 2035 | Thus, a list is always smaller than a string, a string is always |
| 2036 | smaller than a tuple, etc. Mixed numeric types are compared according |
Fred Drake | 93aa0f2 | 1999-04-05 21:39:17 +0000 | [diff] [blame] | 2037 | to their numeric value, so 0 equals 0.0, etc.\footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2038 | The rules for comparing objects of different types should |
| 2039 | not be relied upon; they may change in a future version of |
| 2040 | the language. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2041 | } |
| 2042 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2043 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2044 | \chapter{Modules \label{modules}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2045 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2046 | 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] | 2047 | definitions you have made (functions and variables) are lost. |
| 2048 | Therefore, if you want to write a somewhat longer program, you are |
| 2049 | 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] | 2050 | 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] | 2051 | \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] | 2052 | into several files for easier maintenance. You may also want to use a |
| 2053 | handy function that you've written in several programs without copying |
| 2054 | its definition into each program. |
| 2055 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2056 | 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] | 2057 | them in a script or in an interactive instance of the interpreter. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2058 | Such a file is called a \emph{module}; definitions from a module can be |
| 2059 | \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] | 2060 | collection of variables that you have access to in a script |
| 2061 | executed at the top level |
| 2062 | and in calculator mode). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2063 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2064 | A module is a file containing Python definitions and statements. The |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2065 | 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] | 2066 | 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] | 2067 | the global variable \code{__name__}. For instance, use your favorite text |
| 2068 | 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] | 2069 | with the following contents: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2070 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2071 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2072 | # Fibonacci numbers module |
| 2073 | |
| 2074 | def fib(n): # write Fibonacci series up to n |
| 2075 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 2076 | while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2077 | print b, |
| 2078 | a, b = b, a+b |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2079 | |
| 2080 | def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2081 | result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2082 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 2083 | while b < n: |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2084 | result.append(b) |
| 2085 | a, b = b, a+b |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2086 | return result |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2087 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2088 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2089 | Now enter the Python interpreter and import this module with the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2090 | following command: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2091 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2092 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2093 | >>> import fibo |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2094 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2095 | |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 2096 | 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] | 2097 | directly in the current symbol table; it only enters the module name |
Fred Drake | f1ad207 | 1999-06-30 15:32:50 +0000 | [diff] [blame] | 2098 | \code{fibo} there. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2099 | Using the module name you can access the functions: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2100 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2101 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2102 | >>> fibo.fib(1000) |
| 2103 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 2104 | >>> fibo.fib2(100) |
| 2105 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2106 | >>> fibo.__name__ |
| 2107 | 'fibo' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2108 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2109 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2110 | 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] | 2111 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2112 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2113 | >>> fib = fibo.fib |
| 2114 | >>> fib(500) |
| 2115 | 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] | 2116 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2117 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2118 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2119 | \section{More on Modules \label{moreModules}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2120 | |
| 2121 | A module can contain executable statements as well as function |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2122 | definitions. |
| 2123 | These statements are intended to initialize the module. |
| 2124 | They are executed only the |
| 2125 | \emph{first} time the module is imported somewhere.\footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2126 | In fact function definitions are also `statements' that are |
| 2127 | `executed'; the execution enters the function name in the |
| 2128 | module's global symbol table. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2129 | } |
| 2130 | |
| 2131 | Each module has its own private symbol table, which is used as the |
| 2132 | global symbol table by all functions defined in the module. |
| 2133 | Thus, the author of a module can use global variables in the module |
| 2134 | without worrying about accidental clashes with a user's global |
| 2135 | variables. |
| 2136 | On the other hand, if you know what you are doing you can touch a |
| 2137 | module's global variables with the same notation used to refer to its |
| 2138 | functions, |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2139 | \code{modname.itemname}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2140 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2141 | Modules can import other modules. It is customary but not required to |
| 2142 | place all \keyword{import} statements at the beginning of a module (or |
| 2143 | script, for that matter). The imported module names are placed in the |
| 2144 | importing module's global symbol table. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2145 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2146 | There is a variant of the \keyword{import} statement that imports |
| 2147 | names from a module directly into the importing module's symbol |
| 2148 | table. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2149 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2150 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2151 | >>> from fibo import fib, fib2 |
| 2152 | >>> fib(500) |
| 2153 | 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] | 2154 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2155 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2156 | 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] | 2157 | 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] | 2158 | defined). |
| 2159 | |
| 2160 | 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] | 2161 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2162 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2163 | >>> from fibo import * |
| 2164 | >>> fib(500) |
| 2165 | 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] | 2166 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2167 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2168 | This imports all names except those beginning with an underscore |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2169 | (\code{_}). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2170 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2171 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2172 | \subsection{The Module Search Path \label{searchPath}} |
Guido van Rossum | aee5e26 | 1998-08-07 17:45:09 +0000 | [diff] [blame] | 2173 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2174 | \indexiii{module}{search}{path} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2175 | When a module named \module{spam} is imported, the interpreter searches |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2176 | for a file named \file{spam.py} in the current directory, |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2177 | and then in the list of directories specified by |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2178 | the environment variable \envvar{PYTHONPATH}. This has the same syntax as |
| 2179 | the shell variable \envvar{PATH}, i.e., a list of |
| 2180 | 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] | 2181 | is not found there, the search continues in an installation-dependent |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2182 | 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] | 2183 | |
| 2184 | Actually, modules are searched in the list of directories given by the |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2185 | variable \code{sys.path} which is initialized from the directory |
| 2186 | containing the input script (or the current directory), |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2187 | \envvar{PYTHONPATH} and the installation-dependent default. This allows |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2188 | Python programs that know what they're doing to modify or replace the |
| 2189 | module search path. See the section on Standard Modules later. |
| 2190 | |
| 2191 | \subsection{``Compiled'' Python files} |
| 2192 | |
| 2193 | 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] | 2194 | use a lot of standard modules, if a file called \file{spam.pyc} exists |
| 2195 | 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] | 2196 | contain an already-``byte-compiled'' version of the module \module{spam}. |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2197 | 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] | 2198 | \file{spam.pyc} is recorded in \file{spam.pyc}, and the |
| 2199 | \file{.pyc} file is ignored if these don't match. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2200 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2201 | Normally, you don't need to do anything to create the |
| 2202 | \file{spam.pyc} file. Whenever \file{spam.py} is successfully |
| 2203 | compiled, an attempt is made to write the compiled version to |
| 2204 | \file{spam.pyc}. It is not an error if this attempt fails; if for any |
| 2205 | reason the file is not written completely, the resulting |
| 2206 | \file{spam.pyc} file will be recognized as invalid and thus ignored |
| 2207 | later. The contents of the \file{spam.pyc} file are platform |
| 2208 | independent, so a Python module directory can be shared by machines of |
| 2209 | different architectures. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2210 | |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2211 | Some tips for experts: |
| 2212 | |
| 2213 | \begin{itemize} |
| 2214 | |
| 2215 | \item |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2216 | When the Python interpreter is invoked with the \programopt{-O} flag, |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2217 | optimized code is generated and stored in \file{.pyo} files. |
| 2218 | The optimizer currently doesn't help much; it only removes |
| 2219 | \keyword{assert} statements and \code{SET_LINENO} instructions. |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2220 | When \programopt{-O} is used, \emph{all} bytecode is optimized; |
| 2221 | \code{.pyc} files are ignored and \code{.py} files are compiled to |
| 2222 | optimized bytecode. |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2223 | |
| 2224 | \item |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2225 | Passing two \programopt{-O} flags to the Python interpreter |
| 2226 | (\programopt{-OO}) will cause the bytecode compiler to perform |
| 2227 | optimizations that could in some rare cases result in malfunctioning |
| 2228 | programs. Currently only \code{__doc__} strings are removed from the |
| 2229 | bytecode, resulting in more compact \file{.pyo} files. Since some |
| 2230 | programs may rely on having these available, you should only use this |
| 2231 | option if you know what you're doing. |
Guido van Rossum | 6b86a42 | 1999-01-28 15:07:47 +0000 | [diff] [blame] | 2232 | |
| 2233 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2234 | A program doesn't run any faster when it is read from a \file{.pyc} or |
| 2235 | \file{.pyo} file than when it is read from a \file{.py} file; the only |
| 2236 | thing that's faster about \file{.pyc} or \file{.pyo} files is the |
| 2237 | speed with which they are loaded. |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2238 | |
| 2239 | \item |
Guido van Rossum | 002f7aa | 1998-06-28 19:16:38 +0000 | [diff] [blame] | 2240 | When a script is run by giving its name on the command line, the |
| 2241 | bytecode for the script is never written to a \file{.pyc} or |
| 2242 | \file{.pyo} file. Thus, the startup time of a script may be reduced |
| 2243 | 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] | 2244 | script that imports that module. It is also possible to name a |
| 2245 | \file{.pyc} or \file{.pyo} file directly on the command line. |
Guido van Rossum | 002f7aa | 1998-06-28 19:16:38 +0000 | [diff] [blame] | 2246 | |
| 2247 | \item |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2248 | It is possible to have a file called \file{spam.pyc} (or |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2249 | \file{spam.pyo} when \programopt{-O} is used) without a file |
| 2250 | \file{spam.py} for the same module. This can be used to distribute a |
| 2251 | 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] | 2252 | engineer. |
| 2253 | |
| 2254 | \item |
| 2255 | The module \module{compileall}\refstmodindex{compileall} can create |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2256 | \file{.pyc} files (or \file{.pyo} files when \programopt{-O} is used) for |
Guido van Rossum | 13c8ef6 | 1998-05-29 19:12:23 +0000 | [diff] [blame] | 2257 | all modules in a directory. |
| 2258 | |
| 2259 | \end{itemize} |
| 2260 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2261 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2262 | \section{Standard Modules \label{standardModules}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2263 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 2264 | Python comes with a library of standard modules, described in a separate |
Fred Drake | 37f1574 | 1999-11-10 16:21:37 +0000 | [diff] [blame] | 2265 | document, the \citetitle[../lib/lib.html]{Python Library Reference} |
| 2266 | (``Library Reference'' hereafter). Some modules are built into the |
| 2267 | interpreter; these provide access to operations that are not part of |
| 2268 | the core of the language but are nevertheless built in, either for |
| 2269 | efficiency or to provide access to operating system primitives such as |
| 2270 | system calls. The set of such modules is a configuration option; e.g., |
| 2271 | the \module{amoeba} module is only provided on systems that somehow |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2272 | support Amoeba primitives. One particular module deserves some |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2273 | attention: \module{sys}\refstmodindex{sys}, which is built into every |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2274 | Python interpreter. The variables \code{sys.ps1} and |
| 2275 | \code{sys.ps2} define the strings used as primary and secondary |
| 2276 | prompts: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2277 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2278 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2279 | >>> import sys |
| 2280 | >>> sys.ps1 |
| 2281 | '>>> ' |
| 2282 | >>> sys.ps2 |
| 2283 | '... ' |
| 2284 | >>> sys.ps1 = 'C> ' |
| 2285 | C> print 'Yuck!' |
| 2286 | Yuck! |
| 2287 | C> |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2288 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2289 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2290 | These two variables are only defined if the interpreter is in |
| 2291 | interactive mode. |
| 2292 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2293 | The variable \code{sys.path} is a list of strings that determine the |
| 2294 | interpreter's search path for modules. It is initialized to a default |
| 2295 | path taken from the environment variable \envvar{PYTHONPATH}, or from |
| 2296 | a built-in default if \envvar{PYTHONPATH} is not set. You can modify |
| 2297 | it using standard list operations, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2298 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2299 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2300 | >>> import sys |
| 2301 | >>> sys.path.append('/ufs/guido/lib/python') |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2302 | \end{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2303 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2304 | \section{The \function{dir()} Function \label{dir}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2305 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2306 | The built-in function \function{dir()} is used to find out which names |
| 2307 | a module defines. It returns a sorted list of strings: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2308 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2309 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2310 | >>> import fibo, sys |
| 2311 | >>> dir(fibo) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2312 | ['__name__', 'fib', 'fib2'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2313 | >>> dir(sys) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2314 | ['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit', |
| 2315 | 'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace', |
| 2316 | 'stderr', 'stdin', 'stdout', 'version'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2317 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2318 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2319 | Without arguments, \function{dir()} lists the names you have defined |
| 2320 | currently: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2321 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2322 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2323 | >>> a = [1, 2, 3, 4, 5] |
| 2324 | >>> import fibo, sys |
| 2325 | >>> fib = fibo.fib |
| 2326 | >>> dir() |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2327 | ['__name__', 'a', 'fib', 'fibo', 'sys'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2328 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2329 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2330 | 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] | 2331 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2332 | \function{dir()} does not list the names of built-in functions and |
| 2333 | 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] | 2334 | standard module \module{__builtin__}\refbimodindex{__builtin__}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2335 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2336 | \begin{verbatim} |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 2337 | >>> import __builtin__ |
| 2338 | >>> dir(__builtin__) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2339 | ['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError', |
| 2340 | 'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt', |
| 2341 | 'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError', |
| 2342 | 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', |
| 2343 | 'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce', |
| 2344 | 'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float', |
| 2345 | 'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long', |
| 2346 | 'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input', |
| 2347 | 'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2348 | \end{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2349 | |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2350 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2351 | \section{Packages \label{packages}} |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2352 | |
| 2353 | Packages are a way of structuring Python's module namespace |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2354 | by using ``dotted module names''. For example, the module name |
| 2355 | \module{A.B} designates a submodule named \samp{B} in a package named |
| 2356 | \samp{A}. Just like the use of modules saves the authors of different |
| 2357 | modules from having to worry about each other's global variable names, |
| 2358 | the use of dotted module names saves the authors of multi-module |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2359 | packages like NumPy or the Python Imaging Library from having to worry |
| 2360 | about each other's module names. |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2361 | |
| 2362 | Suppose you want to design a collection of modules (a ``package'') for |
| 2363 | the uniform handling of sound files and sound data. There are many |
| 2364 | different sound file formats (usually recognized by their extension, |
| 2365 | e.g. \file{.wav}, \file{.aiff}, \file{.au}), so you may need to create |
| 2366 | and maintain a growing collection of modules for the conversion |
| 2367 | between the various file formats. There are also many different |
| 2368 | operations you might want to perform on sound data (e.g. mixing, |
| 2369 | adding echo, applying an equalizer function, creating an artificial |
| 2370 | stereo effect), so in addition you will be writing a never-ending |
| 2371 | stream of modules to perform these operations. Here's a possible |
| 2372 | structure for your package (expressed in terms of a hierarchical |
| 2373 | filesystem): |
| 2374 | |
| 2375 | \begin{verbatim} |
| 2376 | Sound/ Top-level package |
| 2377 | __init__.py Initialize the sound package |
| 2378 | Formats/ Subpackage for file format conversions |
| 2379 | __init__.py |
| 2380 | wavread.py |
| 2381 | wavwrite.py |
| 2382 | aiffread.py |
| 2383 | aiffwrite.py |
| 2384 | auread.py |
| 2385 | auwrite.py |
| 2386 | ... |
| 2387 | Effects/ Subpackage for sound effects |
| 2388 | __init__.py |
| 2389 | echo.py |
| 2390 | surround.py |
| 2391 | reverse.py |
| 2392 | ... |
| 2393 | Filters/ Subpackage for filters |
| 2394 | __init__.py |
| 2395 | equalizer.py |
| 2396 | vocoder.py |
| 2397 | karaoke.py |
| 2398 | ... |
| 2399 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2400 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2401 | The \file{__init__.py} files are required to make Python treat the |
| 2402 | directories as containing packages; this is done to prevent |
| 2403 | directories with a common name, such as \samp{string}, from |
| 2404 | unintentionally hiding valid modules that occur later on the module |
| 2405 | search path. In the simplest case, \file{__init__.py} can just be an |
| 2406 | empty file, but it can also execute initialization code for the |
| 2407 | package or set the \code{__all__} variable, described later. |
| 2408 | |
| 2409 | Users of the package can import individual modules from the |
| 2410 | package, for example: |
| 2411 | |
| 2412 | \begin{verbatim} |
| 2413 | import Sound.Effects.echo |
| 2414 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2415 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2416 | This loads the submodule \module{Sound.Effects.echo}. It must be referenced |
| 2417 | with its full name, e.g. |
| 2418 | |
| 2419 | \begin{verbatim} |
| 2420 | Sound.Effects.echo.echofilter(input, output, delay=0.7, atten=4) |
| 2421 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2422 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2423 | An alternative way of importing the submodule is: |
| 2424 | |
| 2425 | \begin{verbatim} |
| 2426 | from Sound.Effects import echo |
| 2427 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2428 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2429 | This also loads the submodule \module{echo}, and makes it available without |
| 2430 | its package prefix, so it can be used as follows: |
| 2431 | |
| 2432 | \begin{verbatim} |
| 2433 | echo.echofilter(input, output, delay=0.7, atten=4) |
| 2434 | \end{verbatim} |
| 2435 | |
| 2436 | Yet another variation is to import the desired function or variable directly: |
| 2437 | |
| 2438 | \begin{verbatim} |
| 2439 | from Sound.Effects.echo import echofilter |
| 2440 | \end{verbatim} |
| 2441 | |
| 2442 | Again, this loads the submodule \module{echo}, but this makes its function |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2443 | \function{echofilter()} directly available: |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2444 | |
| 2445 | \begin{verbatim} |
| 2446 | echofilter(input, output, delay=0.7, atten=4) |
| 2447 | \end{verbatim} |
| 2448 | |
| 2449 | Note that when using \code{from \var{package} import \var{item}}, the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2450 | 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] | 2451 | other name defined in the package, like a function, class or |
| 2452 | variable. The \code{import} statement first tests whether the item is |
| 2453 | 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] | 2454 | to load it. If it fails to find it, an |
| 2455 | \exception{ImportError} exception is raised. |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2456 | |
| 2457 | Contrarily, when using syntax like \code{import |
| 2458 | \var{item.subitem.subsubitem}}, each item except for the last must be |
| 2459 | a package; the last item can be a module or a package but can't be a |
| 2460 | class or function or variable defined in the previous item. |
| 2461 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2462 | \subsection{Importing * From a Package \label{pkg-import-star}} |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2463 | %The \code{__all__} Attribute |
| 2464 | |
| 2465 | Now what happens when the user writes \code{from Sound.Effects import |
| 2466 | *}? Ideally, one would hope that this somehow goes out to the |
| 2467 | filesystem, finds which submodules are present in the package, and |
| 2468 | imports them all. Unfortunately, this operation does not work very |
| 2469 | well on Mac and Windows platforms, where the filesystem does not |
| 2470 | always have accurate information about the case of a filename! On |
| 2471 | these platforms, there is no guaranteed way to know whether a file |
| 2472 | \file{ECHO.PY} should be imported as a module \module{echo}, |
| 2473 | \module{Echo} or \module{ECHO}. (For example, Windows 95 has the |
| 2474 | annoying practice of showing all file names with a capitalized first |
| 2475 | letter.) The DOS 8+3 filename restriction adds another interesting |
| 2476 | problem for long module names. |
| 2477 | |
| 2478 | The only solution is for the package author to provide an explicit |
| 2479 | index of the package. The import statement uses the following |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2480 | convention: if a package's \file{__init__.py} code defines a list |
| 2481 | named \code{__all__}, it is taken to be the list of module names that |
| 2482 | should be imported when \code{from \var{package} import *} is |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2483 | encountered. It is up to the package author to keep this list |
| 2484 | up-to-date when a new version of the package is released. Package |
| 2485 | authors may also decide not to support it, if they don't see a use for |
| 2486 | importing * from their package. For example, the file |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2487 | \file{Sounds/Effects/__init__.py} could contain the following code: |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2488 | |
| 2489 | \begin{verbatim} |
| 2490 | __all__ = ["echo", "surround", "reverse"] |
| 2491 | \end{verbatim} |
| 2492 | |
| 2493 | This would mean that \code{from Sound.Effects import *} would |
| 2494 | import the three named submodules of the \module{Sound} package. |
| 2495 | |
| 2496 | If \code{__all__} is not defined, the statement \code{from Sound.Effects |
| 2497 | import *} does \emph{not} import all submodules from the package |
| 2498 | \module{Sound.Effects} into the current namespace; it only ensures that the |
| 2499 | package \module{Sound.Effects} has been imported (possibly running its |
| 2500 | initialization code, \file{__init__.py}) and then imports whatever names are |
| 2501 | defined in the package. This includes any names defined (and |
| 2502 | submodules explicitly loaded) by \file{__init__.py}. It also includes any |
| 2503 | submodules of the package that were explicitly loaded by previous |
| 2504 | import statements, e.g. |
| 2505 | |
| 2506 | \begin{verbatim} |
| 2507 | import Sound.Effects.echo |
| 2508 | import Sound.Effects.surround |
| 2509 | from Sound.Effects import * |
| 2510 | \end{verbatim} |
| 2511 | |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2512 | In this example, the echo and surround modules are imported in the |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2513 | current namespace because they are defined in the |
| 2514 | \module{Sound.Effects} package when the \code{from...import} statement |
| 2515 | is executed. (This also works when \code{__all__} is defined.) |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2516 | |
| 2517 | Note that in general the practicing of importing * from a module or |
| 2518 | package is frowned upon, since it often causes poorly readable code. |
| 2519 | However, it is okay to use it to save typing in interactive sessions, |
| 2520 | and certain modules are designed to export only names that follow |
| 2521 | certain patterns. |
| 2522 | |
| 2523 | Remember, there is nothing wrong with using \code{from Package |
| 2524 | import specific_submodule}! In fact, this is the |
| 2525 | recommended notation unless the importing module needs to use |
| 2526 | submodules with the same name from different packages. |
| 2527 | |
| 2528 | |
| 2529 | \subsection{Intra-package References} |
| 2530 | |
| 2531 | The submodules often need to refer to each other. For example, the |
| 2532 | \module{surround} module might use the \module{echo} module. In fact, such references |
| 2533 | are so common that the \code{import} statement first looks in the |
| 2534 | containing package before looking in the standard module search path. |
| 2535 | Thus, the surround module can simply use \code{import echo} or |
| 2536 | \code{from echo import echofilter}. If the imported module is not |
| 2537 | found in the current package (the package of which the current module |
| 2538 | is a submodule), the \code{import} statement looks for a top-level module |
| 2539 | with the given name. |
| 2540 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2541 | When packages are structured into subpackages (as with the |
| 2542 | \module{Sound} package in the example), there's no shortcut to refer |
| 2543 | to submodules of sibling packages - the full name of the subpackage |
| 2544 | must be used. For example, if the module |
| 2545 | \module{Sound.Filters.vocoder} needs to use the \module{echo} module |
| 2546 | in the \module{Sound.Effects} package, it can use \code{from |
Andrew M. Kuchling | 108943c | 1998-07-01 13:58:55 +0000 | [diff] [blame] | 2547 | Sound.Effects import echo}. |
| 2548 | |
| 2549 | %(One could design a notation to refer to parent packages, similar to |
| 2550 | %the use of ".." to refer to the parent directory in Unix and Windows |
| 2551 | %filesystems. In fact, the \module{ni} module, which was the |
| 2552 | %ancestor of this package system, supported this using \code{__} for |
| 2553 | %the package containing the current module, |
| 2554 | %\code{__.__} for the parent package, and so on. This feature was dropped |
| 2555 | %because of its awkwardness; since most packages will have a relative |
| 2556 | %shallow substructure, this is no big loss.) |
| 2557 | |
| 2558 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2559 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2560 | \chapter{Input and Output \label{io}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2561 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2562 | There are several ways to present the output of a program; data can be |
| 2563 | printed in a human-readable form, or written to a file for future use. |
| 2564 | This chapter will discuss some of the possibilities. |
| 2565 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2566 | |
| 2567 | \section{Fancier Output Formatting \label{formatting}} |
| 2568 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2569 | So far we've encountered two ways of writing values: \emph{expression |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2570 | statements} and the \keyword{print} statement. (A third way is using |
| 2571 | the \method{write()} method of file objects; the standard output file |
| 2572 | can be referenced as \code{sys.stdout}. See the Library Reference for |
| 2573 | more information on this.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2574 | |
| 2575 | 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] | 2576 | simply printing space-separated values. There are two ways to format |
| 2577 | your output; the first way is to do all the string handling yourself; |
| 2578 | using string slicing and concatenation operations you can create any |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2579 | lay-out you can imagine. The standard module |
| 2580 | \module{string}\refstmodindex{string} contains some useful operations |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2581 | for padding strings to a given column width; these will be discussed |
| 2582 | shortly. The second way is to use the \code{\%} operator with a |
| 2583 | string as the left argument. The \code{\%} operator interprets the |
| 2584 | left argument as a C much like a \cfunction{sprintf()}-style format |
| 2585 | string to be applied to the right argument, and returns the string |
| 2586 | resulting from this formatting operation. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2587 | |
| 2588 | One question remains, of course: how do you convert values to strings? |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2589 | Luckily, Python has a way to convert any value to a string: pass it to |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2590 | the \function{repr()} function, or just write the value between |
| 2591 | reverse quotes (\code{``}). Some examples: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2592 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2593 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2594 | >>> x = 10 * 3.14 |
| 2595 | >>> y = 200*200 |
| 2596 | >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' |
| 2597 | >>> print s |
| 2598 | The value of x is 31.4, and y is 40000... |
| 2599 | >>> # Reverse quotes work on other types besides numbers: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2600 | ... p = [x, y] |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2601 | >>> ps = repr(p) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2602 | >>> ps |
| 2603 | '[31.4, 40000]' |
| 2604 | >>> # Converting a string adds string quotes and backslashes: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2605 | ... hello = 'hello, world\n' |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2606 | >>> hellos = `hello` |
| 2607 | >>> print hellos |
| 2608 | 'hello, world\012' |
| 2609 | >>> # The argument of reverse quotes may be a tuple: |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2610 | ... `x, y, ('spam', 'eggs')` |
| 2611 | "(31.4, 40000, ('spam', 'eggs'))" |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2612 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2613 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2614 | 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] | 2615 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2616 | \begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2617 | >>> import string |
| 2618 | >>> for x in range(1, 11): |
| 2619 | ... print string.rjust(`x`, 2), string.rjust(`x*x`, 3), |
| 2620 | ... # Note trailing comma on previous line |
| 2621 | ... print string.rjust(`x*x*x`, 4) |
| 2622 | ... |
| 2623 | 1 1 1 |
| 2624 | 2 4 8 |
| 2625 | 3 9 27 |
| 2626 | 4 16 64 |
| 2627 | 5 25 125 |
| 2628 | 6 36 216 |
| 2629 | 7 49 343 |
| 2630 | 8 64 512 |
| 2631 | 9 81 729 |
| 2632 | 10 100 1000 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2633 | >>> for x in range(1,11): |
| 2634 | ... print '%2d %3d %4d' % (x, x*x, x*x*x) |
| 2635 | ... |
| 2636 | 1 1 1 |
| 2637 | 2 4 8 |
| 2638 | 3 9 27 |
| 2639 | 4 16 64 |
| 2640 | 5 25 125 |
| 2641 | 6 36 216 |
| 2642 | 7 49 343 |
| 2643 | 8 64 512 |
| 2644 | 9 81 729 |
| 2645 | 10 100 1000 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2646 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2647 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2648 | (Note that one space between each column was added by the way |
| 2649 | \keyword{print} works: it always adds spaces between its arguments.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2650 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2651 | This example demonstrates the function \function{string.rjust()}, |
| 2652 | which right-justifies a string in a field of a given width by padding |
| 2653 | it with spaces on the left. There are similar functions |
| 2654 | \function{string.ljust()} and \function{string.center()}. These |
| 2655 | functions do not write anything, they just return a new string. If |
| 2656 | the input string is too long, they don't truncate it, but return it |
| 2657 | unchanged; this will mess up your column lay-out but that's usually |
| 2658 | better than the alternative, which would be lying about a value. (If |
| 2659 | you really want truncation you can always add a slice operation, as in |
| 2660 | \samp{string.ljust(x,~n)[0:n]}.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2661 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2662 | There is another function, \function{string.zfill()}, which pads a |
| 2663 | numeric string on the left with zeros. It understands about plus and |
| 2664 | minus signs: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2665 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2666 | \begin{verbatim} |
Fred Drake | 0ba5815 | 1999-09-14 18:00:49 +0000 | [diff] [blame] | 2667 | >>> import string |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2668 | >>> string.zfill('12', 5) |
| 2669 | '00012' |
| 2670 | >>> string.zfill('-3.14', 7) |
| 2671 | '-003.14' |
| 2672 | >>> string.zfill('3.14159265359', 5) |
| 2673 | '3.14159265359' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2674 | \end{verbatim} |
Fred Drake | 31b761e | 2000-09-29 15:17:36 +0000 | [diff] [blame] | 2675 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2676 | Using the \code{\%} operator looks like this: |
| 2677 | |
| 2678 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2679 | >>> import math |
| 2680 | >>> print 'The value of PI is approximately %5.3f.' % math.pi |
| 2681 | The value of PI is approximately 3.142. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2682 | \end{verbatim} |
| 2683 | |
| 2684 | If there is more than one format in the string you pass a tuple as |
| 2685 | right operand, e.g. |
| 2686 | |
| 2687 | \begin{verbatim} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2688 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 7678} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2689 | >>> for name, phone in table.items(): |
| 2690 | ... print '%-10s ==> %10d' % (name, phone) |
| 2691 | ... |
| 2692 | Jack ==> 4098 |
Fred Drake | 69fbf33 | 2000-04-04 19:53:06 +0000 | [diff] [blame] | 2693 | Dcab ==> 7678 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2694 | Sjoerd ==> 4127 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2695 | \end{verbatim} |
| 2696 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2697 | 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] | 2698 | 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] | 2699 | The \code{\%s} format is more relaxed: if the corresponding argument is |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2700 | not a string object, it is converted to string using the |
| 2701 | \function{str()} built-in function. Using \code{*} to pass the width |
| 2702 | or precision in as a separate (integer) argument is supported. The |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2703 | C formats \code{\%n} and \code{\%p} are not supported. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2704 | |
| 2705 | If you have a really long format string that you don't want to split |
| 2706 | up, it would be nice if you could reference the variables to be |
| 2707 | formatted by name instead of by position. This can be done by using |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2708 | an extension of C formats using the form \code{\%(name)format}, e.g. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2709 | |
| 2710 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2711 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
| 2712 | >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table |
| 2713 | Jack: 4098; Sjoerd: 4127; Dcab: 8637678 |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2714 | \end{verbatim} |
| 2715 | |
| 2716 | This is particularly useful in combination with the new built-in |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2717 | \function{vars()} function, which returns a dictionary containing all |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2718 | local variables. |
| 2719 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2720 | \section{Reading and Writing Files \label{files}} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2721 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2722 | % Opening files |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2723 | \function{open()}\bifuncindex{open} returns a file |
| 2724 | object\obindex{file}, and is most commonly used with two arguments: |
| 2725 | \samp{open(\var{filename}, \var{mode})}. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2726 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2727 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2728 | >>> f=open('/tmp/workfile', 'w') |
| 2729 | >>> print f |
| 2730 | <open file '/tmp/workfile', mode 'w' at 80a0960> |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2731 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2732 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2733 | The first argument is a string containing the filename. The second |
| 2734 | argument is another string containing a few characters describing the |
| 2735 | way in which the file will be used. \var{mode} can be \code{'r'} when |
| 2736 | the file will only be read, \code{'w'} for only writing (an existing |
| 2737 | file with the same name will be erased), and \code{'a'} opens the file |
| 2738 | for appending; any data written to the file is automatically added to |
| 2739 | the end. \code{'r+'} opens the file for both reading and writing. |
| 2740 | The \var{mode} argument is optional; \code{'r'} will be assumed if |
| 2741 | it's omitted. |
| 2742 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2743 | On Windows and the Macintosh, \code{'b'} appended to the |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2744 | mode opens the file in binary mode, so there are also modes like |
| 2745 | \code{'rb'}, \code{'wb'}, and \code{'r+b'}. Windows makes a |
| 2746 | distinction between text and binary files; the end-of-line characters |
| 2747 | in text files are automatically altered slightly when data is read or |
| 2748 | written. This behind-the-scenes modification to file data is fine for |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2749 | \ASCII{} text files, but it'll corrupt binary data like that in JPEGs or |
| 2750 | \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] | 2751 | writing such files. (Note that the precise semantics of text mode on |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 2752 | the Macintosh depends on the underlying C library being used.) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2753 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2754 | \subsection{Methods of File Objects \label{fileMethods}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2755 | |
| 2756 | The rest of the examples in this section will assume that a file |
| 2757 | object called \code{f} has already been created. |
| 2758 | |
| 2759 | To read a file's contents, call \code{f.read(\var{size})}, which reads |
| 2760 | some quantity of data and returns it as a string. \var{size} is an |
| 2761 | optional numeric argument. When \var{size} is omitted or negative, |
| 2762 | the entire contents of the file will be read and returned; it's your |
| 2763 | problem if the file is twice as large as your machine's memory. |
| 2764 | Otherwise, at most \var{size} bytes are read and returned. If the end |
| 2765 | of the file has been reached, \code{f.read()} will return an empty |
| 2766 | string (\code {""}). |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2767 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2768 | >>> f.read() |
| 2769 | 'This is the entire file.\012' |
| 2770 | >>> f.read() |
| 2771 | '' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2772 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2773 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2774 | \code{f.readline()} reads a single line from the file; a newline |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2775 | 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] | 2776 | omitted on the last line of the file if the file doesn't end in a |
| 2777 | newline. This makes the return value unambiguous; if |
| 2778 | \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] | 2779 | 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] | 2780 | string containing only a single newline. |
| 2781 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2782 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2783 | >>> f.readline() |
| 2784 | 'This is the first line of the file.\012' |
| 2785 | >>> f.readline() |
| 2786 | 'Second line of the file\012' |
| 2787 | >>> f.readline() |
| 2788 | '' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2789 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2790 | |
Fred Drake | 343ad7a | 2000-09-22 04:12:27 +0000 | [diff] [blame] | 2791 | \code{f.readlines()} returns a list containing all the lines of data |
| 2792 | in the file. If given an optional parameter \var{sizehint}, it reads |
| 2793 | that many bytes from the file and enough more to complete a line, and |
| 2794 | returns the lines from that. This is often used to allow efficient |
| 2795 | reading of a large file by lines, but without having to load the |
| 2796 | entire file in memory. Only complete lines will be returned. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2797 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2798 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2799 | >>> f.readlines() |
| 2800 | ['This is the first line of the file.\012', 'Second line of the file\012'] |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2801 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2802 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2803 | \code{f.write(\var{string})} writes the contents of \var{string} to |
| 2804 | the file, returning \code{None}. |
| 2805 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2806 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2807 | >>> f.write('This is a test\n') |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2808 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2809 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2810 | \code{f.tell()} returns an integer giving the file object's current |
| 2811 | position in the file, measured in bytes from the beginning of the |
| 2812 | file. To change the file object's position, use |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2813 | \samp{f.seek(\var{offset}, \var{from_what})}. The position is |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2814 | computed from adding \var{offset} to a reference point; the reference |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2815 | point is selected by the \var{from_what} argument. A |
| 2816 | \var{from_what} value of 0 measures from the beginning of the file, 1 |
| 2817 | uses the current file position, and 2 uses the end of the file as the |
| 2818 | reference point. \var{from_what} can be omitted and defaults to 0, |
| 2819 | using the beginning of the file as the reference point. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2820 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2821 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2822 | >>> f=open('/tmp/workfile', 'r+') |
| 2823 | >>> f.write('0123456789abcdef') |
| 2824 | >>> f.seek(5) # Go to the 5th byte in the file |
| 2825 | >>> f.read(1) |
| 2826 | '5' |
| 2827 | >>> f.seek(-3, 2) # Go to the 3rd byte before the end |
| 2828 | >>> f.read(1) |
| 2829 | 'd' |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2830 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2831 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2832 | When you're done with a file, call \code{f.close()} to close it and |
| 2833 | free up any system resources taken up by the open file. After calling |
| 2834 | \code{f.close()}, attempts to use the file object will automatically fail. |
| 2835 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2836 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2837 | >>> f.close() |
| 2838 | >>> f.read() |
| 2839 | Traceback (innermost last): |
| 2840 | File "<stdin>", line 1, in ? |
| 2841 | ValueError: I/O operation on closed file |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2842 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2843 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2844 | File objects have some additional methods, such as |
| 2845 | \method{isatty()} and \method{truncate()} which are less frequently |
| 2846 | used; consult the Library Reference for a complete guide to file |
| 2847 | objects. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2848 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2849 | \subsection{The \module{pickle} Module \label{pickle}} |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 2850 | \refstmodindex{pickle} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2851 | |
| 2852 | 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] | 2853 | bit more effort, since the \method{read()} method only returns |
| 2854 | strings, which will have to be passed to a function like |
| 2855 | \function{string.atoi()}, which takes a string like \code{'123'} and |
| 2856 | returns its numeric value 123. However, when you want to save more |
| 2857 | complex data types like lists, dictionaries, or class instances, |
| 2858 | things get a lot more complicated. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2859 | |
| 2860 | Rather than have users be constantly writing and debugging code to |
| 2861 | save complicated data types, Python provides a standard module called |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2862 | \module{pickle}. This is an amazing module that can take almost |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2863 | any Python object (even some forms of Python code!), and convert it to |
| 2864 | a string representation; this process is called \dfn{pickling}. |
| 2865 | Reconstructing the object from the string representation is called |
| 2866 | \dfn{unpickling}. Between pickling and unpickling, the string |
| 2867 | representing the object may have been stored in a file or data, or |
| 2868 | sent over a network connection to some distant machine. |
| 2869 | |
| 2870 | If you have an object \code{x}, and a file object \code{f} that's been |
| 2871 | opened for writing, the simplest way to pickle the object takes only |
| 2872 | one line of code: |
| 2873 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2874 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2875 | pickle.dump(x, f) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2876 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2877 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2878 | To unpickle the object again, if \code{f} is a file object which has |
| 2879 | been opened for reading: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2880 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2881 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2882 | x = pickle.load(f) |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2883 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2884 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2885 | (There are other variants of this, used when pickling many objects or |
| 2886 | when you don't want to write the pickled data to a file; consult the |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2887 | complete documentation for \module{pickle} in the Library Reference.) |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2888 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2889 | \module{pickle} is the standard way to make Python objects which can |
| 2890 | be stored and reused by other programs or by a future invocation of |
| 2891 | the same program; the technical term for this is a |
| 2892 | \dfn{persistent} object. Because \module{pickle} is so widely used, |
| 2893 | many authors who write Python extensions take care to ensure that new |
| 2894 | data types such as matrices can be properly pickled and unpickled. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2895 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2896 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2897 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2898 | \chapter{Errors and Exceptions \label{errors}} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2899 | |
| 2900 | Until now error messages haven't been more than mentioned, but if you |
| 2901 | have tried out the examples you have probably seen some. There are |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2902 | (at least) two distinguishable kinds of errors: |
| 2903 | \emph{syntax errors} and \emph{exceptions}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2904 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2905 | \section{Syntax Errors \label{syntaxErrors}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2906 | |
| 2907 | 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] | 2908 | kind of complaint you get while you are still learning Python: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2909 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2910 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2911 | >>> while 1 print 'Hello world' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2912 | File "<stdin>", line 1 |
| 2913 | while 1 print 'Hello world' |
| 2914 | ^ |
| 2915 | SyntaxError: invalid syntax |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2916 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2917 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2918 | The parser repeats the offending line and displays a little `arrow' |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2919 | pointing at the earliest point in the line where the error was |
| 2920 | detected. The error is caused by (or at least detected at) the token |
| 2921 | \emph{preceding} the arrow: in the example, the error is detected at |
| 2922 | the keyword \keyword{print}, since a colon (\character{:}) is missing |
| 2923 | before it. File name and line number are printed so you know where to |
| 2924 | look in case the input came from a script. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2925 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2926 | \section{Exceptions \label{exceptions}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2927 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2928 | Even if a statement or expression is syntactically correct, it may |
| 2929 | cause an error when an attempt is made to execute it. |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 2930 | Errors detected during execution are called \emph{exceptions} and are |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2931 | not unconditionally fatal: you will soon learn how to handle them in |
| 2932 | Python programs. Most exceptions are not handled by programs, |
| 2933 | however, and result in error messages as shown here: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2934 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2935 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2936 | >>> 10 * (1/0) |
Guido van Rossum | 3cbc16d | 1993-12-17 12:13:53 +0000 | [diff] [blame] | 2937 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2938 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2939 | ZeroDivisionError: integer division or modulo |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2940 | >>> 4 + spam*3 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2941 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2942 | File "<stdin>", line 1 |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 2943 | NameError: spam |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2944 | >>> '2' + 2 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2945 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2946 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2947 | TypeError: illegal argument type for built-in operation |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2948 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2949 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2950 | The last line of the error message indicates what happened. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2951 | Exceptions come in different types, and the type is printed as part of |
| 2952 | the message: the types in the example are |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2953 | \exception{ZeroDivisionError}, \exception{NameError} and |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2954 | \exception{TypeError}. |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2955 | The string printed as the exception type is the name of the built-in |
| 2956 | name for the exception that occurred. This is true for all built-in |
| 2957 | exceptions, but need not be true for user-defined exceptions (although |
| 2958 | it is a useful convention). |
| 2959 | Standard exception names are built-in identifiers (not reserved |
| 2960 | keywords). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2961 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2962 | The rest of the line is a detail whose interpretation depends on the |
| 2963 | exception type; its meaning is dependent on the exception type. |
| 2964 | |
| 2965 | The preceding part of the error message shows the context where the |
| 2966 | exception happened, in the form of a stack backtrace. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2967 | In general it contains a stack backtrace listing source lines; however, |
| 2968 | it will not display lines read from standard input. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2969 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2970 | The \emph{Python Library Reference} lists the built-in exceptions and |
| 2971 | their meanings. |
| 2972 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2973 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 2974 | \section{Handling Exceptions \label{handling}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2975 | |
| 2976 | It is possible to write programs that handle selected exceptions. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2977 | Look at the following example, which asks the user for input until a |
| 2978 | valid integer has been entered, but allows the user to interrupt the |
| 2979 | program (using \kbd{Control-C} or whatever the operating system |
| 2980 | supports); note that a user-generated interruption is signalled by |
| 2981 | raising the \exception{KeyboardInterrupt} exception. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2982 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2983 | \begin{verbatim} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2984 | >>> while 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2985 | ... try: |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2986 | ... x = int(raw_input("Please enter a number: ")) |
| 2987 | ... break |
| 2988 | ... except ValueError: |
| 2989 | ... print "Oops! That was no valid number. Try again..." |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 2990 | ... |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2991 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 2992 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 2993 | The \keyword{try} statement works as follows. |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2994 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2995 | \begin{itemize} |
| 2996 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 2997 | First, the \emph{try clause} (the statement(s) between the |
| 2998 | \keyword{try} and \keyword{except} keywords) is executed. |
| 2999 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3000 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3001 | If no exception occurs, the \emph{except\ clause} is skipped and |
| 3002 | execution of the \keyword{try} statement is finished. |
| 3003 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3004 | \item |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3005 | If an exception occurs during execution of the try clause, the rest of |
| 3006 | the clause is skipped. Then if its type matches the exception named |
| 3007 | after the \keyword{except} keyword, the rest of the try clause is |
| 3008 | skipped, the except clause is executed, and then execution continues |
| 3009 | after the \keyword{try} statement. |
| 3010 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3011 | \item |
| 3012 | 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] | 3013 | except clause, it is passed on to outer \keyword{try} statements; if |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3014 | no handler is found, it is an \emph{unhandled exception} and execution |
| 3015 | stops with a message as shown above. |
| 3016 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3017 | \end{itemize} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3018 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3019 | A \keyword{try} statement may have more than one except clause, to |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3020 | specify handlers for different exceptions. At most one handler will |
| 3021 | be executed. Handlers only handle exceptions that occur in the |
| 3022 | corresponding try clause, not in other handlers of the same |
| 3023 | \keyword{try} statement. An except clause may name multiple exceptions |
| 3024 | as a parenthesized list, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3025 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3026 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3027 | ... except (RuntimeError, TypeError, NameError): |
| 3028 | ... pass |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3029 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3030 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3031 | 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] | 3032 | wildcard. Use this with extreme caution, since it is easy to mask a |
| 3033 | real programming error in this way! It can also be used to print an |
| 3034 | error message and then re-raise the exception (allowing a caller to |
| 3035 | handle the exception as well): |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3036 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3037 | \begin{verbatim} |
| 3038 | import string, sys |
| 3039 | |
| 3040 | try: |
| 3041 | f = open('myfile.txt') |
| 3042 | s = f.readline() |
| 3043 | i = int(string.strip(s)) |
| 3044 | except IOError, (errno, strerror): |
| 3045 | print "I/O error(%s): %s" % (errno, strerror) |
| 3046 | except ValueError: |
| 3047 | print "Could not convert data to an integer." |
| 3048 | except: |
| 3049 | print "Unexpected error:", sys.exc_info()[0] |
| 3050 | raise |
| 3051 | \end{verbatim} |
Fred Drake | 2900ff9 | 1999-08-24 22:14:57 +0000 | [diff] [blame] | 3052 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3053 | The \keyword{try} \ldots\ \keyword{except} statement has an optional |
Fred Drake | e99d1db | 2000-04-17 14:56:31 +0000 | [diff] [blame] | 3054 | \emph{else clause}, which, when present, must follow all except |
| 3055 | clauses. It is useful for code that must be executed if the try |
| 3056 | clause does not raise an exception. For example: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3057 | |
| 3058 | \begin{verbatim} |
Guido van Rossum | a4289a7 | 1998-07-07 20:18:06 +0000 | [diff] [blame] | 3059 | for arg in sys.argv[1:]: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3060 | try: |
| 3061 | f = open(arg, 'r') |
| 3062 | except IOError: |
| 3063 | print 'cannot open', arg |
| 3064 | else: |
| 3065 | print arg, 'has', len(f.readlines()), 'lines' |
| 3066 | f.close() |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3067 | \end{verbatim} |
| 3068 | |
Fred Drake | e99d1db | 2000-04-17 14:56:31 +0000 | [diff] [blame] | 3069 | The use of the \keyword{else} clause is better than adding additional |
| 3070 | code to the \keyword{try} clause because it avoids accidentally |
| 3071 | catching an exception that wasn't raised by the code being protected |
| 3072 | by the \keyword{try} \ldots\ \keyword{except} statement. |
| 3073 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3074 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3075 | 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] | 3076 | the exception's \emph{argument}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3077 | The presence and type of the argument depend on the exception type. |
| 3078 | For exception types which have an argument, the except clause may |
| 3079 | specify a variable after the exception name (or list) to receive the |
| 3080 | argument's value, as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3081 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3082 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3083 | >>> try: |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 3084 | ... spam() |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3085 | ... except NameError, x: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 3086 | ... print 'name', x, 'undefined' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3087 | ... |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 3088 | name spam undefined |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3089 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3090 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3091 | 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] | 3092 | (`detail') of the message for unhandled exceptions. |
| 3093 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3094 | Exception handlers don't just handle exceptions if they occur |
| 3095 | immediately in the try clause, but also if they occur inside functions |
| 3096 | that are called (even indirectly) in the try clause. |
| 3097 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3098 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3099 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3100 | >>> def this_fails(): |
| 3101 | ... x = 1/0 |
| 3102 | ... |
| 3103 | >>> try: |
| 3104 | ... this_fails() |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3105 | ... except ZeroDivisionError, detail: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3106 | ... print 'Handling run-time error:', detail |
| 3107 | ... |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3108 | Handling run-time error: integer division or modulo |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3109 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3110 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3111 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3112 | \section{Raising Exceptions \label{raising}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3113 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3114 | The \keyword{raise} statement allows the programmer to force a |
| 3115 | specified exception to occur. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3116 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3117 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3118 | \begin{verbatim} |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3119 | >>> raise NameError, 'HiThere' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3120 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 3121 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3122 | NameError: HiThere |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3123 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3124 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3125 | The first argument to \keyword{raise} names the exception to be |
| 3126 | raised. The optional second argument specifies the exception's |
| 3127 | argument. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3128 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3129 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3130 | \section{User-defined Exceptions \label{userExceptions}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3131 | |
| 3132 | Programs may name their own exceptions by assigning a string to a |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3133 | variable or creating a new exception class. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3134 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3135 | \begin{verbatim} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3136 | >>> class MyError: |
| 3137 | ... def __init__(self, value): |
| 3138 | ... self.value = value |
| 3139 | ... def __str__(self): |
| 3140 | ... return `self.value` |
| 3141 | ... |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3142 | >>> try: |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3143 | ... raise MyError(2*2) |
| 3144 | ... except MyError, e: |
| 3145 | ... print 'My exception occurred, value:', e.value |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3146 | ... |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3147 | My exception occurred, value: 4 |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3148 | >>> raise MyError, 1 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3149 | Traceback (innermost last): |
| 3150 | File "<stdin>", line 1 |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3151 | __main__.MyError: 1 |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3152 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3153 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3154 | Many standard modules use this to report errors that may occur in |
| 3155 | functions they define. |
| 3156 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3157 | More information on classes is presented in chapter \ref{classes}, |
| 3158 | ``Classes.'' |
| 3159 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3160 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3161 | \section{Defining Clean-up Actions \label{cleanup}} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3162 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3163 | The \keyword{try} statement has another optional clause which is |
| 3164 | intended to define clean-up actions that must be executed under all |
| 3165 | circumstances. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 3166 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3167 | \begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3168 | >>> try: |
| 3169 | ... raise KeyboardInterrupt |
| 3170 | ... finally: |
| 3171 | ... print 'Goodbye, world!' |
| 3172 | ... |
| 3173 | Goodbye, world! |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3174 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 3175 | File "<stdin>", line 2 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 3176 | KeyboardInterrupt |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3177 | \end{verbatim} |
Fred Drake | 6c2176e | 1998-02-26 21:47:54 +0000 | [diff] [blame] | 3178 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3179 | A \emph{finally clause} is executed whether or not an exception has |
| 3180 | occurred in the try clause. When an exception has occurred, it is |
| 3181 | re-raised after the finally clause is executed. The finally clause is |
| 3182 | also executed ``on the way out'' when the \keyword{try} statement is |
| 3183 | left via a \keyword{break} or \keyword{return} statement. |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 3184 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3185 | A \keyword{try} statement must either have one or more except clauses |
| 3186 | or one finally clause, but not both. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 3187 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3188 | \chapter{Classes \label{classes}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3189 | |
| 3190 | Python's class mechanism adds classes to the language with a minimum |
| 3191 | 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] | 3192 | 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] | 3193 | do not put an absolute barrier between definition and user, but rather |
| 3194 | rely on the politeness of the user not to ``break into the |
| 3195 | definition.'' The most important features of classes are retained |
| 3196 | with full power, however: the class inheritance mechanism allows |
| 3197 | multiple base classes, a derived class can override any methods of its |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3198 | 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] | 3199 | same name. Objects can contain an arbitrary amount of private data. |
| 3200 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 3201 | In \Cpp{} terminology, all class members (including the data members) are |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3202 | \emph{public}, and all member functions are \emph{virtual}. There are |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3203 | 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] | 3204 | shorthands for referencing the object's members from its methods: the |
| 3205 | method function is declared with an explicit first argument |
| 3206 | representing the object, which is provided implicitly by the call. As |
| 3207 | in Smalltalk, classes themselves are objects, albeit in the wider |
| 3208 | sense of the word: in Python, all data types are objects. This |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3209 | provides semantics for importing and renaming. But, just like in |
| 3210 | \Cpp{} or Modula-3, built-in types cannot be used as base classes for |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 3211 | 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] | 3212 | built-in operators with special syntax (arithmetic operators, |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3213 | subscripting etc.) can be redefined for class instances. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3214 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3215 | \section{A Word About Terminology \label{terminology}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3216 | |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3217 | Lacking universally accepted terminology to talk about classes, I will |
| 3218 | 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] | 3219 | terms, since its object-oriented semantics are closer to those of |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3220 | 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] | 3221 | |
| 3222 | I also have to warn you that there's a terminological pitfall for |
| 3223 | object-oriented readers: the word ``object'' in Python does not |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3224 | necessarily mean a class instance. Like \Cpp{} and Modula-3, and |
| 3225 | unlike Smalltalk, not all types in Python are classes: the basic |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3226 | 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] | 3227 | exotic types like files aren't. However, \emph{all} Python types |
| 3228 | share a little bit of common semantics that is best described by using |
| 3229 | the word object. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3230 | |
| 3231 | Objects have individuality, and multiple names (in multiple scopes) |
| 3232 | can be bound to the same object. This is known as aliasing in other |
| 3233 | languages. This is usually not appreciated on a first glance at |
| 3234 | Python, and can be safely ignored when dealing with immutable basic |
| 3235 | types (numbers, strings, tuples). However, aliasing has an |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3236 | (intended!) effect on the semantics of Python code involving mutable |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3237 | objects such as lists, dictionaries, and most types representing |
| 3238 | entities outside the program (files, windows, etc.). This is usually |
| 3239 | used to the benefit of the program, since aliases behave like pointers |
| 3240 | in some respects. For example, passing an object is cheap since only |
| 3241 | a pointer is passed by the implementation; and if a function modifies |
| 3242 | an object passed as an argument, the caller will see the change --- this |
| 3243 | obviates the need for two different argument passing mechanisms as in |
| 3244 | Pascal. |
| 3245 | |
| 3246 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3247 | \section{Python Scopes and Name Spaces \label{scopes}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3248 | |
| 3249 | Before introducing classes, I first have to tell you something about |
| 3250 | Python's scope rules. Class definitions play some neat tricks with |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3251 | 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] | 3252 | fully understand what's going on. Incidentally, knowledge about this |
| 3253 | subject is useful for any advanced Python programmer. |
| 3254 | |
| 3255 | Let's begin with some definitions. |
| 3256 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3257 | A \emph{namespace} is a mapping from names to objects. Most |
| 3258 | namespaces are currently implemented as Python dictionaries, but |
| 3259 | that's normally not noticeable in any way (except for performance), |
| 3260 | and it may change in the future. Examples of namespaces are: the set |
| 3261 | of built-in names (functions such as \function{abs()}, and built-in |
| 3262 | exception names); the global names in a module; and the local names in |
| 3263 | a function invocation. In a sense the set of attributes of an object |
| 3264 | also form a namespace. The important thing to know about namespaces |
| 3265 | is that there is absolutely no relation between names in different |
| 3266 | namespaces; for instance, two different modules may both define a |
| 3267 | function ``maximize'' without confusion --- users of the modules must |
| 3268 | prefix it with the module name. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3269 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3270 | 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] | 3271 | dot --- for example, in the expression \code{z.real}, \code{real} is |
| 3272 | an attribute of the object \code{z}. Strictly speaking, references to |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3273 | names in modules are attribute references: in the expression |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3274 | \code{modname.funcname}, \code{modname} is a module object and |
| 3275 | \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] | 3276 | be a straightforward mapping between the module's attributes and the |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3277 | global names defined in the module: they share the same namespace! |
| 3278 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3279 | Except for one thing. Module objects have a secret read-only |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3280 | attribute called \member{__dict__} which returns the dictionary |
| 3281 | used to implement the module's namespace; the name |
| 3282 | \member{__dict__} is an attribute but not a global name. |
| 3283 | Obviously, using this violates the abstraction of namespace |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3284 | implementation, and should be restricted to things like |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3285 | post-mortem debuggers. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3286 | } |
| 3287 | |
| 3288 | Attributes may be read-only or writable. In the latter case, |
| 3289 | assignment to attributes is possible. Module attributes are writable: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3290 | you can write \samp{modname.the_answer = 42}. Writable attributes may |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3291 | also be deleted with the \keyword{del} statement, e.g. |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3292 | \samp{del modname.the_answer}. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3293 | |
| 3294 | Name spaces are created at different moments and have different |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3295 | lifetimes. The namespace containing the built-in names is created |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3296 | when the Python interpreter starts up, and is never deleted. The |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3297 | global namespace for a module is created when the module definition |
| 3298 | is read in; normally, module namespaces also last until the |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3299 | interpreter quits. The statements executed by the top-level |
| 3300 | invocation of the interpreter, either read from a script file or |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3301 | interactively, are considered part of a module called |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3302 | \module{__main__}, so they have their own global namespace. (The |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3303 | built-in names actually also live in a module; this is called |
| 3304 | \module{__builtin__}.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3305 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3306 | 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] | 3307 | called, and deleted when the function returns or raises an exception |
| 3308 | that is not handled within the function. (Actually, forgetting would |
| 3309 | be a better way to describe what actually happens.) Of course, |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3310 | recursive invocations each have their own local namespace. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3311 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3312 | A \emph{scope} is a textual region of a Python program where a |
| 3313 | namespace is directly accessible. ``Directly accessible'' here means |
| 3314 | that an unqualified reference to a name attempts to find the name in |
| 3315 | the namespace. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3316 | |
| 3317 | Although scopes are determined statically, they are used dynamically. |
| 3318 | At any time during execution, exactly three nested scopes are in use |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3319 | (i.e., exactly three namespaces are directly accessible): the |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3320 | innermost scope, which is searched first, contains the local names, |
| 3321 | the middle scope, searched next, contains the current module's global |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3322 | names, and the outermost scope (searched last) is the namespace |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3323 | containing built-in names. |
| 3324 | |
| 3325 | Usually, the local scope references the local names of the (textually) |
Guido van Rossum | 96628a9 | 1995-04-10 11:34:00 +0000 | [diff] [blame] | 3326 | current function. Outside of functions, the local scope references |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3327 | the same namespace as the global scope: the module's namespace. |
| 3328 | Class definitions place yet another namespace in the local scope. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3329 | |
| 3330 | It is important to realize that scopes are determined textually: the |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3331 | global scope of a function defined in a module is that module's |
| 3332 | namespace, no matter from where or by what alias the function is |
| 3333 | called. On the other hand, the actual search for names is done |
| 3334 | dynamically, at run time --- however, the language definition is |
| 3335 | evolving towards static name resolution, at ``compile'' time, so don't |
| 3336 | rely on dynamic name resolution! (In fact, local variables are |
| 3337 | already determined statically.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3338 | |
| 3339 | A special quirk of Python is that assignments always go into the |
| 3340 | innermost scope. Assignments do not copy data --- they just |
| 3341 | bind names to objects. The same is true for deletions: the statement |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3342 | \samp{del x} removes the binding of \code{x} from the namespace |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3343 | referenced by the local scope. In fact, all operations that introduce |
| 3344 | new names use the local scope: in particular, import statements and |
| 3345 | function definitions bind the module or function name in the local |
| 3346 | scope. (The \keyword{global} statement can be used to indicate that |
| 3347 | particular variables live in the global scope.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3348 | |
| 3349 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3350 | \section{A First Look at Classes \label{firstClasses}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3351 | |
| 3352 | Classes introduce a little bit of new syntax, three new object types, |
| 3353 | and some new semantics. |
| 3354 | |
| 3355 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3356 | \subsection{Class Definition Syntax \label{classDefinition}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3357 | |
| 3358 | The simplest form of class definition looks like this: |
| 3359 | |
| 3360 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3361 | class ClassName: |
| 3362 | <statement-1> |
| 3363 | . |
| 3364 | . |
| 3365 | . |
| 3366 | <statement-N> |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3367 | \end{verbatim} |
| 3368 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3369 | Class definitions, like function definitions |
| 3370 | (\keyword{def} statements) must be executed before they have any |
| 3371 | effect. (You could conceivably place a class definition in a branch |
| 3372 | of an \keyword{if} statement, or inside a function.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3373 | |
| 3374 | In practice, the statements inside a class definition will usually be |
| 3375 | function definitions, but other statements are allowed, and sometimes |
| 3376 | useful --- we'll come back to this later. The function definitions |
| 3377 | inside a class normally have a peculiar form of argument list, |
| 3378 | dictated by the calling conventions for methods --- again, this is |
| 3379 | explained later. |
| 3380 | |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3381 | 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] | 3382 | used as the local scope --- thus, all assignments to local variables |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3383 | go into this new namespace. In particular, function definitions bind |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3384 | the name of the new function here. |
| 3385 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3386 | 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] | 3387 | object} is created. This is basically a wrapper around the contents |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3388 | 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] | 3389 | about class objects in the next section. The original local scope |
| 3390 | (the one in effect just before the class definitions was entered) is |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 3391 | reinstated, and the class object is bound here to the class name given |
| 3392 | in the class definition header (\class{ClassName} in the example). |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3393 | |
| 3394 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3395 | \subsection{Class Objects \label{classObjects}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3396 | |
| 3397 | Class objects support two kinds of operations: attribute references |
| 3398 | and instantiation. |
| 3399 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3400 | \emph{Attribute references} use the standard syntax used for all |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3401 | attribute references in Python: \code{obj.name}. Valid attribute |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3402 | 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] | 3403 | class object was created. So, if the class definition looked like |
| 3404 | this: |
| 3405 | |
| 3406 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3407 | class MyClass: |
| 3408 | "A simple example class" |
| 3409 | i = 12345 |
| 3410 | def f(x): |
| 3411 | return 'hello world' |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3412 | \end{verbatim} |
| 3413 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3414 | then \code{MyClass.i} and \code{MyClass.f} are valid attribute |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3415 | references, returning an integer and a method object, respectively. |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3416 | 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] | 3417 | of \code{MyClass.i} by assignment. \member{__doc__} is also a valid |
| 3418 | attribute, returning the docstring belonging to the class: \code{"A |
| 3419 | simple example class"}). |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3420 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3421 | Class \emph{instantiation} uses function notation. Just pretend that |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3422 | the class object is a parameterless function that returns a new |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3423 | instance of the class. For example (assuming the above class): |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3424 | |
| 3425 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3426 | x = MyClass() |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3427 | \end{verbatim} |
| 3428 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3429 | creates a new \emph{instance} of the class and assigns this object to |
| 3430 | the local variable \code{x}. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3431 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3432 | The instantiation operation (``calling'' a class object) creates an |
| 3433 | empty object. Many classes like to create objects in a known initial |
| 3434 | state. Therefore a class may define a special method named |
| 3435 | \method{__init__()}, like this: |
| 3436 | |
| 3437 | \begin{verbatim} |
| 3438 | def __init__(self): |
| 3439 | self.data = [] |
| 3440 | \end{verbatim} |
| 3441 | |
| 3442 | When a class defines an \method{__init__()} method, class |
| 3443 | instantiation automatically invokes \method{__init__()} for the |
| 3444 | newly-created class instance. So in this example, a new, initialized |
| 3445 | instance can be obtained by: |
| 3446 | |
| 3447 | \begin{verbatim} |
| 3448 | x = MyClass() |
| 3449 | \end{verbatim} |
| 3450 | |
| 3451 | Of course, the \method{__init__()} method may have arguments for |
| 3452 | greater flexibility. In that case, arguments given to the class |
| 3453 | instantiation operator are passed on to \method{__init__()}. For |
| 3454 | example, |
| 3455 | |
| 3456 | \begin{verbatim} |
| 3457 | >>> class Complex: |
| 3458 | ... def __init__(self, realpart, imagpart): |
| 3459 | ... self.r = realpart |
| 3460 | ... self.i = imagpart |
| 3461 | ... |
| 3462 | >>> x = Complex(3.0,-4.5) |
| 3463 | >>> x.r, x.i |
| 3464 | (3.0, -4.5) |
| 3465 | \end{verbatim} |
| 3466 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3467 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3468 | \subsection{Instance Objects \label{instanceObjects}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3469 | |
| 3470 | Now what can we do with instance objects? The only operations |
| 3471 | understood by instance objects are attribute references. There are |
| 3472 | two kinds of valid attribute names. |
| 3473 | |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3474 | The first I'll call \emph{data attributes}. These correspond to |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3475 | ``instance variables'' in Smalltalk, and to ``data members'' in |
| 3476 | \Cpp{}. Data attributes need not be declared; like local variables, |
| 3477 | they spring into existence when they are first assigned to. For |
| 3478 | example, if \code{x} is the instance of \class{MyClass} created above, |
| 3479 | the following piece of code will print the value \code{16}, without |
| 3480 | leaving a trace: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3481 | |
| 3482 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3483 | x.counter = 1 |
| 3484 | while x.counter < 10: |
| 3485 | x.counter = x.counter * 2 |
| 3486 | print x.counter |
| 3487 | del x.counter |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3488 | \end{verbatim} |
| 3489 | |
| 3490 | The second kind of attribute references understood by instance objects |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3491 | 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] | 3492 | object. (In Python, the term method is not unique to class instances: |
| 3493 | other object types can have methods as well, e.g., list objects have |
| 3494 | methods called append, insert, remove, sort, and so on. However, |
| 3495 | below, we'll use the term method exclusively to mean methods of class |
| 3496 | instance objects, unless explicitly stated otherwise.) |
| 3497 | |
| 3498 | Valid method names of an instance object depend on its class. By |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3499 | definition, all attributes of a class that are (user-defined) function |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3500 | objects define corresponding methods of its instances. So in our |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3501 | example, \code{x.f} is a valid method reference, since |
| 3502 | \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] | 3503 | \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] | 3504 | \code{MyClass.f} --- it is a \obindex{method}\emph{method object}, not |
| 3505 | a function object. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3506 | |
| 3507 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3508 | \subsection{Method Objects \label{methodObjects}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3509 | |
| 3510 | Usually, a method is called immediately, e.g.: |
| 3511 | |
| 3512 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3513 | x.f() |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3514 | \end{verbatim} |
| 3515 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3516 | In our example, this will return the string \code{'hello world'}. |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3517 | However, it is not necessary to call a method right away: |
| 3518 | \code{x.f} is a method object, and can be stored away and called at a |
| 3519 | later time. For example: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3520 | |
| 3521 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3522 | xf = x.f |
| 3523 | while 1: |
| 3524 | print xf() |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3525 | \end{verbatim} |
| 3526 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3527 | 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] | 3528 | |
| 3529 | What exactly happens when a method is called? You may have noticed |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3530 | that \code{x.f()} was called without an argument above, even though |
| 3531 | the function definition for \method{f} specified an argument. What |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3532 | happened to the argument? Surely Python raises an exception when a |
| 3533 | function that requires an argument is called without any --- even if |
| 3534 | the argument isn't actually used... |
| 3535 | |
| 3536 | Actually, you may have guessed the answer: the special thing about |
| 3537 | 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] | 3538 | function. In our example, the call \code{x.f()} is exactly equivalent |
| 3539 | 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] | 3540 | \var{n} arguments is equivalent to calling the corresponding function |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3541 | with an argument list that is created by inserting the method's object |
| 3542 | before the first argument. |
| 3543 | |
| 3544 | If you still don't understand how methods work, a look at the |
| 3545 | implementation can perhaps clarify matters. When an instance |
| 3546 | attribute is referenced that isn't a data attribute, its class is |
| 3547 | searched. If the name denotes a valid class attribute that is a |
| 3548 | function object, a method object is created by packing (pointers to) |
| 3549 | the instance object and the function object just found together in an |
| 3550 | abstract object: this is the method object. When the method object is |
| 3551 | called with an argument list, it is unpacked again, a new argument |
| 3552 | list is constructed from the instance object and the original argument |
| 3553 | list, and the function object is called with this new argument list. |
| 3554 | |
| 3555 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3556 | \section{Random Remarks \label{remarks}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3557 | |
| 3558 | [These should perhaps be placed more carefully...] |
| 3559 | |
| 3560 | |
| 3561 | Data attributes override method attributes with the same name; to |
| 3562 | avoid accidental name conflicts, which may cause hard-to-find bugs in |
| 3563 | large programs, it is wise to use some kind of convention that |
| 3564 | minimizes the chance of conflicts, e.g., capitalize method names, |
| 3565 | prefix data attribute names with a small unique string (perhaps just |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3566 | an underscore), or use verbs for methods and nouns for data attributes. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3567 | |
| 3568 | |
| 3569 | Data attributes may be referenced by methods as well as by ordinary |
| 3570 | users (``clients'') of an object. In other words, classes are not |
| 3571 | usable to implement pure abstract data types. In fact, nothing in |
| 3572 | Python makes it possible to enforce data hiding --- it is all based |
| 3573 | upon convention. (On the other hand, the Python implementation, |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3574 | written in C, can completely hide implementation details and control |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3575 | 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] | 3576 | Python written in C.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3577 | |
| 3578 | |
| 3579 | Clients should use data attributes with care --- clients may mess up |
| 3580 | invariants maintained by the methods by stamping on their data |
| 3581 | attributes. Note that clients may add data attributes of their own to |
| 3582 | an instance object without affecting the validity of the methods, as |
| 3583 | long as name conflicts are avoided --- again, a naming convention can |
| 3584 | save a lot of headaches here. |
| 3585 | |
| 3586 | |
| 3587 | There is no shorthand for referencing data attributes (or other |
| 3588 | methods!) from within methods. I find that this actually increases |
| 3589 | the readability of methods: there is no chance of confusing local |
| 3590 | variables and instance variables when glancing through a method. |
| 3591 | |
| 3592 | |
| 3593 | Conventionally, the first argument of methods is often called |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3594 | \code{self}. This is nothing more than a convention: the name |
| 3595 | \code{self} has absolutely no special meaning to Python. (Note, |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3596 | however, that by not following the convention your code may be less |
| 3597 | readable by other Python programmers, and it is also conceivable that |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3598 | 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] | 3599 | convention.) |
| 3600 | |
| 3601 | |
| 3602 | Any function object that is a class attribute defines a method for |
| 3603 | instances of that class. It is not necessary that the function |
| 3604 | definition is textually enclosed in the class definition: assigning a |
| 3605 | function object to a local variable in the class is also ok. For |
| 3606 | example: |
| 3607 | |
| 3608 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3609 | # Function defined outside the class |
| 3610 | def f1(self, x, y): |
| 3611 | return min(x, x+y) |
| 3612 | |
| 3613 | class C: |
| 3614 | f = f1 |
| 3615 | def g(self): |
| 3616 | return 'hello world' |
| 3617 | h = g |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3618 | \end{verbatim} |
| 3619 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3620 | Now \code{f}, \code{g} and \code{h} are all attributes of class |
| 3621 | \class{C} that refer to function objects, and consequently they are all |
| 3622 | methods of instances of \class{C} --- \code{h} being exactly equivalent |
| 3623 | 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] | 3624 | the reader of a program. |
| 3625 | |
| 3626 | |
| 3627 | Methods may call other methods by using method attributes of the |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3628 | \code{self} argument, e.g.: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3629 | |
| 3630 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3631 | class Bag: |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3632 | def __init__(self): |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3633 | self.data = [] |
| 3634 | def add(self, x): |
| 3635 | self.data.append(x) |
| 3636 | def addtwice(self, x): |
| 3637 | self.add(x) |
| 3638 | self.add(x) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3639 | \end{verbatim} |
| 3640 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3641 | Methods may reference global names in the same way as ordinary |
| 3642 | functions. The global scope associated with a method is the module |
| 3643 | containing the class definition. (The class itself is never used as a |
| 3644 | global scope!) While one rarely encounters a good reason for using |
| 3645 | global data in a method, there are many legitimate uses of the global |
| 3646 | scope: for one thing, functions and modules imported into the global |
| 3647 | scope can be used by methods, as well as functions and classes defined |
| 3648 | in it. Usually, the class containing the method is itself defined in |
| 3649 | this global scope, and in the next section we'll find some good |
| 3650 | reasons why a method would want to reference its own class! |
| 3651 | |
| 3652 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3653 | \section{Inheritance \label{inheritance}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3654 | |
| 3655 | Of course, a language feature would not be worthy of the name ``class'' |
| 3656 | without supporting inheritance. The syntax for a derived class |
| 3657 | definition looks as follows: |
| 3658 | |
| 3659 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3660 | class DerivedClassName(BaseClassName): |
| 3661 | <statement-1> |
| 3662 | . |
| 3663 | . |
| 3664 | . |
| 3665 | <statement-N> |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3666 | \end{verbatim} |
| 3667 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3668 | The name \class{BaseClassName} must be defined in a scope containing |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3669 | the derived class definition. Instead of a base class name, an |
| 3670 | expression is also allowed. This is useful when the base class is |
| 3671 | defined in another module, e.g., |
| 3672 | |
| 3673 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3674 | class DerivedClassName(modname.BaseClassName): |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3675 | \end{verbatim} |
| 3676 | |
| 3677 | Execution of a derived class definition proceeds the same as for a |
| 3678 | base class. When the class object is constructed, the base class is |
| 3679 | remembered. This is used for resolving attribute references: if a |
| 3680 | requested attribute is not found in the class, it is searched in the |
| 3681 | base class. This rule is applied recursively if the base class itself |
| 3682 | is derived from some other class. |
| 3683 | |
| 3684 | There's nothing special about instantiation of derived classes: |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3685 | \code{DerivedClassName()} creates a new instance of the class. Method |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3686 | references are resolved as follows: the corresponding class attribute |
| 3687 | is searched, descending down the chain of base classes if necessary, |
| 3688 | and the method reference is valid if this yields a function object. |
| 3689 | |
| 3690 | Derived classes may override methods of their base classes. Because |
| 3691 | methods have no special privileges when calling other methods of the |
| 3692 | same object, a method of a base class that calls another method |
| 3693 | 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] | 3694 | a derived class that overrides it. (For \Cpp{} programmers: all methods |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3695 | in Python are effectively \keyword{virtual}.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3696 | |
| 3697 | An overriding method in a derived class may in fact want to extend |
| 3698 | rather than simply replace the base class method of the same name. |
| 3699 | 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] | 3700 | call \samp{BaseClassName.methodname(self, arguments)}. This is |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3701 | occasionally useful to clients as well. (Note that this only works if |
| 3702 | the base class is defined or imported directly in the global scope.) |
| 3703 | |
| 3704 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3705 | \subsection{Multiple Inheritance \label{multiple}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3706 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3707 | Python supports a limited form of multiple inheritance as well. A |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3708 | class definition with multiple base classes looks as follows: |
| 3709 | |
| 3710 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3711 | class DerivedClassName(Base1, Base2, Base3): |
| 3712 | <statement-1> |
| 3713 | . |
| 3714 | . |
| 3715 | . |
| 3716 | <statement-N> |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3717 | \end{verbatim} |
| 3718 | |
| 3719 | The only rule necessary to explain the semantics is the resolution |
| 3720 | rule used for class attribute references. This is depth-first, |
| 3721 | left-to-right. Thus, if an attribute is not found in |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3722 | \class{DerivedClassName}, it is searched in \class{Base1}, then |
| 3723 | (recursively) in the base classes of \class{Base1}, and only if it is |
| 3724 | 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] | 3725 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3726 | (To some people breadth first --- searching \class{Base2} and |
| 3727 | \class{Base3} before the base classes of \class{Base1} --- looks more |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3728 | natural. However, this would require you to know whether a particular |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3729 | 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] | 3730 | 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] | 3731 | 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] | 3732 | rule makes no differences between direct and inherited attributes of |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3733 | \class{Base1}.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3734 | |
| 3735 | It is clear that indiscriminate use of multiple inheritance is a |
| 3736 | maintenance nightmare, given the reliance in Python on conventions to |
| 3737 | avoid accidental name conflicts. A well-known problem with multiple |
| 3738 | inheritance is a class derived from two classes that happen to have a |
| 3739 | common base class. While it is easy enough to figure out what happens |
| 3740 | in this case (the instance will have a single copy of ``instance |
| 3741 | variables'' or data attributes used by the common base class), it is |
| 3742 | not clear that these semantics are in any way useful. |
| 3743 | |
| 3744 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3745 | \section{Private Variables \label{private}} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3746 | |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 3747 | There is limited support for class-private |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3748 | identifiers. Any identifier of the form \code{__spam} (at least two |
| 3749 | leading underscores, at most one trailing underscore) is now textually |
| 3750 | replaced with \code{_classname__spam}, where \code{classname} is the |
| 3751 | current class name with leading underscore(s) stripped. This mangling |
| 3752 | is done without regard of the syntactic position of the identifier, so |
| 3753 | it can be used to define class-private instance and class variables, |
| 3754 | methods, as well as globals, and even to store instance variables |
Fred Drake | eee08cd | 1997-12-04 15:43:15 +0000 | [diff] [blame] | 3755 | private to this class on instances of \emph{other} classes. Truncation |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3756 | may occur when the mangled name would be longer than 255 characters. |
| 3757 | Outside classes, or when the class name consists of only underscores, |
| 3758 | no mangling occurs. |
| 3759 | |
| 3760 | Name mangling is intended to give classes an easy way to define |
| 3761 | ``private'' instance variables and methods, without having to worry |
| 3762 | about instance variables defined by derived classes, or mucking with |
| 3763 | instance variables by code outside the class. Note that the mangling |
| 3764 | rules are designed mostly to avoid accidents; it still is possible for |
| 3765 | a determined soul to access or modify a variable that is considered |
| 3766 | private. This can even be useful, e.g. for the debugger, and that's |
| 3767 | one reason why this loophole is not closed. (Buglet: derivation of a |
| 3768 | class with the same name as the base class makes use of private |
| 3769 | variables of the base class possible.) |
| 3770 | |
| 3771 | Notice that code passed to \code{exec}, \code{eval()} or |
| 3772 | \code{evalfile()} does not consider the classname of the invoking |
| 3773 | class to be the current class; this is similar to the effect of the |
| 3774 | \code{global} statement, the effect of which is likewise restricted to |
| 3775 | code that is byte-compiled together. The same restriction applies to |
| 3776 | \code{getattr()}, \code{setattr()} and \code{delattr()}, as well as |
| 3777 | when referencing \code{__dict__} directly. |
| 3778 | |
| 3779 | Here's an example of a class that implements its own |
Fred Drake | 1349437 | 2000-09-12 16:23:48 +0000 | [diff] [blame] | 3780 | \method{__getattr__()} and \method{__setattr__()} methods and stores |
| 3781 | all attributes in a private variable, in a way that works in all |
| 3782 | versions of Python, including those available before this feature was |
| 3783 | added: |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3784 | |
| 3785 | \begin{verbatim} |
| 3786 | class VirtualAttributes: |
| 3787 | __vdict = None |
| 3788 | __vdict_name = locals().keys()[0] |
| 3789 | |
| 3790 | def __init__(self): |
| 3791 | self.__dict__[self.__vdict_name] = {} |
| 3792 | |
| 3793 | def __getattr__(self, name): |
| 3794 | return self.__vdict[name] |
| 3795 | |
| 3796 | def __setattr__(self, name, value): |
| 3797 | self.__vdict[name] = value |
| 3798 | \end{verbatim} |
| 3799 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3800 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3801 | \section{Odds and Ends \label{odds}} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3802 | |
| 3803 | 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] | 3804 | ``record'' or C ``struct'', bundling together a couple of named data |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3805 | items. An empty class definition will do nicely, e.g.: |
| 3806 | |
| 3807 | \begin{verbatim} |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3808 | class Employee: |
| 3809 | pass |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3810 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3811 | john = Employee() # Create an empty employee record |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3812 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3813 | # Fill the fields of the record |
| 3814 | john.name = 'John Doe' |
| 3815 | john.dept = 'computer lab' |
| 3816 | john.salary = 1000 |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3817 | \end{verbatim} |
| 3818 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3819 | A piece of Python code that expects a particular abstract data type |
| 3820 | can often be passed a class that emulates the methods of that data |
| 3821 | type instead. For instance, if you have a function that formats some |
| 3822 | data from a file object, you can define a class with methods |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3823 | \method{read()} and \method{readline()} that gets the data from a string |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3824 | buffer instead, and pass it as an argument.% (Unfortunately, this |
| 3825 | %technique has its limitations: a class can't define operations that |
| 3826 | %are accessed by special syntax such as sequence subscripting or |
| 3827 | %arithmetic operators, and assigning such a ``pseudo-file'' to |
| 3828 | %\code{sys.stdin} will not cause the interpreter to read further input |
| 3829 | %from it.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3830 | |
| 3831 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3832 | Instance method objects have attributes, too: \code{m.im_self} is the |
| 3833 | 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] | 3834 | function object corresponding to the method. |
| 3835 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3836 | \subsection{Exceptions Can Be Classes \label{exceptionClasses}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3837 | |
| 3838 | User-defined exceptions are no longer limited to being string objects |
| 3839 | --- they can be identified by classes as well. Using this mechanism it |
| 3840 | is possible to create extensible hierarchies of exceptions. |
| 3841 | |
| 3842 | There are two new valid (semantic) forms for the raise statement: |
| 3843 | |
| 3844 | \begin{verbatim} |
| 3845 | raise Class, instance |
| 3846 | |
| 3847 | raise instance |
| 3848 | \end{verbatim} |
| 3849 | |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 3850 | In the first form, \code{instance} must be an instance of |
| 3851 | \class{Class} or of a class derived from it. The second form is a |
| 3852 | shorthand for: |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3853 | |
| 3854 | \begin{verbatim} |
| 3855 | raise instance.__class__, instance |
| 3856 | \end{verbatim} |
| 3857 | |
| 3858 | An except clause may list classes as well as string objects. A class |
| 3859 | in an except clause is compatible with an exception if it is the same |
| 3860 | class or a base class thereof (but not the other way around --- an |
| 3861 | except clause listing a derived class is not compatible with a base |
| 3862 | class). For example, the following code will print B, C, D in that |
| 3863 | order: |
| 3864 | |
| 3865 | \begin{verbatim} |
| 3866 | class B: |
| 3867 | pass |
| 3868 | class C(B): |
| 3869 | pass |
| 3870 | class D(C): |
| 3871 | pass |
| 3872 | |
| 3873 | for c in [B, C, D]: |
| 3874 | try: |
| 3875 | raise c() |
| 3876 | except D: |
| 3877 | print "D" |
| 3878 | except C: |
| 3879 | print "C" |
| 3880 | except B: |
| 3881 | print "B" |
| 3882 | \end{verbatim} |
| 3883 | |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3884 | Note that if the except clauses were reversed (with |
| 3885 | \samp{except B} first), it would have printed B, B, B --- the first |
| 3886 | matching except clause is triggered. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3887 | |
| 3888 | When an error message is printed for an unhandled exception which is a |
| 3889 | class, the class name is printed, then a colon and a space, and |
| 3890 | finally the instance converted to a string using the built-in function |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3891 | \function{str()}. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3892 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3893 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3894 | \chapter{What Now? \label{whatNow}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3895 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3896 | Hopefully reading this tutorial has reinforced your interest in using |
| 3897 | Python. Now what should you do? |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3898 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3899 | You should read, or at least page through, the Library Reference, |
| 3900 | which gives complete (though terse) reference material about types, |
| 3901 | functions, and modules that can save you a lot of time when writing |
| 3902 | Python programs. The standard Python distribution includes a |
Fred Drake | ee84d59 | 1999-03-10 17:25:30 +0000 | [diff] [blame] | 3903 | \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] | 3904 | \UNIX{} mailboxes, retrieve documents via HTTP, generate random |
| 3905 | numbers, parse command-line options, write CGI programs, compress |
| 3906 | data, and a lot more; skimming through the Library Reference will give |
| 3907 | you an idea of what's available. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3908 | |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 3909 | 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] | 3910 | code, documentation, and pointers to Python-related pages around the |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3911 | Web. This web site is mirrored in various places around the |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3912 | world, such as Europe, Japan, and Australia; a mirror may be faster |
| 3913 | than the main site, depending on your geographical location. A more |
Fred Drake | c0fcbc1 | 1999-04-29 02:30:04 +0000 | [diff] [blame] | 3914 | informal site is \url{http://starship.python.net/}, which contains a |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3915 | bunch of Python-related personal home pages; many people have |
Fred Drake | c0fcbc1 | 1999-04-29 02:30:04 +0000 | [diff] [blame] | 3916 | downloadable software there. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3917 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3918 | For Python-related questions and problem reports, you can post to the |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3919 | newsgroup \newsgroup{comp.lang.python}, or send them to the mailing |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 3920 | list at \email{python-list@python.org}. The newsgroup and mailing list |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3921 | are gatewayed, so messages posted to one will automatically be |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 3922 | forwarded to the other. There are around 120 postings a day, |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3923 | % Postings figure based on average of last six months activity as |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 3924 | % reported by www.egroups.com; Jan. 2000 - June 2000: 21272 msgs / 182 |
| 3925 | % days = 116.9 msgs / day and steadily increasing. |
Fred Drake | 391564f | 1998-04-01 23:11:56 +0000 | [diff] [blame] | 3926 | asking (and answering) questions, suggesting new features, and |
| 3927 | announcing new modules. Before posting, be sure to check the list of |
| 3928 | Frequently Asked Questions (also called the FAQ), at |
Fred Drake | ca6567f | 1998-01-22 20:44:18 +0000 | [diff] [blame] | 3929 | \url{http://www.python.org/doc/FAQ.html}, or look for it in the |
Fred Drake | 518e55c | 2000-07-27 20:55:12 +0000 | [diff] [blame] | 3930 | \file{Misc/} directory of the Python source distribution. Mailing |
| 3931 | list archives are available at \url{http://www.python.org/pipermail/}. |
| 3932 | The FAQ answers many of the questions that come up again and again, |
| 3933 | and may already contain the solution for your problem. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3934 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3935 | |
Fred Drake | a594baf | 1998-04-03 05:16:31 +0000 | [diff] [blame] | 3936 | \appendix |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3937 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3938 | \chapter{Interactive Input Editing and History Substitution |
| 3939 | \label{interacting}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3940 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3941 | Some versions of the Python interpreter support editing of the current |
| 3942 | input line and history substitution, similar to facilities found in |
| 3943 | 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] | 3944 | \emph{GNU Readline} library, which supports Emacs-style and vi-style |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3945 | editing. This library has its own documentation which I won't |
Fred Drake | cc09e8d | 1998-12-28 21:21:36 +0000 | [diff] [blame] | 3946 | duplicate here; however, the basics are easily explained. The |
| 3947 | interactive editing and history described here are optionally |
| 3948 | available in the \UNIX{} and CygWin versions of the interpreter. |
| 3949 | |
| 3950 | This chapter does \emph{not} document the editing facilities of Mark |
| 3951 | Hammond's PythonWin package or the Tk-based environment, IDLE, |
| 3952 | distributed with Python. The command line history recall which |
| 3953 | operates within DOS boxes on NT and some other DOS and Windows flavors |
| 3954 | is yet another beast. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3955 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3956 | \section{Line Editing \label{lineEditing}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3957 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3958 | If supported, input line editing is active whenever the interpreter |
| 3959 | prints a primary or secondary prompt. The current line can be edited |
| 3960 | using the conventional Emacs control characters. The most important |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 3961 | of these are: \kbd{C-A} (Control-A) moves the cursor to the beginning |
| 3962 | of the line, \kbd{C-E} to the end, \kbd{C-B} moves it one position to |
| 3963 | the left, \kbd{C-F} to the right. Backspace erases the character to |
| 3964 | the left of the cursor, \kbd{C-D} the character to its right. |
| 3965 | \kbd{C-K} kills (erases) the rest of the line to the right of the |
| 3966 | cursor, \kbd{C-Y} yanks back the last killed string. |
| 3967 | \kbd{C-underscore} undoes the last change you made; it can be repeated |
| 3968 | for cumulative effect. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3969 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3970 | \section{History Substitution \label{history}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3971 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3972 | History substitution works as follows. All non-empty input lines |
| 3973 | 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] | 3974 | you are positioned on a new line at the bottom of this buffer. |
| 3975 | \kbd{C-P} moves one line up (back) in the history buffer, |
| 3976 | \kbd{C-N} moves one down. Any line in the history buffer can be |
| 3977 | edited; an asterisk appears in front of the prompt to mark a line as |
| 3978 | modified. Pressing the \kbd{Return} key passes the current line to |
| 3979 | the interpreter. \kbd{C-R} starts an incremental reverse search; |
| 3980 | \kbd{C-S} starts a forward search. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3981 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 3982 | \section{Key Bindings \label{keyBindings}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3983 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3984 | The key bindings and some other parameters of the Readline library can |
| 3985 | be customized by placing commands in an initialization file called |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 3986 | \file{\~{}/.inputrc}. Key bindings have the form |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3987 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3988 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3989 | key-name: function-name |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3990 | \end{verbatim} |
| 3991 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3992 | or |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3993 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3994 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3995 | "string": function-name |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 3996 | \end{verbatim} |
| 3997 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 3998 | and options can be set with |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3999 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4000 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4001 | set option-name value |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4002 | \end{verbatim} |
| 4003 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4004 | For example: |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4005 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4006 | \begin{verbatim} |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4007 | # I prefer vi-style editing: |
| 4008 | set editing-mode vi |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 4009 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4010 | # Edit using a single line: |
| 4011 | set horizontal-scroll-mode On |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 4012 | |
Guido van Rossum | 0245569 | 1997-07-17 16:21:52 +0000 | [diff] [blame] | 4013 | # Rebind some keys: |
| 4014 | Meta-h: backward-kill-word |
| 4015 | "\C-u": universal-argument |
| 4016 | "\C-x\C-r": re-read-init-file |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4017 | \end{verbatim} |
| 4018 | |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 4019 | Note that the default binding for \kbd{Tab} in Python is to insert a |
| 4020 | \kbd{Tab} character instead of Readline's default filename completion |
| 4021 | function. If you insist, you can override this by putting |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4022 | |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4023 | \begin{verbatim} |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 4024 | Tab: complete |
Fred Drake | 8842e86 | 1998-02-13 07:16:30 +0000 | [diff] [blame] | 4025 | \end{verbatim} |
| 4026 | |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 4027 | in your \file{\~{}/.inputrc}. (Of course, this makes it harder to |
| 4028 | type indented continuation lines.) |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4029 | |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 4030 | Automatic completion of variable and module names is optionally |
| 4031 | available. To enable it in the interpreter's interactive mode, add |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 4032 | the following to your startup file:\footnote{ |
| 4033 | Python will execute the contents of a file identified by the |
| 4034 | \envvar{PYTHONSTARTUP} environment variable when you start an |
| 4035 | interactive interpreter.} |
Fred Drake | 20082d9 | 2000-04-03 04:26:58 +0000 | [diff] [blame] | 4036 | \refstmodindex{rlcompleter}\refbimodindex{readline} |
Fred Drake | 7238988 | 1998-04-13 01:31:10 +0000 | [diff] [blame] | 4037 | |
| 4038 | \begin{verbatim} |
| 4039 | import rlcompleter, readline |
| 4040 | readline.parse_and_bind('tab: complete') |
| 4041 | \end{verbatim} |
| 4042 | |
| 4043 | This binds the TAB key to the completion function, so hitting the TAB |
| 4044 | key twice suggests completions; it looks at Python statement names, |
| 4045 | the current local variables, and the available module names. For |
| 4046 | dotted expressions such as \code{string.a}, it will evaluate the the |
| 4047 | expression up to the final \character{.} and then suggest completions |
| 4048 | from the attributes of the resulting object. Note that this may |
| 4049 | execute application-defined code if an object with a |
| 4050 | \method{__getattr__()} method is part of the expression. |
| 4051 | |
| 4052 | |
Fred Drake | b7833d3 | 1998-09-11 16:21:55 +0000 | [diff] [blame] | 4053 | \section{Commentary \label{commentary}} |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4054 | |
Fred Drake | 5443c49 | 2000-07-08 05:18:54 +0000 | [diff] [blame] | 4055 | This facility is an enormous step forward compared to earlier versions |
| 4056 | of the interpreter; however, some wishes are left: It would be nice if |
| 4057 | the proper indentation were suggested on continuation lines (the |
| 4058 | parser knows if an indent token is required next). The completion |
| 4059 | mechanism might use the interpreter's symbol table. A command to |
| 4060 | check (or even suggest) matching parentheses, quotes, etc., would also |
| 4061 | be useful. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 4062 | |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 4063 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 4064 | \end{document} |