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