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