Guido van Rossum | 3795378 | 1992-04-06 14:04:04 +0000 | [diff] [blame] | 1 | \documentstyle[twoside,11pt,myformat]{report} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3 | \title{Python Tutorial} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 4 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 5 | \input{boilerplate} |
Guido van Rossum | 83eb962 | 1993-11-23 16:28:45 +0000 | [diff] [blame] | 6 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 7 | \begin{document} |
| 8 | |
| 9 | \pagenumbering{roman} |
| 10 | |
| 11 | \maketitle |
| 12 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 13 | \input{copyright} |
| 14 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 15 | \begin{abstract} |
| 16 | |
| 17 | \noindent |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 18 | Python is a simple, yet powerful programming language that bridges the |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 19 | gap between C and shell programming, and is thus ideally suited for |
| 20 | ``throw-away programming'' |
| 21 | and rapid prototyping. Its syntax is put |
| 22 | together from constructs borrowed from a variety of other languages; |
| 23 | most prominent are influences from ABC, C, Modula-3 and Icon. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 24 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 25 | The Python interpreter is easily extended with new functions and data |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 26 | types implemented in C. Python is also suitable as an extension |
| 27 | language for highly customizable C applications such as editors or |
| 28 | window managers. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 29 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 30 | Python is available for various operating systems, amongst which |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 31 | several flavors of \UNIX{}, the Apple Macintosh, MS-DOS, Windows |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 32 | (3.1(1), '95 and NT flavors), OS/2, and others. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 33 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 34 | This tutorial introduces the reader informally to the basic concepts |
| 35 | and features of the Python language and system. It helps to have a |
| 36 | Python interpreter handy for hands-on experience, but as the examples |
| 37 | are self-contained, the tutorial can be read off-line as well. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 38 | |
Guido van Rossum | 481ae68 | 1991-11-25 17:28:03 +0000 | [diff] [blame] | 39 | For a description of standard objects and modules, see the {\em Python |
| 40 | Library Reference} document. The {\em Python Reference Manual} gives |
| 41 | a more formal definition of the language. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 42 | |
| 43 | \end{abstract} |
| 44 | |
| 45 | \pagebreak |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 46 | { |
| 47 | \parskip = 0mm |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 48 | \tableofcontents |
Guido van Rossum | cdc9355 | 1992-02-11 15:53:13 +0000 | [diff] [blame] | 49 | } |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 50 | |
| 51 | \pagebreak |
| 52 | |
| 53 | \pagenumbering{arabic} |
| 54 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 55 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 56 | \chapter{Whetting Your Appetite} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 57 | |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 58 | \section{Disclaimer} |
| 59 | |
| 60 | Now that there are several books out on Python, this tutorial has lost |
| 61 | its role as the only introduction to Python for most new users. It |
| 62 | takes time to keep a document like this up to date in the face of |
| 63 | additions to the language, and I simply don't have enough time to do a |
| 64 | good job. Therefore, this version of the tutorial is almost unchanged |
| 65 | since the previous release. This doesn't mean that the tutorial is |
| 66 | out of date --- all the examples still work exactly as before. There |
| 67 | are simply some new areas of the language that aren't covered. |
| 68 | |
| 69 | To make up for this, there are some chapters at the end cover |
| 70 | important changes in recent Python releases, and these are up to date |
| 71 | with the current release. |
| 72 | |
| 73 | \section{Introduction} |
| 74 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 75 | If you ever wrote a large shell script, you probably know this |
| 76 | feeling: you'd love to add yet another feature, but it's already so |
| 77 | slow, and so big, and so complicated; or the feature involves a system |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 78 | 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] | 79 | the problem at hand isn't serious enough to warrant rewriting the |
| 80 | script in C; perhaps because the problem requires variable-length |
| 81 | strings or other data types (like sorted lists of file names) that are |
| 82 | easy in the shell but lots of work to implement in C; or perhaps just |
| 83 | because you're not sufficiently familiar with C. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 84 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 85 | In such cases, Python may be just the language for you. Python is |
| 86 | simple to use, but it is a real programming language, offering much |
| 87 | more structure and support for large programs than the shell has. On |
| 88 | the other hand, it also offers much more error checking than C, and, |
| 89 | being a {\em very-high-level language}, it has high-level data types |
| 90 | built in, such as flexible arrays and dictionaries that would cost you |
| 91 | days to implement efficiently in C. Because of its more general data |
| 92 | types Python is applicable to a much larger problem domain than {\em |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 93 | Awk} or even {\em Perl}, yet many things are at least as easy in |
| 94 | Python as in those languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 95 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 96 | Python allows you to split up your program in modules that can be |
| 97 | 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] | 98 | standard modules that you can use as the basis of your programs --- or |
| 99 | as examples to start learning to program in Python. There are also |
| 100 | built-in modules that provide things like file I/O, system calls, |
| 101 | sockets, and even a generic interface to window systems (STDWIN). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 102 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 103 | Python is an interpreted language, which can save you considerable time |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 104 | during program development because no compilation and linking is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 105 | necessary. The interpreter can be used interactively, which makes it |
| 106 | easy to experiment with features of the language, to write throw-away |
| 107 | programs, or to test functions during bottom-up program development. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 108 | It is also a handy desk calculator. |
| 109 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 110 | Python allows writing very compact and readable programs. Programs |
| 111 | written in Python are typically much shorter than equivalent C |
| 112 | programs, for several reasons: |
| 113 | \begin{itemize} |
| 114 | \item |
| 115 | the high-level data types allow you to express complex operations in a |
| 116 | single statement; |
| 117 | \item |
| 118 | statement grouping is done by indentation instead of begin/end |
| 119 | brackets; |
| 120 | \item |
| 121 | no variable or argument declarations are necessary. |
| 122 | \end{itemize} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 123 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 124 | Python is {\em extensible}: if you know how to program in C it is easy |
| 125 | to add a new built-in |
| 126 | function or |
| 127 | module to the interpreter, either to |
| 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, |
| 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 | |
| 134 | By the way, the language is named after the BBC show ``Monty |
| 135 | Python's Flying Circus'' and has nothing to do with nasty reptiles... |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 136 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 137 | \section{Where From Here} |
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 | 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] | 140 | 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] | 141 | using it, you are invited here to do so. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 142 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 143 | In the next chapter, the mechanics of using the interpreter are |
| 144 | explained. This is rather mundane information, but essential for |
| 145 | trying out the examples shown later. |
| 146 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 147 | The rest of the tutorial introduces various features of the Python |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 148 | language and system though examples, beginning with simple |
| 149 | expressions, statements and data types, through functions and modules, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 150 | and finally touching upon advanced concepts like exceptions |
| 151 | and user-defined classes. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 152 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 153 | When you're through with the tutorial (or just getting bored), you |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 154 | should read the Library Reference, which gives complete (though terse) |
| 155 | reference material about built-in and standard types, functions and |
| 156 | modules that can save you a lot of time when writing Python programs. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 157 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 158 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 159 | \chapter{Using the Python Interpreter} |
| 160 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 161 | \section{Invoking the Interpreter} |
| 162 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 163 | The Python interpreter is usually installed as {\tt /usr/local/bin/python} |
| 164 | on those machines where it is available; putting {\tt /usr/local/bin} in |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 165 | 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] | 166 | typing the command |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 167 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 168 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 169 | python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 170 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 171 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 172 | to the shell. Since the choice of the directory where the interpreter |
| 173 | lives is an installation option, other places are possible; check with |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 174 | your local Python guru or system administrator. (E.g., {\tt |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 175 | /usr/local/python} is a popular alternative location.) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 176 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 177 | The interpreter operates somewhat like the \UNIX{} shell: when called |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 178 | with standard input connected to a tty device, it reads and executes |
| 179 | commands interactively; when called with a file name argument or with |
| 180 | a file as standard input, it reads and executes a {\em script} from |
| 181 | that file. |
| 182 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 183 | A third way of starting the interpreter is |
| 184 | ``{\tt python -c command [arg] ...}'', which |
| 185 | executes the statement(s) in {\tt command}, analogous to the shell's |
| 186 | {\tt -c} option. Since Python statements often contain spaces or other |
| 187 | characters that are special to the shell, it is best to quote {\tt |
| 188 | command} in its entirety with double quotes. |
| 189 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 190 | Note that there is a difference between ``{\tt python file}'' and |
| 191 | ``{\tt python $<$file}''. In the latter case, input requests from the |
Guido van Rossum | 573805a | 1992-03-06 10:56:03 +0000 | [diff] [blame] | 192 | program, such as calls to {\tt input()} and {\tt raw_input()}, are |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 193 | satisfied from {\em file}. Since this file has already been read |
| 194 | until the end by the parser before the program starts executing, the |
| 195 | program will encounter EOF immediately. In the former case (which is |
| 196 | usually what you want) they are satisfied from whatever file or device |
| 197 | is connected to standard input of the Python interpreter. |
| 198 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 199 | When a script file is used, it is sometimes useful to be able to run |
| 200 | the script and enter interactive mode afterwards. This can be done by |
| 201 | passing {\tt -i} before the script. (This does not work if the script |
| 202 | is read from standard input, for the same reason as explained in the |
| 203 | previous paragraph.) |
| 204 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 205 | \subsection{Argument Passing} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 206 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 207 | When known to the interpreter, the script name and additional |
| 208 | arguments thereafter are passed to the script in the variable {\tt |
| 209 | sys.argv}, which is a list of strings. Its length is at least one; |
| 210 | when no script and no arguments are given, {\tt sys.argv[0]} is an |
| 211 | empty string. When the script name is given as {\tt '-'} (meaning |
| 212 | standard input), {\tt sys.argv[0]} is set to {\tt '-'}. When {\tt -c |
| 213 | command} is used, {\tt sys.argv[0]} is set to {\tt '-c'}. Options |
| 214 | found after {\tt -c command} are not consumed by the Python |
| 215 | interpreter's option processing but left in {\tt sys.argv} for the |
| 216 | command to handle. |
| 217 | |
| 218 | \subsection{Interactive Mode} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 219 | |
Guido van Rossum | dd01080 | 1991-06-07 14:31:11 +0000 | [diff] [blame] | 220 | When commands are read from a tty, the interpreter is said to be in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 221 | {\em interactive\ mode}. In this mode it prompts for the next command |
| 222 | with the {\em primary\ prompt}, usually three greater-than signs ({\tt |
Guido van Rossum | a67dee3 | 1995-09-13 17:34:25 +0000 | [diff] [blame] | 223 | >>>}); for continuation lines it prompts with the |
| 224 | {\em secondary\ prompt}, |
Guido van Rossum | 34e1777 | 1996-06-10 19:44:49 +0000 | [diff] [blame] | 225 | by default three dots ({\tt ...}). Typing an EOF character |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 226 | (Control-D on \UNIX{}, Control-Z on DOS or Windows) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 227 | at the primary prompt causes the interpreter to exit with a zero exit |
| 228 | status. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 229 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 230 | The interpreter prints a welcome message stating its version number |
| 231 | and a copyright notice before printing the first prompt, e.g.: |
| 232 | |
| 233 | \bcode\begin{verbatim} |
| 234 | python |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 235 | Python 1.4 (Oct 25 1996) [GCC 2.7.2] |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 236 | Copyright 1991-1996 Stichting Mathematisch Centrum, Amsterdam |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 237 | >>> |
| 238 | \end{verbatim}\ecode |
| 239 | |
| 240 | \section{The Interpreter and its Environment} |
| 241 | |
| 242 | \subsection{Error Handling} |
| 243 | |
| 244 | When an error occurs, the interpreter prints an error |
| 245 | message and a stack trace. In interactive mode, it then returns to |
| 246 | the primary prompt; when input came from a file, it exits with a |
| 247 | nonzero exit status after printing |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 248 | the stack trace. (Exceptions handled by an {\tt except} clause in a |
| 249 | {\tt try} statement are not errors in this context.) Some errors are |
| 250 | unconditionally fatal and cause an exit with a nonzero exit; this |
| 251 | applies to internal inconsistencies and some cases of running out of |
| 252 | memory. All error messages are written to the standard error stream; |
| 253 | normal output from the executed commands is written to standard |
| 254 | output. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 255 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 256 | Typing the interrupt character (usually Control-C or DEL) to the |
| 257 | primary or secondary prompt cancels the input and returns to the |
| 258 | primary prompt.% |
| 259 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 260 | A problem with the GNU Readline package may prevent this. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 261 | } |
| 262 | Typing an interrupt while a command is executing raises the {\tt |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 263 | KeyboardInterrupt} exception, which may be handled by a {\tt try} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 264 | statement. |
| 265 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 266 | \subsection{The Module Search Path} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 267 | |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 268 | When a module named {\tt spam} is imported, the interpreter searches |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 269 | for a file named {\tt spam.py} in the current directory, |
| 270 | and then in the list of directories specified by |
| 271 | the environment variable {\tt PYTHONPATH}. This has the same syntax as |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 272 | the \UNIX{} shell variable {\tt PATH}, i.e., a list of colon-separated |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 273 | directory names. When {\tt PYTHONPATH} is not set, or when the file |
| 274 | is not found there, the search continues in an installation-dependent |
| 275 | default path, usually {\tt .:/usr/local/lib/python}. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 276 | |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 277 | Actually, modules are searched in the list of directories given by the |
| 278 | variable {\tt sys.path} which is initialized from the directory |
| 279 | containing the input script (or the current directory), {\tt |
| 280 | PYTHONPATH} and the installation-dependent default. This allows |
| 281 | Python programs that know what they're doing to modify or replace the |
| 282 | module search path. See the section on Standard Modules later. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 283 | |
| 284 | \subsection{``Compiled'' Python files} |
| 285 | |
| 286 | As an important speed-up of the start-up time for short programs that |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 287 | use a lot of standard modules, if a file called {\tt spam.pyc} exists |
| 288 | in the directory where {\tt spam.py} is found, this is assumed to |
| 289 | contain an already-``compiled'' version of the module {\tt spam}. The |
| 290 | modification time of the version of {\tt spam.py} used to create {\tt |
| 291 | spam.pyc} is recorded in {\tt spam.pyc}, and the file is ignored if |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 292 | these don't match. |
| 293 | |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 294 | Normally, you don't need to do anything to create the {\tt spam.pyc} file. |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 295 | Whenever {\tt spam.py} is successfully compiled, an attempt is made to |
| 296 | write the compiled version to {\tt spam.pyc}. It is not an error if |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 297 | this attempt fails; if for any reason the file is not written |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 298 | completely, the resulting {\tt spam.pyc} file will be recognized as |
Guido van Rossum | 34e1777 | 1996-06-10 19:44:49 +0000 | [diff] [blame] | 299 | invalid and thus ignored later. The contents of the {\tt spam.pyc} |
| 300 | file is platform independent, so a Python module directory can be |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 301 | shared by machines of different architectures. (Tip for experts: |
| 302 | the module {\tt compileall} creates {\tt .pyc} files for all modules.) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 303 | |
| 304 | \subsection{Executable Python scripts} |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 305 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 306 | On BSD'ish \UNIX{} systems, Python scripts can be made directly |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 307 | executable, like shell scripts, by putting the line |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 308 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 309 | \bcode\begin{verbatim} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 310 | #! /usr/local/bin/python |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 311 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 312 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 313 | (assuming that's the name of the interpreter) at the beginning of the |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 314 | script and giving the file an executable mode. The {\tt \#!} must be |
| 315 | the first two characters of the file. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 316 | |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 317 | \subsection{The Interactive Startup File} |
| 318 | |
| 319 | When you use Python interactively, it is frequently handy to have some |
| 320 | standard commands executed every time the interpreter is started. You |
| 321 | can do this by setting an environment variable named {\tt |
| 322 | PYTHONSTARTUP} to the name of a file containing your start-up |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 323 | commands. This is similar to the {\tt .profile} feature of the \UNIX{} |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 324 | shells. |
| 325 | |
| 326 | This file is only read in interactive sessions, not when Python reads |
| 327 | commands from a script, and not when {\tt /dev/tty} is given as the |
| 328 | explicit source of commands (which otherwise behaves like an |
| 329 | interactive session). It is executed in the same name space where |
| 330 | interactive commands are executed, so that objects that it defines or |
| 331 | imports can be used without qualification in the interactive session. |
Guido van Rossum | 7b3c8a1 | 1992-09-08 09:20:13 +0000 | [diff] [blame] | 332 | You can also change the prompts {\tt sys.ps1} and {\tt sys.ps2} in |
| 333 | this file. |
Guido van Rossum | 9a4e3fc | 1992-09-03 21:27:55 +0000 | [diff] [blame] | 334 | |
| 335 | If you want to read an additional start-up file from the current |
| 336 | directory, you can program this in the global start-up file, e.g. |
| 337 | \verb\execfile('.pythonrc')\. If you want to use the startup file |
| 338 | in a script, you must write this explicitly in the script, e.g. |
| 339 | \verb\import os;\ \verb\execfile(os.environ['PYTHONSTARTUP'])\. |
| 340 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 341 | \section{Interactive Input Editing and History Substitution} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 342 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 343 | Some versions of the Python interpreter support editing of the current |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 344 | input line and history substitution, similar to facilities found in |
| 345 | the Korn shell and the GNU Bash shell. This is implemented using the |
| 346 | {\em GNU\ Readline} library, which supports Emacs-style and vi-style |
| 347 | editing. This library has its own documentation which I won't |
| 348 | duplicate here; however, the basics are easily explained. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 349 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 350 | Perhaps the quickest check to see whether command line editing is |
| 351 | supported is typing Control-P to the first Python prompt you get. If |
| 352 | it beeps, you have command line editing. If nothing appears to |
| 353 | happen, or if \verb/^P/ is echoed, you can skip the rest of this |
| 354 | section. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 355 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 356 | \subsection{Line Editing} |
| 357 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 358 | If supported, input line editing is active whenever the interpreter |
| 359 | prints a primary or secondary prompt. The current line can be edited |
| 360 | using the conventional Emacs control characters. The most important |
| 361 | of these are: C-A (Control-A) moves the cursor to the beginning of the |
| 362 | line, C-E to the end, C-B moves it one position to the left, C-F to |
| 363 | the right. Backspace erases the character to the left of the cursor, |
| 364 | C-D the character to its right. C-K kills (erases) the rest of the |
| 365 | line to the right of the cursor, C-Y yanks back the last killed |
| 366 | string. C-underscore undoes the last change you made; it can be |
| 367 | repeated for cumulative effect. |
| 368 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 369 | \subsection{History Substitution} |
| 370 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 371 | History substitution works as follows. All non-empty input lines |
| 372 | issued are saved in a history buffer, and when a new prompt is given |
| 373 | you are positioned on a new line at the bottom of this buffer. C-P |
| 374 | moves one line up (back) in the history buffer, C-N moves one down. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 375 | Any line in the history buffer can be edited; an asterisk appears in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 376 | front of the prompt to mark a line as modified. Pressing the Return |
| 377 | key passes the current line to the interpreter. C-R starts an |
| 378 | incremental reverse search; C-S starts a forward search. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 379 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 380 | \subsection{Key Bindings} |
| 381 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 382 | The key bindings and some other parameters of the Readline library can |
| 383 | be customized by placing commands in an initialization file called |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 384 | {\tt \$HOME/.inputrc}. Key bindings have the form |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 385 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 386 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 387 | key-name: function-name |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 388 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 389 | % |
| 390 | or |
| 391 | |
| 392 | \bcode\begin{verbatim} |
| 393 | "string": function-name |
| 394 | \end{verbatim}\ecode |
| 395 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 396 | and options can be set with |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 397 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 398 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 399 | set option-name value |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 400 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 401 | % |
| 402 | For example: |
| 403 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 404 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 405 | # I prefer vi-style editing: |
| 406 | set editing-mode vi |
| 407 | # Edit using a single line: |
| 408 | set horizontal-scroll-mode On |
| 409 | # Rebind some keys: |
| 410 | Meta-h: backward-kill-word |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 411 | "\C-u": universal-argument |
| 412 | "\C-x\C-r": re-read-init-file |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 413 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 414 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 415 | Note that the default binding for TAB in Python is to insert a TAB |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 416 | instead of Readline's default filename completion function. If you |
| 417 | insist, you can override this by putting |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 418 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 419 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 420 | TAB: complete |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 421 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 422 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 423 | in your {\tt \$HOME/.inputrc}. (Of course, this makes it hard to type |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 424 | indented continuation lines...) |
| 425 | |
| 426 | \subsection{Commentary} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 427 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 428 | This facility is an enormous step forward compared to previous |
| 429 | versions of the interpreter; however, some wishes are left: It would |
| 430 | be nice if the proper indentation were suggested on continuation lines |
| 431 | (the parser knows if an indent token is required next). The |
| 432 | completion mechanism might use the interpreter's symbol table. A |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 433 | command to check (or even suggest) matching parentheses, quotes etc. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 434 | would also be useful. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 435 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 436 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 437 | \chapter{An Informal Introduction to Python} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 438 | |
| 439 | In the following examples, input and output are distinguished by the |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 440 | presence or absence of prompts ({\tt >>>} and {\tt ...}): to repeat |
| 441 | the example, you must type everything after the prompt, when the |
| 442 | prompt appears; lines that do not begin with a prompt are output from |
| 443 | the interpreter.% |
| 444 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 445 | I'd prefer to use different fonts to distinguish input |
| 446 | from output, but the amount of LaTeX hacking that would require |
| 447 | is currently beyond my ability. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 448 | } |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 449 | Note that a secondary prompt on a line by itself in an example means |
| 450 | 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] | 451 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 452 | \section{Using Python as a Calculator} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 453 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 454 | Let's try some simple Python commands. Start the interpreter and wait |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 455 | for the primary prompt, {\tt >>>}. (It shouldn't take long.) |
| 456 | |
| 457 | \subsection{Numbers} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 458 | |
| 459 | The interpreter acts as a simple calculator: you can type an |
| 460 | expression at it and it will write the value. Expression syntax is |
| 461 | straightforward: the operators {\tt +}, {\tt -}, {\tt *} and {\tt /} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 462 | 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] | 463 | can be used for grouping. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 464 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 465 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 466 | >>> 2+2 |
| 467 | 4 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 468 | >>> # This is a comment |
| 469 | ... 2+2 |
| 470 | 4 |
| 471 | >>> 2+2 # and a comment on the same line as code |
| 472 | 4 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 473 | >>> (50-5*6)/4 |
| 474 | 5 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 475 | >>> # Integer division returns the floor: |
| 476 | ... 7/3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 477 | 2 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 478 | >>> 7/-3 |
| 479 | -3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 480 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 481 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 482 | % |
| 483 | Like in C, the equal sign ({\tt =}) is used to assign a value to a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 484 | variable. The value of an assignment is not written: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 485 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 486 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 487 | >>> width = 20 |
| 488 | >>> height = 5*9 |
| 489 | >>> width * height |
| 490 | 900 |
| 491 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 492 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 493 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 494 | A value can be assigned to several variables simultaneously: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 495 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 496 | \bcode\begin{verbatim} |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 497 | >>> x = y = z = 0 # Zero x, y and z |
| 498 | >>> x |
| 499 | 0 |
| 500 | >>> y |
| 501 | 0 |
| 502 | >>> z |
| 503 | 0 |
| 504 | >>> |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 505 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 506 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 507 | There is full support for floating point; operators with mixed type |
| 508 | operands convert the integer operand to floating point: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 509 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 510 | \bcode\begin{verbatim} |
| 511 | >>> 4 * 2.5 / 3.3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 512 | 3.0303030303 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 513 | >>> 7.0 / 2 |
| 514 | 3.5 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 515 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 516 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 517 | |
| 518 | \subsection{Strings} |
| 519 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 520 | Besides numbers, Python can also manipulate strings, enclosed in |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 521 | single quotes or double quotes: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 522 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 523 | \bcode\begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 524 | >>> 'spam eggs' |
| 525 | 'spam eggs' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 526 | >>> 'doesn\'t' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 527 | "doesn't" |
| 528 | >>> "doesn't" |
| 529 | "doesn't" |
| 530 | >>> '"Yes," he said.' |
| 531 | '"Yes," he said.' |
| 532 | >>> "\"Yes,\" he said." |
| 533 | '"Yes," he said.' |
| 534 | >>> '"Isn\'t," she said.' |
| 535 | '"Isn\'t," she said.' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 536 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 537 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 538 | % |
| 539 | Strings are written the same way as they are typed for input: inside |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 540 | quotes and with quotes and other funny characters escaped by backslashes, |
| 541 | to show the precise value. The string is enclosed in double quotes if |
| 542 | the string contains a single quote and no double quotes, else it's |
| 543 | enclosed in single quotes. (The {\tt print} statement, described later, |
| 544 | can be used to write strings without quotes or escapes.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 545 | |
| 546 | Strings can be concatenated (glued together) with the {\tt +} |
| 547 | operator, and repeated with {\tt *}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 548 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 549 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 550 | >>> word = 'Help' + 'A' |
| 551 | >>> word |
| 552 | 'HelpA' |
| 553 | >>> '<' + word*5 + '>' |
| 554 | '<HelpAHelpAHelpAHelpAHelpA>' |
| 555 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 556 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 557 | % |
| 558 | Strings can be subscripted (indexed); like in C, the first character of |
| 559 | a string has subscript (index) 0. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 560 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 561 | There is no separate character type; a character is simply a string of |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 562 | size one. Like in Icon, substrings can be specified with the {\em |
| 563 | slice} notation: two indices separated by a colon. |
| 564 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 565 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 566 | >>> word[4] |
| 567 | 'A' |
| 568 | >>> word[0:2] |
| 569 | 'He' |
| 570 | >>> word[2:4] |
| 571 | 'lp' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 572 | >>> |
| 573 | \end{verbatim}\ecode |
| 574 | % |
| 575 | Slice indices have useful defaults; an omitted first index defaults to |
| 576 | zero, an omitted second index defaults to the size of the string being |
| 577 | sliced. |
| 578 | |
| 579 | \bcode\begin{verbatim} |
| 580 | >>> word[:2] # The first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 581 | 'He' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 582 | >>> word[2:] # All but the first two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 583 | 'lpA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 584 | >>> |
| 585 | \end{verbatim}\ecode |
| 586 | % |
| 587 | Here's a useful invariant of slice operations: \verb\s[:i] + s[i:]\ |
| 588 | equals \verb\s\. |
| 589 | |
| 590 | \bcode\begin{verbatim} |
| 591 | >>> word[:2] + word[2:] |
| 592 | 'HelpA' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 593 | >>> word[:3] + word[3:] |
| 594 | 'HelpA' |
| 595 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 596 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 597 | % |
| 598 | Degenerate slice indices are handled gracefully: an index that is too |
| 599 | large is replaced by the string size, an upper bound smaller than the |
| 600 | lower bound returns an empty string. |
| 601 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 602 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 603 | >>> word[1:100] |
| 604 | 'elpA' |
| 605 | >>> word[10:] |
| 606 | '' |
| 607 | >>> word[2:1] |
| 608 | '' |
| 609 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 610 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 611 | % |
| 612 | Indices may be negative numbers, to start counting from the right. |
| 613 | For example: |
| 614 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 615 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 616 | >>> word[-1] # The last character |
| 617 | 'A' |
| 618 | >>> word[-2] # The last-but-one character |
| 619 | 'p' |
| 620 | >>> word[-2:] # The last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 621 | 'pA' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 622 | >>> word[:-2] # All but the last two characters |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 623 | 'Hel' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 624 | >>> |
| 625 | \end{verbatim}\ecode |
| 626 | % |
| 627 | But note that -0 is really the same as 0, so it does not count from |
| 628 | the right! |
| 629 | |
| 630 | \bcode\begin{verbatim} |
| 631 | >>> word[-0] # (since -0 equals 0) |
| 632 | 'H' |
| 633 | >>> |
| 634 | \end{verbatim}\ecode |
| 635 | % |
| 636 | Out-of-range negative slice indices are truncated, but don't try this |
| 637 | for single-element (non-slice) indices: |
| 638 | |
| 639 | \bcode\begin{verbatim} |
| 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 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 646 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 647 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 648 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 649 | The best way to remember how slices work is to think of the indices as |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 650 | pointing {\em between} characters, with the left edge of the first |
| 651 | character numbered 0. Then the right edge of the last character of a |
| 652 | string of {\tt n} characters has index {\tt n}, for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 653 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 654 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 655 | +---+---+---+---+---+ |
| 656 | | H | e | l | p | A | |
| 657 | +---+---+---+---+---+ |
| 658 | 0 1 2 3 4 5 |
| 659 | -5 -4 -3 -2 -1 |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 660 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 661 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 662 | The first row of numbers gives the position of the indices 0...5 in |
| 663 | the string; the second row gives the corresponding negative indices. |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 664 | The slice from \verb\i\ to \verb\j\ consists of all characters between |
| 665 | the edges labeled \verb\i\ and \verb\j\, respectively. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 666 | |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 667 | For nonnegative indices, the length of a slice is the difference of |
| 668 | the indices, if both are within bounds, e.g., the length of |
| 669 | \verb\word[1:3]\ is 2. |
| 670 | |
| 671 | The built-in function {\tt len()} returns the length of a string: |
| 672 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 673 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 674 | >>> s = 'supercalifragilisticexpialidocious' |
| 675 | >>> len(s) |
| 676 | 34 |
| 677 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 678 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 679 | |
| 680 | \subsection{Lists} |
| 681 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 682 | Python knows a number of {\em compound} data types, used to group |
| 683 | together other values. The most versatile is the {\em list}, which |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 684 | can be written as a list of comma-separated values (items) between |
| 685 | square brackets. List items need not all have the same type. |
| 686 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 687 | \bcode\begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 688 | >>> a = ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 689 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 690 | ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 691 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 692 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 693 | % |
| 694 | Like string indices, list indices start at 0, and lists can be sliced, |
| 695 | concatenated and so on: |
| 696 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 697 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 698 | >>> a[0] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 699 | 'spam' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 700 | >>> a[3] |
| 701 | 1234 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 702 | >>> a[-2] |
| 703 | 100 |
| 704 | >>> a[1:-1] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 705 | ['eggs', 100] |
| 706 | >>> a[:2] + ['bacon', 2*2] |
| 707 | ['spam', 'eggs', 'bacon', 4] |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 708 | >>> 3*a[:3] + ['Boe!'] |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 709 | ['spam', 'eggs', 100, 'spam', 'eggs', 100, 'spam', 'eggs', 100, 'Boe!'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 710 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 711 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 712 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 713 | Unlike strings, which are {\em immutable}, it is possible to change |
| 714 | individual elements of a list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 715 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 716 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 717 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 718 | ['spam', 'eggs', 100, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 719 | >>> a[2] = a[2] + 23 |
| 720 | >>> a |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 721 | ['spam', 'eggs', 123, 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 722 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 723 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 724 | % |
| 725 | 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] | 726 | of the list: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 727 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 728 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 729 | >>> # Replace some items: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 730 | ... a[0:2] = [1, 12] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 731 | >>> a |
| 732 | [1, 12, 123, 1234] |
| 733 | >>> # Remove some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 734 | ... a[0:2] = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 735 | >>> a |
| 736 | [123, 1234] |
| 737 | >>> # Insert some: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 738 | ... a[1:1] = ['bletch', 'xyzzy'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 739 | >>> a |
| 740 | [123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 741 | >>> a[:0] = a # Insert (a copy of) itself at the beginning |
| 742 | >>> a |
| 743 | [123, 'bletch', 'xyzzy', 1234, 123, 'bletch', 'xyzzy', 1234] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 744 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 745 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 746 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 747 | The built-in function {\tt len()} also applies to lists: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 748 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 749 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 750 | >>> len(a) |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 751 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 752 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 753 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 754 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 755 | It is possible to nest lists (create lists containing other lists), |
| 756 | for example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 757 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 758 | \bcode\begin{verbatim} |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 759 | >>> q = [2, 3] |
| 760 | >>> p = [1, q, 4] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 761 | >>> len(p) |
| 762 | 3 |
| 763 | >>> p[1] |
| 764 | [2, 3] |
| 765 | >>> p[1][0] |
| 766 | 2 |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 767 | >>> p[1].append('xtra') # See section 5.1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 768 | >>> p |
| 769 | [1, [2, 3, 'xtra'], 4] |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 770 | >>> q |
| 771 | [2, 3, 'xtra'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 772 | >>> |
| 773 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 774 | % |
| 775 | Note that in the last example, {\tt p[1]} and {\tt q} really refer to |
| 776 | the same object! We'll come back to {\em object semantics} later. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 777 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 778 | \section{First Steps Towards Programming} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 779 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 780 | Of course, we can use Python for more complicated tasks than adding |
| 781 | two and two together. For instance, we can write an initial |
| 782 | subsequence of the {\em Fibonacci} series as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 783 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 784 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 785 | >>> # Fibonacci series: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 786 | ... # the sum of two elements defines the next |
| 787 | ... a, b = 0, 1 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 788 | >>> while b < 10: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 789 | ... print b |
| 790 | ... a, b = b, a+b |
| 791 | ... |
| 792 | 1 |
| 793 | 1 |
| 794 | 2 |
| 795 | 3 |
| 796 | 5 |
| 797 | 8 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 798 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 799 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 800 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 801 | This example introduces several new features. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 802 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 803 | \begin{itemize} |
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 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 806 | The first line contains a {\em multiple assignment}: the variables |
| 807 | {\tt a} and {\tt b} simultaneously get the new values 0 and 1. On the |
| 808 | last line this is used again, demonstrating that the expressions on |
| 809 | 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] | 810 | assignments take place. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 811 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 812 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 813 | The {\tt while} loop executes as long as the condition (here: {\tt b < |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 814 | 10}) remains true. In Python, like in C, any non-zero integer value is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 815 | true; zero is false. The condition may also be a string or list value, |
| 816 | in fact any sequence; anything with a non-zero length is true, empty |
| 817 | sequences are false. The test used in the example is a simple |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 818 | comparison. The standard comparison operators are written the same as |
| 819 | in C: {\tt <}, {\tt >}, {\tt ==}, {\tt <=}, {\tt >=} and {\tt !=}. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 820 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 821 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 822 | The {\em body} of the loop is {\em indented}: indentation is Python's |
| 823 | way of grouping statements. Python does not (yet!) provide an |
| 824 | intelligent input line editing facility, so you have to type a tab or |
| 825 | space(s) for each indented line. In practice you will prepare more |
| 826 | complicated input for Python with a text editor; most text editors have |
| 827 | an auto-indent facility. When a compound statement is entered |
| 828 | interactively, it must be followed by a blank line to indicate |
| 829 | completion (since the parser cannot guess when you have typed the last |
| 830 | line). |
| 831 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 832 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 833 | The {\tt print} statement writes the value of the expression(s) it is |
| 834 | given. It differs from just writing the expression you want to write |
| 835 | (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] | 836 | multiple expressions and strings. Strings are printed without quotes, |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 837 | and a space is inserted between items, so you can format things nicely, |
| 838 | like this: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 839 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 840 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 841 | >>> i = 256*256 |
| 842 | >>> print 'The value of i is', i |
| 843 | The value of i is 65536 |
| 844 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 845 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 846 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 847 | A trailing comma avoids the newline after the output: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 848 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 849 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 850 | >>> a, b = 0, 1 |
| 851 | >>> while b < 1000: |
| 852 | ... print b, |
| 853 | ... a, b = b, a+b |
| 854 | ... |
| 855 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 856 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 857 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 858 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 859 | Note that the interpreter inserts a newline before it prints the next |
| 860 | prompt if the last line was not completed. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 861 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 862 | \end{itemize} |
| 863 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 864 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 865 | \chapter{More Control Flow Tools} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 866 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 867 | Besides the {\tt while} statement just introduced, Python knows the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 868 | usual control flow statements known from other languages, with some |
| 869 | twists. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 870 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 871 | \section{If Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 872 | |
| 873 | Perhaps the most well-known statement type is the {\tt if} statement. |
| 874 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 875 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 876 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 877 | >>> if x < 0: |
| 878 | ... x = 0 |
| 879 | ... print 'Negative changed to zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 880 | ... elif x == 0: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 881 | ... print 'Zero' |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 882 | ... elif x == 1: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 883 | ... print 'Single' |
| 884 | ... else: |
| 885 | ... print 'More' |
| 886 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 887 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 888 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 889 | There can be zero or more {\tt elif} parts, and the {\tt else} part is |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 890 | optional. The keyword `{\tt elif}' is short for `{\tt else if}', and is |
| 891 | useful to avoid excessive indentation. An {\tt if...elif...elif...} |
| 892 | sequence is a substitute for the {\em switch} or {\em case} statements |
| 893 | found in other languages. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 894 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 895 | \section{For Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 896 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 897 | The {\tt for} statement in Python differs a bit from what you may be |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 898 | 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] | 899 | arithmetic progression of numbers (like in Pascal), or leaving the user |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 900 | completely free in the iteration test and step (as C), Python's {\tt |
| 901 | for} statement iterates over the items of any sequence (e.g., a list |
| 902 | or a string), in the order that they appear in the sequence. For |
| 903 | example (no pun intended): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 904 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 905 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 906 | >>> # Measure some strings: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 907 | ... a = ['cat', 'window', 'defenestrate'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 908 | >>> for x in a: |
| 909 | ... print x, len(x) |
| 910 | ... |
| 911 | cat 3 |
| 912 | window 6 |
| 913 | defenestrate 12 |
| 914 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 915 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 916 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 917 | It is not safe to modify the sequence being iterated over in the loop |
| 918 | (this can only happen for mutable sequence types, i.e., lists). If |
| 919 | you need to modify the list you are iterating over, e.g., duplicate |
| 920 | selected items, you must iterate over a copy. The slice notation |
| 921 | makes this particularly convenient: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 922 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 923 | \bcode\begin{verbatim} |
| 924 | >>> for x in a[:]: # make a slice copy of the entire list |
| 925 | ... if len(x) > 6: a.insert(0, x) |
| 926 | ... |
| 927 | >>> a |
| 928 | ['defenestrate', 'cat', 'window', 'defenestrate'] |
| 929 | >>> |
| 930 | \end{verbatim}\ecode |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 931 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 932 | \section{The {\tt range()} Function} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 933 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 934 | If you do need to iterate over a sequence of numbers, the built-in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 935 | function {\tt range()} comes in handy. It generates lists containing |
| 936 | arithmetic progressions, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 937 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 938 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 939 | >>> range(10) |
| 940 | [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] |
| 941 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 942 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 943 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 944 | The given end point is never part of the generated list; {\tt range(10)} |
| 945 | generates a list of 10 values, exactly the legal indices for items of a |
| 946 | sequence of length 10. It is possible to let the range start at another |
| 947 | number, or to specify a different increment (even negative): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 948 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 949 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 950 | >>> range(5, 10) |
| 951 | [5, 6, 7, 8, 9] |
| 952 | >>> range(0, 10, 3) |
| 953 | [0, 3, 6, 9] |
| 954 | >>> range(-10, -100, -30) |
| 955 | [-10, -40, -70] |
| 956 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 957 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 958 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 959 | To iterate over the indices of a sequence, combine {\tt range()} and |
| 960 | {\tt len()} as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 961 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 962 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 963 | >>> a = ['Mary', 'had', 'a', 'little', 'lamb'] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 964 | >>> for i in range(len(a)): |
| 965 | ... print i, a[i] |
| 966 | ... |
| 967 | 0 Mary |
| 968 | 1 had |
| 969 | 2 a |
| 970 | 3 little |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 971 | 4 lamb |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 972 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 973 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 974 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 975 | \section{Break and Continue Statements, and Else Clauses on Loops} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 976 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 977 | The {\tt break} statement, like in C, breaks out of the smallest |
| 978 | enclosing {\tt for} or {\tt while} loop. |
| 979 | |
| 980 | The {\tt continue} statement, also borrowed from C, continues with the |
| 981 | next iteration of the loop. |
| 982 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 983 | Loop statements may have an {\tt else} clause; it is executed when the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 984 | loop terminates through exhaustion of the list (with {\tt for}) or when |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 985 | the condition becomes false (with {\tt while}), but not when the loop is |
| 986 | terminated by a {\tt break} statement. This is exemplified by the |
Guido van Rossum | cfb45e4 | 1994-11-10 23:04:43 +0000 | [diff] [blame] | 987 | following loop, which searches for prime numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 988 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 989 | \bcode\begin{verbatim} |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 990 | >>> for n in range(2, 10): |
| 991 | ... for x in range(2, n): |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 992 | ... if n % x == 0: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 993 | ... print n, 'equals', x, '*', n/x |
| 994 | ... break |
| 995 | ... else: |
| 996 | ... print n, 'is a prime number' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 997 | ... |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 998 | 2 is a prime number |
| 999 | 3 is a prime number |
| 1000 | 4 equals 2 * 2 |
| 1001 | 5 is a prime number |
| 1002 | 6 equals 2 * 3 |
| 1003 | 7 is a prime number |
| 1004 | 8 equals 2 * 4 |
| 1005 | 9 equals 3 * 3 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1006 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1007 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1008 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1009 | \section{Pass Statements} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1010 | |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1011 | The {\tt pass} statement does nothing. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1012 | It can be used when a statement is required syntactically but the |
| 1013 | program requires no action. |
| 1014 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1015 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1016 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1017 | >>> while 1: |
| 1018 | ... pass # Busy-wait for keyboard interrupt |
| 1019 | ... |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1020 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1021 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1022 | \section{Defining 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 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1027 | \bcode\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 |
| 1029 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1030 | ... while b < n: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1031 | ... print b, |
| 1032 | ... a, b = b, a+b |
| 1033 | ... |
| 1034 | >>> # Now call the function we just defined: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1035 | ... fib(2000) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1036 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 1597 |
| 1037 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1038 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1039 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1040 | The keyword {\tt def} introduces a function {\em definition}. It must |
| 1041 | be followed by the function name and the parenthesized list of formal |
| 1042 | parameters. The statements that form the body of the function starts at |
| 1043 | the next line, indented by a tab stop. |
| 1044 | |
| 1045 | The {\em execution} of a function introduces a new symbol table used |
| 1046 | for the local variables of the function. More precisely, all variable |
| 1047 | assignments in a function store the value in the local symbol table; |
| 1048 | whereas |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1049 | variable references first look in the local symbol table, then |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1050 | in the global symbol table, and then in the table of built-in names. |
| 1051 | Thus, |
Guido van Rossum | cfb45e4 | 1994-11-10 23:04:43 +0000 | [diff] [blame] | 1052 | global variables cannot be directly assigned a value within a |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1053 | function (unless named in a {\tt global} statement), although |
| 1054 | they may be referenced. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1055 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1056 | The actual parameters (arguments) to a function call are introduced in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1057 | the local symbol table of the called function when it is called; thus, |
| 1058 | arguments are passed using {\em call\ by\ value}.% |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1059 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1060 | Actually, {\em call by object reference} would be a better |
| 1061 | description, since if a mutable object is passed, the caller |
| 1062 | will see any changes the callee makes to it (e.g., items |
| 1063 | inserted into a list). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1064 | } |
| 1065 | When a function calls another function, a new local symbol table is |
| 1066 | created for that call. |
| 1067 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1068 | A function definition introduces the function name in the |
| 1069 | current |
| 1070 | symbol table. The value |
| 1071 | of the function name |
| 1072 | has a type that is recognized by the interpreter as a user-defined |
| 1073 | function. This value can be assigned to another name which can then |
| 1074 | also be used as a function. This serves as a general renaming |
| 1075 | mechanism: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1076 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1077 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1078 | >>> fib |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1079 | <function object at 10042ed0> |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1080 | >>> f = fib |
| 1081 | >>> f(100) |
| 1082 | 1 1 2 3 5 8 13 21 34 55 89 |
| 1083 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1084 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1085 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1086 | You might object that {\tt fib} is not a function but a procedure. In |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1087 | 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] | 1088 | value. In fact, technically speaking, procedures do return a value, |
| 1089 | albeit a rather boring one. This value is called {\tt None} (it's a |
| 1090 | built-in name). Writing the value {\tt None} is normally suppressed by |
| 1091 | the interpreter if it would be the only value written. You can see it |
| 1092 | if you really want to: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1093 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1094 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1095 | >>> print fib(0) |
| 1096 | None |
| 1097 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1098 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +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 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1103 | \bcode\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 | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1105 | ... result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1106 | ... a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1107 | ... while b < n: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1108 | ... result.append(b) # see below |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1109 | ... a, b = b, a+b |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1110 | ... return result |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1111 | ... |
| 1112 | >>> f100 = fib2(100) # call it |
| 1113 | >>> f100 # write the result |
| 1114 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
| 1115 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1116 | \end{verbatim}\ecode |
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 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1123 | The {\tt return} statement returns with a value from a function. {\tt |
| 1124 | return} without an expression argument is used to return from the middle |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1125 | of a procedure (falling off the end also returns from a procedure), in |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1126 | which case the {\tt None} value is returned. |
| 1127 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1128 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1129 | The statement {\tt result.append(b)} calls a {\em method} of the list |
| 1130 | object {\tt result}. A method is a function that `belongs' to an |
| 1131 | object and is named {\tt obj.methodname}, where {\tt obj} is some |
| 1132 | object (this may be an expression), and {\tt methodname} is the name |
| 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 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1136 | own object types and methods, using {\em classes}, as discussed later |
| 1137 | in this tutorial.) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1138 | The method {\tt append} shown in the example, is defined for |
| 1139 | list objects; it adds a new element at the end of the list. In this |
| 1140 | example |
| 1141 | it is equivalent to {\tt result = result + [b]}, but more efficient. |
| 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 | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1145 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1146 | \chapter{Odds and Ends} |
| 1147 | |
| 1148 | This chapter describes some things you've learned about already in |
| 1149 | more detail, and adds some new things as well. |
| 1150 | |
| 1151 | \section{More on Lists} |
| 1152 | |
| 1153 | The list data type has some more methods. Here are all of the methods |
| 1154 | of lists objects: |
| 1155 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1156 | \begin{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1157 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1158 | \item[{\tt insert(i, x)}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1159 | Insert an item at a given position. The first argument is the index of |
| 1160 | the element before which to insert, so {\tt a.insert(0, x)} inserts at |
| 1161 | the front of the list, and {\tt a.insert(len(a), x)} is equivalent to |
| 1162 | {\tt a.append(x)}. |
| 1163 | |
| 1164 | \item[{\tt append(x)}] |
| 1165 | Equivalent to {\tt a.insert(len(a), x)}. |
| 1166 | |
| 1167 | \item[{\tt index(x)}] |
| 1168 | Return the index in the list of the first item whose value is {\tt x}. |
| 1169 | It is an error if there is no such item. |
| 1170 | |
| 1171 | \item[{\tt remove(x)}] |
| 1172 | Remove the first item from the list whose value is {\tt x}. |
| 1173 | It is an error if there is no such item. |
| 1174 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1175 | \item[{\tt sort()}] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1176 | Sort the items of the list, in place. |
| 1177 | |
| 1178 | \item[{\tt reverse()}] |
| 1179 | Reverse the elements of the list, in place. |
| 1180 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1181 | \item[{\tt count(x)}] |
| 1182 | Return the number of times {\tt x} appears in the list. |
| 1183 | |
Guido van Rossum | 7d9f8d7 | 1991-01-22 11:45:00 +0000 | [diff] [blame] | 1184 | \end{description} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1185 | |
| 1186 | An example that uses all list methods: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1187 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1188 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1189 | >>> a = [66.6, 333, 333, 1, 1234.5] |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1190 | >>> print a.count(333), a.count(66.6), a.count('x') |
| 1191 | 2 1 0 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1192 | >>> a.insert(2, -1) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1193 | >>> a.append(333) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1194 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1195 | [66.6, 333, -1, 333, 1, 1234.5, 333] |
| 1196 | >>> a.index(333) |
| 1197 | 1 |
| 1198 | >>> a.remove(333) |
| 1199 | >>> a |
| 1200 | [66.6, -1, 333, 1, 1234.5, 333] |
| 1201 | >>> a.reverse() |
| 1202 | >>> a |
| 1203 | [333, 1234.5, 1, 333, -1, 66.6] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1204 | >>> a.sort() |
| 1205 | >>> a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1206 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1207 | >>> |
| 1208 | \end{verbatim}\ecode |
| 1209 | |
| 1210 | \section{The {\tt del} statement} |
| 1211 | |
| 1212 | There is a way to remove an item from a list given its index instead |
| 1213 | of its value: the {\tt del} statement. This can also be used to |
| 1214 | remove slices from a list (which we did earlier by assignment of an |
| 1215 | empty list to the slice). For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1216 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1217 | \bcode\begin{verbatim} |
| 1218 | >>> a |
| 1219 | [-1, 1, 66.6, 333, 333, 1234.5] |
| 1220 | >>> del a[0] |
| 1221 | >>> a |
| 1222 | [1, 66.6, 333, 333, 1234.5] |
| 1223 | >>> del a[2:4] |
| 1224 | >>> a |
| 1225 | [1, 66.6, 1234.5] |
| 1226 | >>> |
| 1227 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1228 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1229 | {\tt del} can also be used to delete entire variables: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1230 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1231 | \bcode\begin{verbatim} |
| 1232 | >>> del a |
| 1233 | >>> |
| 1234 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1235 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1236 | Referencing the name {\tt a} hereafter is an error (at least until |
| 1237 | another value is assigned to it). We'll find other uses for {\tt del} |
| 1238 | later. |
| 1239 | |
| 1240 | \section{Tuples and Sequences} |
| 1241 | |
| 1242 | We saw that lists and strings have many common properties, e.g., |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1243 | indexing and slicing operations. They are two examples of {\em |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1244 | sequence} data types. Since Python is an evolving language, other |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1245 | sequence data types may be added. There is also another standard |
| 1246 | sequence data type: the {\em tuple}. |
| 1247 | |
| 1248 | A tuple consists of a number of values separated by commas, for |
| 1249 | instance: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1250 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1251 | \bcode\begin{verbatim} |
| 1252 | >>> t = 12345, 54321, 'hello!' |
| 1253 | >>> t[0] |
| 1254 | 12345 |
| 1255 | >>> t |
| 1256 | (12345, 54321, 'hello!') |
| 1257 | >>> # Tuples may be nested: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1258 | ... u = t, (1, 2, 3, 4, 5) |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1259 | >>> u |
| 1260 | ((12345, 54321, 'hello!'), (1, 2, 3, 4, 5)) |
| 1261 | >>> |
| 1262 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1263 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1264 | As you see, on output tuples are alway enclosed in parentheses, so |
| 1265 | that nested tuples are interpreted correctly; they may be input with |
| 1266 | or without surrounding parentheses, although often parentheses are |
| 1267 | necessary anyway (if the tuple is part of a larger expression). |
| 1268 | |
| 1269 | Tuples have many uses, e.g., (x, y) coordinate pairs, employee records |
| 1270 | from a database, etc. Tuples, like strings, are immutable: it is not |
| 1271 | possible to assign to the individual items of a tuple (you can |
| 1272 | simulate much of the same effect with slicing and concatenation, |
| 1273 | though). |
| 1274 | |
| 1275 | 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] | 1276 | items: the syntax has some extra quirks to accommodate these. Empty |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1277 | tuples are constructed by an empty pair of parentheses; a tuple with |
| 1278 | one item is constructed by following a value with a comma |
| 1279 | (it is not sufficient to enclose a single value in parentheses). |
| 1280 | Ugly, but effective. For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1281 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1282 | \bcode\begin{verbatim} |
| 1283 | >>> empty = () |
| 1284 | >>> singleton = 'hello', # <-- note trailing comma |
| 1285 | >>> len(empty) |
| 1286 | 0 |
| 1287 | >>> len(singleton) |
| 1288 | 1 |
| 1289 | >>> singleton |
| 1290 | ('hello',) |
| 1291 | >>> |
| 1292 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1293 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1294 | The statement {\tt t = 12345, 54321, 'hello!'} is an example of {\em |
| 1295 | tuple packing}: the values {\tt 12345}, {\tt 54321} and {\tt 'hello!'} |
| 1296 | are packed together in a tuple. The reverse operation is also |
| 1297 | possible, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1298 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1299 | \bcode\begin{verbatim} |
| 1300 | >>> x, y, z = t |
| 1301 | >>> |
| 1302 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1303 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1304 | This is called, appropriately enough, {\em tuple unpacking}. Tuple |
| 1305 | unpacking requires that the list of variables on the left has the same |
| 1306 | number of elements as the length of the tuple. Note that multiple |
| 1307 | assignment is really just a combination of tuple packing and tuple |
| 1308 | unpacking! |
| 1309 | |
| 1310 | Occasionally, the corresponding operation on lists is useful: {\em list |
| 1311 | unpacking}. This is supported by enclosing the list of variables in |
| 1312 | square brackets: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1313 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1314 | \bcode\begin{verbatim} |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1315 | >>> a = ['spam', 'eggs', 100, 1234] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1316 | >>> [a1, a2, a3, a4] = a |
| 1317 | >>> |
| 1318 | \end{verbatim}\ecode |
| 1319 | |
| 1320 | \section{Dictionaries} |
| 1321 | |
| 1322 | Another useful data type built into Python is the {\em dictionary}. |
| 1323 | Dictionaries are sometimes found in other languages as ``associative |
| 1324 | memories'' or ``associative arrays''. Unlike sequences, which are |
| 1325 | indexed by a range of numbers, dictionaries are indexed by {\em keys}, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1326 | which are strings (the use of non-string values as keys |
| 1327 | is supported, but beyond the scope of this tutorial). |
| 1328 | It is best to think of a dictionary as an unordered set of |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1329 | {\em key:value} pairs, with the requirement that the keys are unique |
| 1330 | (within one dictionary). |
| 1331 | A pair of braces creates an empty dictionary: \verb/{}/. |
| 1332 | Placing a comma-separated list of key:value pairs within the |
| 1333 | braces adds initial key:value pairs to the dictionary; this is also the |
| 1334 | way dictionaries are written on output. |
| 1335 | |
| 1336 | The main operations on a dictionary are storing a value with some key |
| 1337 | and extracting the value given the key. It is also possible to delete |
| 1338 | a key:value pair |
| 1339 | with {\tt del}. |
| 1340 | If you store using a key that is already in use, the old value |
| 1341 | 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] | 1342 | value using a non-existent key. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1343 | |
| 1344 | The {\tt keys()} method of a dictionary object returns a list of all the |
| 1345 | keys used in the dictionary, in random order (if you want it sorted, |
| 1346 | just apply the {\tt sort()} method to the list of keys). To check |
| 1347 | whether a single key is in the dictionary, use the \verb/has_key()/ |
| 1348 | method of the dictionary. |
| 1349 | |
| 1350 | Here is a small example using a dictionary: |
| 1351 | |
| 1352 | \bcode\begin{verbatim} |
| 1353 | >>> tel = {'jack': 4098, 'sape': 4139} |
| 1354 | >>> tel['guido'] = 4127 |
| 1355 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1356 | {'sape': 4139, 'guido': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1357 | >>> tel['jack'] |
| 1358 | 4098 |
| 1359 | >>> del tel['sape'] |
| 1360 | >>> tel['irv'] = 4127 |
| 1361 | >>> tel |
Guido van Rossum | 8f96f77 | 1991-11-12 15:45:03 +0000 | [diff] [blame] | 1362 | {'guido': 4127, 'irv': 4127, 'jack': 4098} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1363 | >>> tel.keys() |
| 1364 | ['guido', 'irv', 'jack'] |
| 1365 | >>> tel.has_key('guido') |
| 1366 | 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1367 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1368 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1369 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1370 | \section{More on Conditions} |
| 1371 | |
| 1372 | The conditions used in {\tt while} and {\tt if} statements above can |
| 1373 | contain other operators besides comparisons. |
| 1374 | |
| 1375 | The comparison operators {\tt in} and {\tt not in} check whether a value |
| 1376 | occurs (does not occur) in a sequence. The operators {\tt is} and {\tt |
| 1377 | is not} compare whether two objects are really the same object; this |
| 1378 | only matters for mutable objects like lists. All comparison operators |
| 1379 | have the same priority, which is lower than that of all numerical |
| 1380 | operators. |
| 1381 | |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1382 | Comparisons can be chained: e.g., {\tt a < b == c} tests whether {\tt a} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1383 | is less than {\tt b} and moreover {\tt b} equals {\tt c}. |
| 1384 | |
| 1385 | Comparisons may be combined by the Boolean operators {\tt and} and {\tt |
| 1386 | or}, and the outcome of a comparison (or of any other Boolean |
| 1387 | expression) may be negated with {\tt not}. These all have lower |
| 1388 | priorities than comparison operators again; between them, {\tt not} has |
| 1389 | the highest priority, and {\tt or} the lowest, so that |
| 1390 | {\tt A and not B or C} is equivalent to {\tt (A and (not B)) or C}. Of |
| 1391 | course, parentheses can be used to express the desired composition. |
| 1392 | |
| 1393 | The Boolean operators {\tt and} and {\tt or} are so-called {\em |
| 1394 | shortcut} operators: their arguments are evaluated from left to right, |
| 1395 | and evaluation stops as soon as the outcome is determined. E.g., if |
| 1396 | {\tt A} and {\tt C} are true but {\tt B} is false, {\tt A and B and C} |
| 1397 | does not evaluate the expression C. In general, the return value of a |
| 1398 | shortcut operator, when used as a general value and not as a Boolean, is |
| 1399 | the last evaluated argument. |
| 1400 | |
| 1401 | 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] | 1402 | expression to a variable. For example, |
| 1403 | |
| 1404 | \bcode\begin{verbatim} |
| 1405 | >>> string1, string2, string3 = '', 'Trondheim', 'Hammer Dance' |
| 1406 | >>> non_null = string1 or string2 or string3 |
| 1407 | >>> non_null |
| 1408 | 'Trondheim' |
| 1409 | >>> |
| 1410 | \end{verbatim}\ecode |
| 1411 | % |
| 1412 | Note that in Python, unlike C, assignment cannot occur inside expressions. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1413 | |
| 1414 | \section{Comparing Sequences and Other Types} |
| 1415 | |
| 1416 | Sequence objects may be compared to other objects with the same |
| 1417 | sequence type. The comparison uses {\em lexicographical} ordering: |
| 1418 | first the first two items are compared, and if they differ this |
| 1419 | determines the outcome of the comparison; if they are equal, the next |
| 1420 | two items are compared, and so on, until either sequence is exhausted. |
| 1421 | 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] | 1422 | the lexicographical comparison is carried out recursively. If all |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1423 | items of two sequences compare equal, the sequences are considered |
| 1424 | equal. If one sequence is an initial subsequence of the other, the |
| 1425 | shorted sequence is the smaller one. Lexicographical ordering for |
Guido van Rossum | 47b4c0f | 1995-03-15 11:25:32 +0000 | [diff] [blame] | 1426 | strings uses the \ASCII{} ordering for individual characters. Some |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1427 | examples of comparisons between sequences with the same types: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1428 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1429 | \bcode\begin{verbatim} |
| 1430 | (1, 2, 3) < (1, 2, 4) |
| 1431 | [1, 2, 3] < [1, 2, 4] |
| 1432 | 'ABC' < 'C' < 'Pascal' < 'Python' |
| 1433 | (1, 2, 3, 4) < (1, 2, 4) |
| 1434 | (1, 2) < (1, 2, -1) |
| 1435 | (1, 2, 3) = (1.0, 2.0, 3.0) |
| 1436 | (1, 2, ('aa', 'ab')) < (1, 2, ('abc', 'a'), 4) |
| 1437 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1438 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1439 | Note that comparing objects of different types is legal. The outcome |
| 1440 | is deterministic but arbitrary: the types are ordered by their name. |
| 1441 | Thus, a list is always smaller than a string, a string is always |
| 1442 | smaller than a tuple, etc. Mixed numeric types are compared according |
| 1443 | to their numeric value, so 0 equals 0.0, etc.% |
| 1444 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1445 | The rules for comparing objects of different types should |
| 1446 | not be relied upon; they may change in a future version of |
| 1447 | the language. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1448 | } |
| 1449 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1450 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1451 | \chapter{Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1452 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1453 | 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] | 1454 | definitions you have made (functions and variables) are lost. |
| 1455 | Therefore, if you want to write a somewhat longer program, you are |
| 1456 | 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] | 1457 | and running it with that file as input instead. This is known as creating a |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1458 | {\em script}. As your program gets longer, you may want to split it |
| 1459 | into several files for easier maintenance. You may also want to use a |
| 1460 | handy function that you've written in several programs without copying |
| 1461 | its definition into each program. |
| 1462 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1463 | 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] | 1464 | them in a script or in an interactive instance of the interpreter. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1465 | Such a file is called a {\em module}; definitions from a module can be |
| 1466 | {\em imported} into other modules or into the {\em main} module (the |
| 1467 | collection of variables that you have access to in a script |
| 1468 | executed at the top level |
| 1469 | and in calculator mode). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1470 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1471 | A module is a file containing Python definitions and statements. The |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1472 | file name is the module name with the suffix {\tt .py} appended. Within |
| 1473 | a module, the module's name (as a string) is available as the value of |
| 1474 | the global variable {\tt __name__}. For instance, use your favorite text |
| 1475 | editor to create a file called {\tt fibo.py} in the current directory |
| 1476 | with the following contents: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1477 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1478 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1479 | # Fibonacci numbers module |
| 1480 | |
| 1481 | def fib(n): # write Fibonacci series up to n |
| 1482 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1483 | while b < n: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1484 | print b, |
| 1485 | a, b = b, a+b |
| 1486 | |
| 1487 | def fib2(n): # return Fibonacci series up to n |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1488 | result = [] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1489 | a, b = 0, 1 |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 1490 | while b < n: |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1491 | result.append(b) |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1492 | a, b = b, a+b |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1493 | return result |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1494 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1495 | % |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1496 | Now enter the Python interpreter and import this module with the |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1497 | following command: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1498 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1499 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1500 | >>> import fibo |
| 1501 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1502 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1503 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1504 | This does not enter the names of the functions defined in |
| 1505 | {\tt fibo} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1506 | directly in the current symbol table; it only enters the module name |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1507 | {\tt fibo} |
| 1508 | there. |
| 1509 | Using the module name you can access the functions: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1510 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1511 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1512 | >>> fibo.fib(1000) |
| 1513 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 610 987 |
| 1514 | >>> fibo.fib2(100) |
| 1515 | [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89] |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1516 | >>> fibo.__name__ |
| 1517 | 'fibo' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1518 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1519 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1520 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1521 | 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] | 1522 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1523 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1524 | >>> fib = fibo.fib |
| 1525 | >>> fib(500) |
| 1526 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1527 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1528 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1529 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1530 | \section{More on Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1531 | |
| 1532 | A module can contain executable statements as well as function |
| 1533 | definitions. |
| 1534 | These statements are intended to initialize the module. |
| 1535 | They are executed only the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1536 | {\em first} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1537 | time the module is imported somewhere.% |
| 1538 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1539 | In fact function definitions are also `statements' that are |
| 1540 | `executed'; the execution enters the function name in the |
| 1541 | module's global symbol table. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1542 | } |
| 1543 | |
| 1544 | Each module has its own private symbol table, which is used as the |
| 1545 | global symbol table by all functions defined in the module. |
| 1546 | Thus, the author of a module can use global variables in the module |
| 1547 | without worrying about accidental clashes with a user's global |
| 1548 | variables. |
| 1549 | On the other hand, if you know what you are doing you can touch a |
| 1550 | module's global variables with the same notation used to refer to its |
| 1551 | functions, |
| 1552 | {\tt modname.itemname}. |
| 1553 | |
| 1554 | Modules can import other modules. |
| 1555 | It is customary but not required to place all |
| 1556 | {\tt import} |
| 1557 | statements at the beginning of a module (or script, for that matter). |
| 1558 | The imported module names are placed in the importing module's global |
| 1559 | symbol table. |
| 1560 | |
| 1561 | There is a variant of the |
| 1562 | {\tt import} |
| 1563 | statement that imports names from a module directly into the importing |
| 1564 | module's symbol table. |
| 1565 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1566 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1567 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1568 | >>> from fibo import fib, fib2 |
| 1569 | >>> fib(500) |
| 1570 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1571 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1572 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1573 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1574 | This does not introduce the module name from which the imports are taken |
| 1575 | in the local symbol table (so in the example, {\tt fibo} is not |
| 1576 | defined). |
| 1577 | |
| 1578 | 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] | 1579 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1580 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1581 | >>> from fibo import * |
| 1582 | >>> fib(500) |
| 1583 | 1 1 2 3 5 8 13 21 34 55 89 144 233 377 |
| 1584 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1585 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1586 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1587 | This imports all names except those beginning with an underscore |
Guido van Rossum | 573805a | 1992-03-06 10:56:03 +0000 | [diff] [blame] | 1588 | ({\tt _}). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1589 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1590 | \section{Standard Modules} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1591 | |
Guido van Rossum | 4410c75 | 1991-06-04 20:22:18 +0000 | [diff] [blame] | 1592 | Python comes with a library of standard modules, described in a separate |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1593 | document (Python Library Reference). Some modules are built into the |
| 1594 | interpreter; these provide access to operations that are not part of the |
| 1595 | core of the language but are nevertheless built in, either for |
| 1596 | efficiency or to provide access to operating system primitives such as |
| 1597 | system calls. The set of such modules is a configuration option; e.g., |
| 1598 | the {\tt amoeba} module is only provided on systems that somehow support |
| 1599 | Amoeba primitives. One particular module deserves some attention: {\tt |
| 1600 | sys}, which is built into every Python interpreter. The variables {\tt |
| 1601 | sys.ps1} and {\tt sys.ps2} define the strings used as primary and |
| 1602 | secondary prompts: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1603 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1604 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1605 | >>> import sys |
| 1606 | >>> sys.ps1 |
| 1607 | '>>> ' |
| 1608 | >>> sys.ps2 |
| 1609 | '... ' |
| 1610 | >>> sys.ps1 = 'C> ' |
| 1611 | C> print 'Yuck!' |
| 1612 | Yuck! |
| 1613 | C> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1614 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1615 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1616 | These two variables are only defined if the interpreter is in |
| 1617 | interactive mode. |
| 1618 | |
| 1619 | The variable |
| 1620 | {\tt sys.path} |
| 1621 | is a list of strings that determine the interpreter's search path for |
| 1622 | modules. |
| 1623 | It is initialized to a default path taken from the environment variable |
| 1624 | {\tt PYTHONPATH}, |
| 1625 | or from a built-in default if |
| 1626 | {\tt PYTHONPATH} |
| 1627 | is not set. |
| 1628 | You can modify it using standard list operations, e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1629 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1630 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1631 | >>> import sys |
| 1632 | >>> sys.path.append('/ufs/guido/lib/python') |
| 1633 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1634 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1635 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1636 | \section{The {\tt dir()} function} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1637 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1638 | The built-in function {\tt dir} is used to find out which names a module |
| 1639 | defines. It returns a sorted list of strings: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1640 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1641 | \bcode\begin{verbatim} |
| 1642 | >>> import fibo, sys |
| 1643 | >>> dir(fibo) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1644 | ['__name__', 'fib', 'fib2'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1645 | >>> dir(sys) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1646 | ['__name__', 'argv', 'builtin_module_names', 'copyright', 'exit', |
| 1647 | 'maxint', 'modules', 'path', 'ps1', 'ps2', 'setprofile', 'settrace', |
| 1648 | 'stderr', 'stdin', 'stdout', 'version'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1649 | >>> |
| 1650 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1651 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1652 | Without arguments, {\tt dir()} lists the names you have defined currently: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1653 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1654 | \bcode\begin{verbatim} |
| 1655 | >>> a = [1, 2, 3, 4, 5] |
| 1656 | >>> import fibo, sys |
| 1657 | >>> fib = fibo.fib |
| 1658 | >>> dir() |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1659 | ['__name__', 'a', 'fib', 'fibo', 'sys'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1660 | >>> |
| 1661 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1662 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1663 | 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] | 1664 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1665 | {\tt dir()} does not list the names of built-in functions and variables. |
| 1666 | If you want a list of those, they are defined in the standard module |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 1667 | {\tt __builtin__}: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1668 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1669 | \bcode\begin{verbatim} |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 1670 | >>> import __builtin__ |
| 1671 | >>> dir(__builtin__) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1672 | ['AccessError', 'AttributeError', 'ConflictError', 'EOFError', 'IOError', |
| 1673 | 'ImportError', 'IndexError', 'KeyError', 'KeyboardInterrupt', |
| 1674 | 'MemoryError', 'NameError', 'None', 'OverflowError', 'RuntimeError', |
| 1675 | 'SyntaxError', 'SystemError', 'SystemExit', 'TypeError', 'ValueError', |
| 1676 | 'ZeroDivisionError', '__name__', 'abs', 'apply', 'chr', 'cmp', 'coerce', |
| 1677 | 'compile', 'dir', 'divmod', 'eval', 'execfile', 'filter', 'float', |
| 1678 | 'getattr', 'hasattr', 'hash', 'hex', 'id', 'input', 'int', 'len', 'long', |
| 1679 | 'map', 'max', 'min', 'oct', 'open', 'ord', 'pow', 'range', 'raw_input', |
| 1680 | 'reduce', 'reload', 'repr', 'round', 'setattr', 'str', 'type', 'xrange'] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1681 | >>> |
| 1682 | \end{verbatim}\ecode |
| 1683 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1684 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1685 | \chapter{Output Formatting} |
| 1686 | |
| 1687 | So far we've encountered two ways of writing values: {\em expression |
| 1688 | statements} and the {\tt print} statement. (A third way is using the |
| 1689 | {\tt write} method of file objects; the standard output file can be |
| 1690 | referenced as {\tt sys.stdout}. See the Library Reference for more |
| 1691 | information on this.) |
| 1692 | |
| 1693 | Often you'll want more control over the formatting of your output than |
| 1694 | simply printing space-separated values. The key to nice formatting in |
| 1695 | Python is to do all the string handling yourself; using string slicing |
| 1696 | and concatenation operations you can create any lay-out you can imagine. |
| 1697 | The standard module {\tt string} contains some useful operations for |
| 1698 | padding strings to a given column width; these will be discussed shortly. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1699 | Finally, the \code{\%} operator (modulo) with a string left argument |
| 1700 | interprets this string as a C sprintf format string to be applied to the |
| 1701 | right argument, and returns the string resulting from this formatting |
| 1702 | operation. |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1703 | |
| 1704 | One question remains, of course: how do you convert values to strings? |
| 1705 | Luckily, Python has a way to convert any value to a string: just write |
| 1706 | the value between reverse quotes (\verb/``/). Some examples: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1707 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1708 | \bcode\begin{verbatim} |
| 1709 | >>> x = 10 * 3.14 |
| 1710 | >>> y = 200*200 |
| 1711 | >>> s = 'The value of x is ' + `x` + ', and y is ' + `y` + '...' |
| 1712 | >>> print s |
| 1713 | The value of x is 31.4, and y is 40000... |
| 1714 | >>> # Reverse quotes work on other types besides numbers: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1715 | ... p = [x, y] |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1716 | >>> ps = `p` |
| 1717 | >>> ps |
| 1718 | '[31.4, 40000]' |
| 1719 | >>> # Converting a string adds string quotes and backslashes: |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1720 | ... hello = 'hello, world\n' |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1721 | >>> hellos = `hello` |
| 1722 | >>> print hellos |
| 1723 | 'hello, world\012' |
| 1724 | >>> # The argument of reverse quotes may be a tuple: |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1725 | ... `x, y, ('spam', 'eggs')` |
| 1726 | "(31.4, 40000, ('spam', 'eggs'))" |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1727 | >>> |
| 1728 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1729 | % |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1730 | 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] | 1731 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1732 | \bcode\begin{verbatim} |
| 1733 | >>> import string |
| 1734 | >>> for x in range(1, 11): |
| 1735 | ... print string.rjust(`x`, 2), string.rjust(`x*x`, 3), |
| 1736 | ... # Note trailing comma on previous line |
| 1737 | ... print string.rjust(`x*x*x`, 4) |
| 1738 | ... |
| 1739 | 1 1 1 |
| 1740 | 2 4 8 |
| 1741 | 3 9 27 |
| 1742 | 4 16 64 |
| 1743 | 5 25 125 |
| 1744 | 6 36 216 |
| 1745 | 7 49 343 |
| 1746 | 8 64 512 |
| 1747 | 9 81 729 |
| 1748 | 10 100 1000 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1749 | >>> for x in range(1,11): |
| 1750 | ... print '%2d %3d %4d' % (x, x*x, x*x*x) |
| 1751 | ... |
| 1752 | 1 1 1 |
| 1753 | 2 4 8 |
| 1754 | 3 9 27 |
| 1755 | 4 16 64 |
| 1756 | 5 25 125 |
| 1757 | 6 36 216 |
| 1758 | 7 49 343 |
| 1759 | 8 64 512 |
| 1760 | 9 81 729 |
| 1761 | 10 100 1000 |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1762 | >>> |
| 1763 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1764 | % |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1765 | (Note that one space between each column was added by the way {\tt print} |
| 1766 | works: it always adds spaces between its arguments.) |
| 1767 | |
| 1768 | This example demonstrates the function {\tt string.rjust()}, which |
| 1769 | right-justifies a string in a field of a given width by padding it with |
| 1770 | spaces on the left. There are similar functions {\tt string.ljust()} |
| 1771 | and {\tt string.center()}. These functions do not write anything, they |
| 1772 | just return a new string. If the input string is too long, they don't |
| 1773 | truncate it, but return it unchanged; this will mess up your column |
| 1774 | lay-out but that's usually better than the alternative, which would be |
| 1775 | lying about a value. (If you really want truncation you can always add |
| 1776 | a slice operation, as in {\tt string.ljust(x,~n)[0:n]}.) |
| 1777 | |
| 1778 | There is another function, {\tt string.zfill}, which pads a numeric |
| 1779 | string on the left with zeros. It understands about plus and minus |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1780 | signs: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1781 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1782 | \bcode\begin{verbatim} |
| 1783 | >>> string.zfill('12', 5) |
| 1784 | '00012' |
| 1785 | >>> string.zfill('-3.14', 7) |
| 1786 | '-003.14' |
| 1787 | >>> string.zfill('3.14159265359', 5) |
| 1788 | '3.14159265359' |
| 1789 | >>> |
| 1790 | \end{verbatim}\ecode |
| 1791 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 1792 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1793 | \chapter{Errors and Exceptions} |
| 1794 | |
| 1795 | Until now error messages haven't been more than mentioned, but if you |
| 1796 | have tried out the examples you have probably seen some. There are |
| 1797 | (at least) two distinguishable kinds of errors: {\em syntax\ errors} |
| 1798 | and {\em exceptions}. |
| 1799 | |
| 1800 | \section{Syntax Errors} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1801 | |
| 1802 | 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] | 1803 | kind of complaint you get while you are still learning Python: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1804 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1805 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1806 | >>> while 1 print 'Hello world' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1807 | File "<stdin>", line 1 |
| 1808 | while 1 print 'Hello world' |
| 1809 | ^ |
| 1810 | SyntaxError: invalid syntax |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1811 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1812 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1813 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1814 | The parser repeats the offending line and displays a little `arrow' |
| 1815 | pointing at the earliest point in the line where the error was detected. |
| 1816 | The error is caused by (or at least detected at) the token |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1817 | {\em preceding} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1818 | the arrow: in the example, the error is detected at the keyword |
| 1819 | {\tt print}, since a colon ({\tt :}) is missing before it. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1820 | File name and line number are printed so you know where to look in case |
| 1821 | the input came from a script. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1822 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1823 | \section{Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1824 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1825 | Even if a statement or expression is syntactically correct, it may |
| 1826 | cause an error when an attempt is made to execute it. |
| 1827 | Errors detected during execution are called {\em exceptions} and are |
| 1828 | not unconditionally fatal: you will soon learn how to handle them in |
| 1829 | Python programs. Most exceptions are not handled by programs, |
| 1830 | however, and result in error messages as shown here: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1831 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1832 | \bcode\small\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1833 | >>> 10 * (1/0) |
Guido van Rossum | 3cbc16d | 1993-12-17 12:13:53 +0000 | [diff] [blame] | 1834 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1835 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1836 | ZeroDivisionError: integer division or modulo |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1837 | >>> 4 + spam*3 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1838 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1839 | File "<stdin>", line 1 |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1840 | NameError: spam |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1841 | >>> '2' + 2 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1842 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1843 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1844 | TypeError: illegal argument type for built-in operation |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1845 | >>> |
Fred Drake | fd255e4 | 1996-10-29 15:50:05 +0000 | [diff] [blame] | 1846 | \end{verbatim}\normalsize\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1847 | % |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1848 | The last line of the error message indicates what happened. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1849 | Exceptions come in different types, and the type is printed as part of |
| 1850 | the message: the types in the example are |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1851 | {\tt ZeroDivisionError}, |
| 1852 | {\tt NameError} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1853 | and |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1854 | {\tt TypeError}. |
| 1855 | The string printed as the exception type is the name of the built-in |
| 1856 | name for the exception that occurred. This is true for all built-in |
| 1857 | exceptions, but need not be true for user-defined exceptions (although |
| 1858 | it is a useful convention). |
| 1859 | Standard exception names are built-in identifiers (not reserved |
| 1860 | keywords). |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1861 | |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1862 | The rest of the line is a detail whose interpretation depends on the |
| 1863 | exception type; its meaning is dependent on the exception type. |
| 1864 | |
| 1865 | The preceding part of the error message shows the context where the |
| 1866 | exception happened, in the form of a stack backtrace. |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1867 | In general it contains a stack backtrace listing source lines; however, |
| 1868 | it will not display lines read from standard input. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1869 | |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 1870 | The Python Library Reference Manual lists the built-in exceptions and |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1871 | their meanings. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1872 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1873 | \section{Handling Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1874 | |
| 1875 | It is possible to write programs that handle selected exceptions. |
| 1876 | Look at the following example, which prints a table of inverses of |
| 1877 | some floating point numbers: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1878 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1879 | \bcode\begin{verbatim} |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1880 | >>> numbers = [0.3333, 2.5, 0, 10] |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1881 | >>> for x in numbers: |
| 1882 | ... print x, |
| 1883 | ... try: |
| 1884 | ... print 1.0 / x |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1885 | ... except ZeroDivisionError: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1886 | ... print '*** has no inverse ***' |
| 1887 | ... |
| 1888 | 0.3333 3.00030003 |
| 1889 | 2.5 0.4 |
| 1890 | 0 *** has no inverse *** |
| 1891 | 10 0.1 |
| 1892 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1893 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1894 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1895 | The {\tt try} statement works as follows. |
| 1896 | \begin{itemize} |
| 1897 | \item |
| 1898 | First, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1899 | {\em try\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1900 | (the statement(s) between the {\tt try} and {\tt except} keywords) is |
| 1901 | executed. |
| 1902 | \item |
| 1903 | If no exception occurs, the |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1904 | {\em except\ clause} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1905 | is skipped and execution of the {\tt try} statement is finished. |
| 1906 | \item |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1907 | If an exception occurs during execution of the try clause, |
| 1908 | the rest of the clause is skipped. Then if |
| 1909 | its type matches the exception named after the {\tt except} keyword, |
| 1910 | the rest of the try clause is skipped, the except clause is executed, |
| 1911 | and then execution continues after the {\tt try} statement. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1912 | \item |
| 1913 | If an exception occurs which does not match the exception named in the |
| 1914 | except clause, it is passed on to outer try statements; if no handler is |
| 1915 | found, it is an |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1916 | {\em unhandled\ exception} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1917 | and execution stops with a message as shown above. |
| 1918 | \end{itemize} |
| 1919 | A {\tt try} statement may have more than one except clause, to specify |
| 1920 | handlers for different exceptions. |
| 1921 | At most one handler will be executed. |
| 1922 | Handlers only handle exceptions that occur in the corresponding try |
| 1923 | clause, not in other handlers of the same {\tt try} statement. |
| 1924 | An except clause may name multiple exceptions as a parenthesized list, |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1925 | e.g.: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1926 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1927 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1928 | ... except (RuntimeError, TypeError, NameError): |
| 1929 | ... pass |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1930 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1931 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1932 | The last except clause may omit the exception name(s), to serve as a |
| 1933 | wildcard. |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1934 | Use this with extreme caution, since it is easy to mask a real |
| 1935 | programming error in this way! |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1936 | |
| 1937 | When an exception occurs, it may have an associated value, also known as |
| 1938 | the exceptions's |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1939 | {\em argument}. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1940 | The presence and type of the argument depend on the exception type. |
| 1941 | For exception types which have an argument, the except clause may |
| 1942 | specify a variable after the exception name (or list) to receive the |
| 1943 | argument's value, as follows: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1944 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1945 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1946 | >>> try: |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1947 | ... spam() |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1948 | ... except NameError, x: |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1949 | ... print 'name', x, 'undefined' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1950 | ... |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 1951 | name spam undefined |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1952 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1953 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1954 | % |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1955 | 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] | 1956 | (`detail') of the message for unhandled exceptions. |
| 1957 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1958 | Exception handlers don't just handle exceptions if they occur |
| 1959 | immediately in the try clause, but also if they occur inside functions |
| 1960 | that are called (even indirectly) in the try clause. |
| 1961 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1962 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1963 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1964 | >>> def this_fails(): |
| 1965 | ... x = 1/0 |
| 1966 | ... |
| 1967 | >>> try: |
| 1968 | ... this_fails() |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1969 | ... except ZeroDivisionError, detail: |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1970 | ... print 'Handling run-time error:', detail |
| 1971 | ... |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1972 | Handling run-time error: integer division or modulo |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1973 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1974 | \end{verbatim}\ecode |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1975 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1976 | \section{Raising Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1977 | |
| 1978 | The {\tt raise} statement allows the programmer to force a specified |
| 1979 | exception to occur. |
| 1980 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1981 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1982 | \bcode\begin{verbatim} |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1983 | >>> raise NameError, 'HiThere' |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 1984 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 1985 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 1986 | NameError: HiThere |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1987 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1988 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1989 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1990 | The first argument to {\tt raise} names the exception to be raised. |
| 1991 | The optional second argument specifies the exception's argument. |
| 1992 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 1993 | \section{User-defined Exceptions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 1994 | |
| 1995 | Programs may name their own exceptions by assigning a string to a |
| 1996 | variable. |
| 1997 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 1998 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 1999 | \bcode\begin{verbatim} |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2000 | >>> my_exc = 'my_exc' |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2001 | >>> try: |
| 2002 | ... raise my_exc, 2*2 |
| 2003 | ... except my_exc, val: |
Guido van Rossum | 67fa160 | 1991-04-23 14:14:57 +0000 | [diff] [blame] | 2004 | ... print 'My exception occurred, value:', val |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2005 | ... |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2006 | My exception occurred, value: 4 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2007 | >>> raise my_exc, 1 |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2008 | Traceback (innermost last): |
| 2009 | File "<stdin>", line 1 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2010 | my_exc: 1 |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2011 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2012 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2013 | % |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2014 | Many standard modules use this to report errors that may occur in |
| 2015 | functions they define. |
| 2016 | |
Guido van Rossum | 6fc178f | 1991-08-16 09:13:42 +0000 | [diff] [blame] | 2017 | \section{Defining Clean-up Actions} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2018 | |
| 2019 | The {\tt try} statement has another optional clause which is intended to |
| 2020 | define clean-up actions that must be executed under all circumstances. |
| 2021 | For example: |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2022 | |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2023 | \bcode\begin{verbatim} |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2024 | >>> try: |
| 2025 | ... raise KeyboardInterrupt |
| 2026 | ... finally: |
| 2027 | ... print 'Goodbye, world!' |
| 2028 | ... |
| 2029 | Goodbye, world! |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2030 | Traceback (innermost last): |
Guido van Rossum | 2292b8e | 1991-01-23 16:31:24 +0000 | [diff] [blame] | 2031 | File "<stdin>", line 2 |
Guido van Rossum | b2c6556 | 1993-05-12 08:53:36 +0000 | [diff] [blame] | 2032 | KeyboardInterrupt |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2033 | >>> |
Guido van Rossum | 5ce78f1 | 1991-01-25 13:27:18 +0000 | [diff] [blame] | 2034 | \end{verbatim}\ecode |
Guido van Rossum | a8d754e | 1992-01-07 16:44:35 +0000 | [diff] [blame] | 2035 | % |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 2036 | A {\tt finally} clause is executed whether or not an exception has |
| 2037 | occurred in the {\tt try} clause. When an exception has occurred, it |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2038 | is re-raised after the {\tt finally} clause is executed. The |
Guido van Rossum | da8c3fd | 1992-08-09 13:55:25 +0000 | [diff] [blame] | 2039 | {\tt finally} clause is also executed ``on the way out'' when the |
| 2040 | {\tt try} statement is left via a {\tt break} or {\tt return} |
| 2041 | statement. |
| 2042 | |
| 2043 | A {\tt try} statement must either have one or more {\tt except} |
| 2044 | clauses or one {\tt finally} clause, but not both. |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 2045 | |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2046 | |
| 2047 | \chapter{Classes} |
| 2048 | |
| 2049 | Python's class mechanism adds classes to the language with a minimum |
| 2050 | 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] | 2051 | 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] | 2052 | do not put an absolute barrier between definition and user, but rather |
| 2053 | rely on the politeness of the user not to ``break into the |
| 2054 | definition.'' The most important features of classes are retained |
| 2055 | with full power, however: the class inheritance mechanism allows |
| 2056 | multiple base classes, a derived class can override any methods of its |
| 2057 | base class(es), a method can call the method of a base class with the |
| 2058 | same name. Objects can contain an arbitrary amount of private data. |
| 2059 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2060 | In \Cpp{} terminology, all class members (including the data members) are |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2061 | {\em public}, and all member functions are {\em virtual}. There are |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2062 | 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] | 2063 | shorthands for referencing the object's members from its methods: the |
| 2064 | method function is declared with an explicit first argument |
| 2065 | representing the object, which is provided implicitly by the call. As |
| 2066 | in Smalltalk, classes themselves are objects, albeit in the wider |
| 2067 | 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] | 2068 | provides semantics for importing and renaming. But, just like in \Cpp{} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2069 | 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] | 2070 | 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] | 2071 | built-in operators with special syntax (arithmetic operators, |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2072 | subscripting etc.) can be redefined for class members. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2073 | |
| 2074 | |
| 2075 | \section{A word about terminology} |
| 2076 | |
| 2077 | Lacking universally accepted terminology to talk about classes, I'll |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2078 | make occasional use of Smalltalk and \Cpp{} terms. (I'd use Modula-3 |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2079 | terms, since its object-oriented semantics are closer to those of |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2080 | 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] | 2081 | |
| 2082 | I also have to warn you that there's a terminological pitfall for |
| 2083 | object-oriented readers: the word ``object'' in Python does not |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2084 | necessarily mean a class instance. Like \Cpp{} and Modula-3, and unlike |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2085 | Smalltalk, not all types in Python are classes: the basic built-in |
| 2086 | types like integers and lists aren't, and even somewhat more exotic |
| 2087 | types like files aren't. However, {\em all} Python types share a little |
| 2088 | bit of common semantics that is best described by using the word |
| 2089 | object. |
| 2090 | |
| 2091 | Objects have individuality, and multiple names (in multiple scopes) |
| 2092 | can be bound to the same object. This is known as aliasing in other |
| 2093 | languages. This is usually not appreciated on a first glance at |
| 2094 | Python, and can be safely ignored when dealing with immutable basic |
| 2095 | types (numbers, strings, tuples). However, aliasing has an |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2096 | (intended!) effect on the semantics of Python code involving mutable |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2097 | objects such as lists, dictionaries, and most types representing |
| 2098 | entities outside the program (files, windows, etc.). This is usually |
| 2099 | used to the benefit of the program, since aliases behave like pointers |
| 2100 | in some respects. For example, passing an object is cheap since only |
| 2101 | a pointer is passed by the implementation; and if a function modifies |
| 2102 | an object passed as an argument, the caller will see the change --- this |
| 2103 | obviates the need for two different argument passing mechanisms as in |
| 2104 | Pascal. |
| 2105 | |
| 2106 | |
| 2107 | \section{Python scopes and name spaces} |
| 2108 | |
| 2109 | Before introducing classes, I first have to tell you something about |
| 2110 | Python's scope rules. Class definitions play some neat tricks with |
| 2111 | name spaces, and you need to know how scopes and name spaces work to |
| 2112 | fully understand what's going on. Incidentally, knowledge about this |
| 2113 | subject is useful for any advanced Python programmer. |
| 2114 | |
| 2115 | Let's begin with some definitions. |
| 2116 | |
| 2117 | A {\em name space} is a mapping from names to objects. Most name |
| 2118 | spaces are currently implemented as Python dictionaries, but that's |
| 2119 | normally not noticeable in any way (except for performance), and it |
| 2120 | may change in the future. Examples of name spaces are: the set of |
| 2121 | built-in names (functions such as \verb\abs()\, and built-in exception |
| 2122 | names); the global names in a module; and the local names in a |
| 2123 | 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] | 2124 | 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] | 2125 | spaces is that there is absolutely no relation between names in |
| 2126 | different name spaces; for instance, two different modules may both |
| 2127 | define a function ``maximize'' without confusion --- users of the |
| 2128 | modules must prefix it with the module name. |
| 2129 | |
| 2130 | By the way, I use the word {\em attribute} for any name following a |
| 2131 | dot --- for example, in the expression \verb\z.real\, \verb\real\ is |
| 2132 | an attribute of the object \verb\z\. Strictly speaking, references to |
| 2133 | names in modules are attribute references: in the expression |
| 2134 | \verb\modname.funcname\, \verb\modname\ is a module object and |
| 2135 | \verb\funcname\ is an attribute of it. In this case there happens to |
| 2136 | be a straightforward mapping between the module's attributes and the |
| 2137 | global names defined in the module: they share the same name space!% |
| 2138 | \footnote{ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2139 | Except for one thing. Module objects have a secret read-only |
| 2140 | attribute called {\tt __dict__} which returns the dictionary |
| 2141 | used to implement the module's name space; the name |
| 2142 | {\tt __dict__} is an attribute but not a global name. |
| 2143 | Obviously, using this violates the abstraction of name space |
| 2144 | implementation, and should be restricted to things like |
| 2145 | post-mortem debuggers... |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2146 | } |
| 2147 | |
| 2148 | Attributes may be read-only or writable. In the latter case, |
| 2149 | assignment to attributes is possible. Module attributes are writable: |
| 2150 | you can write \verb\modname.the_answer = 42\. Writable attributes may |
| 2151 | also be deleted with the del statement, e.g. |
| 2152 | \verb\del modname.the_answer\. |
| 2153 | |
| 2154 | Name spaces are created at different moments and have different |
| 2155 | lifetimes. The name space containing the built-in names is created |
| 2156 | when the Python interpreter starts up, and is never deleted. The |
| 2157 | global name space for a module is created when the module definition |
| 2158 | is read in; normally, module name spaces also last until the |
| 2159 | interpreter quits. The statements executed by the top-level |
| 2160 | invocation of the interpreter, either read from a script file or |
| 2161 | interactively, are considered part of a module called \verb\__main__\, |
| 2162 | so they have their own global name space. (The built-in names |
Guido van Rossum | 4bd023f | 1993-10-27 13:49:20 +0000 | [diff] [blame] | 2163 | actually also live in a module; this is called \verb\__builtin__\.) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2164 | |
| 2165 | The local name space for a function is created when the function is |
| 2166 | called, and deleted when the function returns or raises an exception |
| 2167 | that is not handled within the function. (Actually, forgetting would |
| 2168 | be a better way to describe what actually happens.) Of course, |
| 2169 | recursive invocations each have their own local name space. |
| 2170 | |
| 2171 | A {\em scope} is a textual region of a Python program where a name space |
| 2172 | is directly accessible. ``Directly accessible'' here means that an |
| 2173 | unqualified reference to a name attempts to find the name in the name |
| 2174 | space. |
| 2175 | |
| 2176 | Although scopes are determined statically, they are used dynamically. |
| 2177 | At any time during execution, exactly three nested scopes are in use |
| 2178 | (i.e., exactly three name spaces are directly accessible): the |
| 2179 | innermost scope, which is searched first, contains the local names, |
| 2180 | the middle scope, searched next, contains the current module's global |
| 2181 | names, and the outermost scope (searched last) is the name space |
| 2182 | containing built-in names. |
| 2183 | |
| 2184 | Usually, the local scope references the local names of the (textually) |
Guido van Rossum | 96628a9 | 1995-04-10 11:34:00 +0000 | [diff] [blame] | 2185 | current function. Outside of functions, the local scope references |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2186 | the same name space as the global scope: the module's name space. |
| 2187 | Class definitions place yet another name space in the local scope. |
| 2188 | |
| 2189 | It is important to realize that scopes are determined textually: the |
| 2190 | global scope of a function defined in a module is that module's name |
| 2191 | space, no matter from where or by what alias the function is called. |
| 2192 | 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] | 2193 | run time --- however, the language definition is evolving towards |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2194 | static name resolution, at ``compile'' time, so don't rely on dynamic |
| 2195 | name resolution! (In fact, local variables are already determined |
| 2196 | statically.) |
| 2197 | |
| 2198 | A special quirk of Python is that assignments always go into the |
| 2199 | innermost scope. Assignments do not copy data --- they just |
| 2200 | bind names to objects. The same is true for deletions: the statement |
| 2201 | \verb\del x\ removes the binding of x from the name space referenced by the |
| 2202 | local scope. In fact, all operations that introduce new names use the |
| 2203 | local scope: in particular, import statements and function definitions |
| 2204 | bind the module or function name in the local scope. (The |
| 2205 | \verb\global\ statement can be used to indicate that particular |
| 2206 | variables live in the global scope.) |
| 2207 | |
| 2208 | |
| 2209 | \section{A first look at classes} |
| 2210 | |
| 2211 | Classes introduce a little bit of new syntax, three new object types, |
| 2212 | and some new semantics. |
| 2213 | |
| 2214 | |
| 2215 | \subsection{Class definition syntax} |
| 2216 | |
| 2217 | The simplest form of class definition looks like this: |
| 2218 | |
| 2219 | \begin{verbatim} |
| 2220 | class ClassName: |
| 2221 | <statement-1> |
| 2222 | . |
| 2223 | . |
| 2224 | . |
| 2225 | <statement-N> |
| 2226 | \end{verbatim} |
| 2227 | |
| 2228 | Class definitions, like function definitions (\verb\def\ statements) |
| 2229 | must be executed before they have any effect. (You could conceivably |
| 2230 | place a class definition in a branch of an \verb\if\ statement, or |
| 2231 | inside a function.) |
| 2232 | |
| 2233 | In practice, the statements inside a class definition will usually be |
| 2234 | function definitions, but other statements are allowed, and sometimes |
| 2235 | useful --- we'll come back to this later. The function definitions |
| 2236 | inside a class normally have a peculiar form of argument list, |
| 2237 | dictated by the calling conventions for methods --- again, this is |
| 2238 | explained later. |
| 2239 | |
| 2240 | When a class definition is entered, a new name space is created, and |
| 2241 | used as the local scope --- thus, all assignments to local variables |
| 2242 | go into this new name space. In particular, function definitions bind |
| 2243 | the name of the new function here. |
| 2244 | |
| 2245 | When a class definition is left normally (via the end), a {\em class |
| 2246 | object} is created. This is basically a wrapper around the contents |
| 2247 | of the name space created by the class definition; we'll learn more |
| 2248 | about class objects in the next section. The original local scope |
| 2249 | (the one in effect just before the class definitions was entered) is |
| 2250 | reinstated, and the class object is bound here to class name given in |
| 2251 | the class definition header (ClassName in the example). |
| 2252 | |
| 2253 | |
| 2254 | \subsection{Class objects} |
| 2255 | |
| 2256 | Class objects support two kinds of operations: attribute references |
| 2257 | and instantiation. |
| 2258 | |
| 2259 | {\em Attribute references} use the standard syntax used for all |
| 2260 | attribute references in Python: \verb\obj.name\. Valid attribute |
| 2261 | names are all the names that were in the class's name space when the |
| 2262 | class object was created. So, if the class definition looked like |
| 2263 | this: |
| 2264 | |
| 2265 | \begin{verbatim} |
| 2266 | class MyClass: |
| 2267 | i = 12345 |
| 2268 | def f(x): |
| 2269 | return 'hello world' |
| 2270 | \end{verbatim} |
| 2271 | |
| 2272 | then \verb\MyClass.i\ and \verb\MyClass.f\ are valid attribute |
| 2273 | references, returning an integer and a function object, respectively. |
| 2274 | Class attributes can also be assigned to, so you can change the |
| 2275 | value of \verb\MyClass.i\ by assignment. |
| 2276 | |
| 2277 | Class {\em instantiation} uses function notation. Just pretend that |
| 2278 | the class object is a parameterless function that returns a new |
| 2279 | instance of the class. For example, (assuming the above class): |
| 2280 | |
| 2281 | \begin{verbatim} |
| 2282 | x = MyClass() |
| 2283 | \end{verbatim} |
| 2284 | |
| 2285 | creates a new {\em instance} of the class and assigns this object to |
| 2286 | the local variable \verb\x\. |
| 2287 | |
| 2288 | |
| 2289 | \subsection{Instance objects} |
| 2290 | |
| 2291 | Now what can we do with instance objects? The only operations |
| 2292 | understood by instance objects are attribute references. There are |
| 2293 | two kinds of valid attribute names. |
| 2294 | |
| 2295 | The first I'll call {\em data attributes}. These correspond to |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2296 | ``instance variables'' in Smalltalk, and to ``data members'' in \Cpp{}. |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2297 | Data attributes need not be declared; like local variables, they |
| 2298 | spring into existence when they are first assigned to. For example, |
| 2299 | if \verb\x\ in the instance of \verb\MyClass\ created above, the |
| 2300 | following piece of code will print the value 16, without leaving a |
| 2301 | trace: |
| 2302 | |
| 2303 | \begin{verbatim} |
| 2304 | x.counter = 1 |
| 2305 | while x.counter < 10: |
| 2306 | x.counter = x.counter * 2 |
| 2307 | print x.counter |
| 2308 | del x.counter |
| 2309 | \end{verbatim} |
| 2310 | |
| 2311 | The second kind of attribute references understood by instance objects |
| 2312 | are {\em methods}. A method is a function that ``belongs to'' an |
| 2313 | object. (In Python, the term method is not unique to class instances: |
| 2314 | other object types can have methods as well, e.g., list objects have |
| 2315 | methods called append, insert, remove, sort, and so on. However, |
| 2316 | below, we'll use the term method exclusively to mean methods of class |
| 2317 | instance objects, unless explicitly stated otherwise.) |
| 2318 | |
| 2319 | Valid method names of an instance object depend on its class. By |
| 2320 | definition, all attributes of a class that are (user-defined) function |
| 2321 | objects define corresponding methods of its instances. So in our |
| 2322 | example, \verb\x.f\ is a valid method reference, since |
| 2323 | \verb\MyClass.f\ is a function, but \verb\x.i\ is not, since |
| 2324 | \verb\MyClass.i\ is not. But \verb\x.f\ is not the |
| 2325 | same thing as \verb\MyClass.f\ --- it is a {\em method object}, not a |
| 2326 | function object. |
| 2327 | |
| 2328 | |
| 2329 | \subsection{Method objects} |
| 2330 | |
| 2331 | Usually, a method is called immediately, e.g.: |
| 2332 | |
| 2333 | \begin{verbatim} |
| 2334 | x.f() |
| 2335 | \end{verbatim} |
| 2336 | |
| 2337 | In our example, this will return the string \verb\'hello world'\. |
| 2338 | However, it is not necessary to call a method right away: \verb\x.f\ |
| 2339 | is a method object, and can be stored away and called at a later |
| 2340 | moment, for example: |
| 2341 | |
| 2342 | \begin{verbatim} |
| 2343 | xf = x.f |
| 2344 | while 1: |
| 2345 | print xf() |
| 2346 | \end{verbatim} |
| 2347 | |
| 2348 | will continue to print \verb\hello world\ until the end of time. |
| 2349 | |
| 2350 | What exactly happens when a method is called? You may have noticed |
| 2351 | that \verb\x.f()\ was called without an argument above, even though |
| 2352 | the function definition for \verb\f\ specified an argument. What |
| 2353 | happened to the argument? Surely Python raises an exception when a |
| 2354 | function that requires an argument is called without any --- even if |
| 2355 | the argument isn't actually used... |
| 2356 | |
| 2357 | Actually, you may have guessed the answer: the special thing about |
| 2358 | methods is that the object is passed as the first argument of the |
| 2359 | function. In our example, the call \verb\x.f()\ is exactly equivalent |
| 2360 | to \verb\MyClass.f(x)\. In general, calling a method with a list of |
| 2361 | {\em n} arguments is equivalent to calling the corresponding function |
| 2362 | with an argument list that is created by inserting the method's object |
| 2363 | before the first argument. |
| 2364 | |
| 2365 | If you still don't understand how methods work, a look at the |
| 2366 | implementation can perhaps clarify matters. When an instance |
| 2367 | attribute is referenced that isn't a data attribute, its class is |
| 2368 | searched. If the name denotes a valid class attribute that is a |
| 2369 | function object, a method object is created by packing (pointers to) |
| 2370 | the instance object and the function object just found together in an |
| 2371 | abstract object: this is the method object. When the method object is |
| 2372 | called with an argument list, it is unpacked again, a new argument |
| 2373 | list is constructed from the instance object and the original argument |
| 2374 | list, and the function object is called with this new argument list. |
| 2375 | |
| 2376 | |
| 2377 | \section{Random remarks} |
| 2378 | |
| 2379 | |
| 2380 | [These should perhaps be placed more carefully...] |
| 2381 | |
| 2382 | |
| 2383 | Data attributes override method attributes with the same name; to |
| 2384 | avoid accidental name conflicts, which may cause hard-to-find bugs in |
| 2385 | large programs, it is wise to use some kind of convention that |
| 2386 | minimizes the chance of conflicts, e.g., capitalize method names, |
| 2387 | prefix data attribute names with a small unique string (perhaps just |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2388 | 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] | 2389 | |
| 2390 | |
| 2391 | Data attributes may be referenced by methods as well as by ordinary |
| 2392 | users (``clients'') of an object. In other words, classes are not |
| 2393 | usable to implement pure abstract data types. In fact, nothing in |
| 2394 | Python makes it possible to enforce data hiding --- it is all based |
| 2395 | upon convention. (On the other hand, the Python implementation, |
| 2396 | written in C, can completely hide implementation details and control |
| 2397 | access to an object if necessary; this can be used by extensions to |
| 2398 | Python written in C.) |
| 2399 | |
| 2400 | |
| 2401 | Clients should use data attributes with care --- clients may mess up |
| 2402 | invariants maintained by the methods by stamping on their data |
| 2403 | attributes. Note that clients may add data attributes of their own to |
| 2404 | an instance object without affecting the validity of the methods, as |
| 2405 | long as name conflicts are avoided --- again, a naming convention can |
| 2406 | save a lot of headaches here. |
| 2407 | |
| 2408 | |
| 2409 | There is no shorthand for referencing data attributes (or other |
| 2410 | methods!) from within methods. I find that this actually increases |
| 2411 | the readability of methods: there is no chance of confusing local |
| 2412 | variables and instance variables when glancing through a method. |
| 2413 | |
| 2414 | |
| 2415 | Conventionally, the first argument of methods is often called |
| 2416 | \verb\self\. This is nothing more than a convention: the name |
| 2417 | \verb\self\ has absolutely no special meaning to Python. (Note, |
| 2418 | however, that by not following the convention your code may be less |
| 2419 | readable by other Python programmers, and it is also conceivable that |
| 2420 | a {\em class browser} program be written which relies upon such a |
| 2421 | convention.) |
| 2422 | |
| 2423 | |
| 2424 | Any function object that is a class attribute defines a method for |
| 2425 | instances of that class. It is not necessary that the function |
| 2426 | definition is textually enclosed in the class definition: assigning a |
| 2427 | function object to a local variable in the class is also ok. For |
| 2428 | example: |
| 2429 | |
| 2430 | \begin{verbatim} |
| 2431 | # Function defined outside the class |
| 2432 | def f1(self, x, y): |
| 2433 | return min(x, x+y) |
| 2434 | |
| 2435 | class C: |
| 2436 | f = f1 |
| 2437 | def g(self): |
| 2438 | return 'hello world' |
| 2439 | h = g |
| 2440 | \end{verbatim} |
| 2441 | |
| 2442 | Now \verb\f\, \verb\g\ and \verb\h\ are all attributes of class |
| 2443 | \verb\C\ that refer to function objects, and consequently they are all |
| 2444 | methods of instances of \verb\C\ --- \verb\h\ being exactly equivalent |
| 2445 | to \verb\g\. Note that this practice usually only serves to confuse |
| 2446 | the reader of a program. |
| 2447 | |
| 2448 | |
| 2449 | Methods may call other methods by using method attributes of the |
| 2450 | \verb\self\ argument, e.g.: |
| 2451 | |
| 2452 | \begin{verbatim} |
| 2453 | class Bag: |
| 2454 | def empty(self): |
| 2455 | self.data = [] |
| 2456 | def add(self, x): |
| 2457 | self.data.append(x) |
| 2458 | def addtwice(self, x): |
Guido van Rossum | 084b0b2 | 1992-08-14 09:19:56 +0000 | [diff] [blame] | 2459 | self.add(x) |
| 2460 | self.add(x) |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2461 | \end{verbatim} |
| 2462 | |
| 2463 | |
| 2464 | The instantiation operation (``calling'' a class object) creates an |
| 2465 | 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] | 2466 | state. Therefore a class may define a special method named |
| 2467 | \verb\__init__\, like this: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2468 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2469 | \begin{verbatim} |
| 2470 | def __init__(self): |
| 2471 | self.empty() |
| 2472 | \end{verbatim} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2473 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2474 | When a class defines an \verb\__init__\ method, class instantiation |
| 2475 | automatically invokes \verb\__init__\ for the newly-created class |
| 2476 | instance. So in the \verb\Bag\ example, a new and initialized instance |
| 2477 | can be obtained by: |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2478 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2479 | \begin{verbatim} |
| 2480 | x = Bag() |
| 2481 | \end{verbatim} |
| 2482 | |
| 2483 | Of course, the \verb\__init__\ method may have arguments for greater |
| 2484 | flexibility. In that case, arguments given to the class instantiation |
| 2485 | operator are passed on to \verb\__init__\. For example, |
| 2486 | |
| 2487 | \bcode\begin{verbatim} |
| 2488 | >>> class Complex: |
| 2489 | ... def __init__(self, realpart, imagpart): |
| 2490 | ... self.r = realpart |
| 2491 | ... self.i = imagpart |
| 2492 | ... |
| 2493 | >>> x = Complex(3.0,-4.5) |
| 2494 | >>> x.r, x.i |
| 2495 | (3.0, -4.5) |
| 2496 | >>> |
| 2497 | \end{verbatim}\ecode |
| 2498 | % |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2499 | Methods may reference global names in the same way as ordinary |
| 2500 | functions. The global scope associated with a method is the module |
| 2501 | containing the class definition. (The class itself is never used as a |
| 2502 | global scope!) While one rarely encounters a good reason for using |
| 2503 | global data in a method, there are many legitimate uses of the global |
| 2504 | scope: for one thing, functions and modules imported into the global |
| 2505 | scope can be used by methods, as well as functions and classes defined |
| 2506 | in it. Usually, the class containing the method is itself defined in |
| 2507 | this global scope, and in the next section we'll find some good |
| 2508 | reasons why a method would want to reference its own class! |
| 2509 | |
| 2510 | |
| 2511 | \section{Inheritance} |
| 2512 | |
| 2513 | Of course, a language feature would not be worthy of the name ``class'' |
| 2514 | without supporting inheritance. The syntax for a derived class |
| 2515 | definition looks as follows: |
| 2516 | |
| 2517 | \begin{verbatim} |
| 2518 | class DerivedClassName(BaseClassName): |
| 2519 | <statement-1> |
| 2520 | . |
| 2521 | . |
| 2522 | . |
| 2523 | <statement-N> |
| 2524 | \end{verbatim} |
| 2525 | |
| 2526 | The name \verb\BaseClassName\ must be defined in a scope containing |
| 2527 | the derived class definition. Instead of a base class name, an |
| 2528 | expression is also allowed. This is useful when the base class is |
| 2529 | defined in another module, e.g., |
| 2530 | |
| 2531 | \begin{verbatim} |
| 2532 | class DerivedClassName(modname.BaseClassName): |
| 2533 | \end{verbatim} |
| 2534 | |
| 2535 | Execution of a derived class definition proceeds the same as for a |
| 2536 | base class. When the class object is constructed, the base class is |
| 2537 | remembered. This is used for resolving attribute references: if a |
| 2538 | requested attribute is not found in the class, it is searched in the |
| 2539 | base class. This rule is applied recursively if the base class itself |
| 2540 | is derived from some other class. |
| 2541 | |
| 2542 | There's nothing special about instantiation of derived classes: |
| 2543 | \verb\DerivedClassName()\ creates a new instance of the class. Method |
| 2544 | references are resolved as follows: the corresponding class attribute |
| 2545 | is searched, descending down the chain of base classes if necessary, |
| 2546 | and the method reference is valid if this yields a function object. |
| 2547 | |
| 2548 | Derived classes may override methods of their base classes. Because |
| 2549 | methods have no special privileges when calling other methods of the |
| 2550 | same object, a method of a base class that calls another method |
| 2551 | 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] | 2552 | a derived class that overrides it. (For \Cpp{} programmers: all methods |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2553 | in Python are ``virtual functions''.) |
| 2554 | |
| 2555 | An overriding method in a derived class may in fact want to extend |
| 2556 | rather than simply replace the base class method of the same name. |
| 2557 | There is a simple way to call the base class method directly: just |
| 2558 | call \verb\BaseClassName.methodname(self, arguments)\. This is |
| 2559 | occasionally useful to clients as well. (Note that this only works if |
| 2560 | the base class is defined or imported directly in the global scope.) |
| 2561 | |
| 2562 | |
| 2563 | \subsection{Multiple inheritance} |
| 2564 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2565 | Python supports a limited form of multiple inheritance as well. A |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2566 | class definition with multiple base classes looks as follows: |
| 2567 | |
| 2568 | \begin{verbatim} |
| 2569 | class DerivedClassName(Base1, Base2, Base3): |
| 2570 | <statement-1> |
| 2571 | . |
| 2572 | . |
| 2573 | . |
| 2574 | <statement-N> |
| 2575 | \end{verbatim} |
| 2576 | |
| 2577 | The only rule necessary to explain the semantics is the resolution |
| 2578 | rule used for class attribute references. This is depth-first, |
| 2579 | left-to-right. Thus, if an attribute is not found in |
| 2580 | \verb\DerivedClassName\, it is searched in \verb\Base1\, then |
| 2581 | (recursively) in the base classes of \verb\Base1\, and only if it is |
| 2582 | not found there, it is searched in \verb\Base2\, and so on. |
| 2583 | |
Guido van Rossum | 95cd2ef | 1992-12-08 14:37:55 +0000 | [diff] [blame] | 2584 | (To some people breadth first---searching \verb\Base2\ and |
| 2585 | \verb\Base3\ before the base classes of \verb\Base1\---looks more |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2586 | natural. However, this would require you to know whether a particular |
| 2587 | attribute of \verb\Base1\ is actually defined in \verb\Base1\ or in |
| 2588 | one of its base classes before you can figure out the consequences of |
| 2589 | a name conflict with an attribute of \verb\Base2\. The depth-first |
| 2590 | rule makes no differences between direct and inherited attributes of |
| 2591 | \verb\Base1\.) |
| 2592 | |
| 2593 | It is clear that indiscriminate use of multiple inheritance is a |
| 2594 | maintenance nightmare, given the reliance in Python on conventions to |
| 2595 | avoid accidental name conflicts. A well-known problem with multiple |
| 2596 | inheritance is a class derived from two classes that happen to have a |
| 2597 | common base class. While it is easy enough to figure out what happens |
| 2598 | in this case (the instance will have a single copy of ``instance |
| 2599 | variables'' or data attributes used by the common base class), it is |
| 2600 | not clear that these semantics are in any way useful. |
| 2601 | |
| 2602 | |
| 2603 | \section{Odds and ends} |
| 2604 | |
| 2605 | Sometimes it is useful to have a data type similar to the Pascal |
| 2606 | ``record'' or C ``struct'', bundling together a couple of named data |
| 2607 | items. An empty class definition will do nicely, e.g.: |
| 2608 | |
| 2609 | \begin{verbatim} |
| 2610 | class Employee: |
| 2611 | pass |
| 2612 | |
| 2613 | john = Employee() # Create an empty employee record |
| 2614 | |
| 2615 | # Fill the fields of the record |
| 2616 | john.name = 'John Doe' |
| 2617 | john.dept = 'computer lab' |
| 2618 | john.salary = 1000 |
| 2619 | \end{verbatim} |
| 2620 | |
| 2621 | |
| 2622 | A piece of Python code that expects a particular abstract data type |
| 2623 | can often be passed a class that emulates the methods of that data |
| 2624 | type instead. For instance, if you have a function that formats some |
| 2625 | data from a file object, you can define a class with methods |
| 2626 | \verb\read()\ and \verb\readline()\ that gets the data from a string |
| 2627 | buffer instead, and pass it as an argument. (Unfortunately, this |
| 2628 | technique has its limitations: a class can't define operations that |
| 2629 | are accessed by special syntax such as sequence subscripting or |
| 2630 | arithmetic operators, and assigning such a ``pseudo-file'' to |
| 2631 | \verb\sys.stdin\ will not cause the interpreter to read further input |
| 2632 | from it.) |
| 2633 | |
| 2634 | |
| 2635 | Instance method objects have attributes, too: \verb\m.im_self\ is the |
| 2636 | object of which the method is an instance, and \verb\m.im_func\ is the |
| 2637 | function object corresponding to the method. |
| 2638 | |
| 2639 | |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 2640 | \chapter{Recent Additions as of Release 1.1} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 2641 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2642 | Python is an evolving language. Since this tutorial was last |
| 2643 | thoroughly revised, several new features have been added to the |
| 2644 | language. While ideally I should revise the tutorial to incorporate |
| 2645 | them in the mainline of the text, lack of time currently requires me |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 2646 | to take a more modest approach. In this chapter I will briefly list the |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2647 | most important improvements to the language and how you can use them |
| 2648 | to your benefit. |
| 2649 | |
| 2650 | \section{The Last Printed Expression} |
| 2651 | |
| 2652 | In interactive mode, the last printed expression is assigned to the |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 2653 | variable \code{_}. This means that when you are using Python as a |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2654 | desk calculator, it is somewhat easier to continue calculations, for |
| 2655 | example: |
| 2656 | |
| 2657 | \begin{verbatim} |
| 2658 | >>> tax = 17.5 / 100 |
| 2659 | >>> price = 3.50 |
| 2660 | >>> price * tax |
| 2661 | 0.6125 |
| 2662 | >>> price + _ |
| 2663 | 4.1125 |
| 2664 | >>> round(_, 2) |
| 2665 | 4.11 |
| 2666 | >>> |
| 2667 | \end{verbatim} |
| 2668 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 2669 | For reasons too embarrassing to explain, this variable is implemented |
| 2670 | as a built-in (living in the module \code{__builtin__}), so it should |
| 2671 | be treated as read-only by the user. I.e. don't explicitly assign a |
| 2672 | value to it --- you would create an independent local variable with |
| 2673 | the same name masking the built-in variable with its magic behavior. |
| 2674 | |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2675 | \section{String Literals} |
| 2676 | |
| 2677 | \subsection{Double Quotes} |
| 2678 | |
| 2679 | Python can now also use double quotes to surround string literals, |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 2680 | e.g. \verb\"this doesn't hurt a bit"\. There is no semantic |
| 2681 | difference between strings surrounded by single or double quotes. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2682 | |
| 2683 | \subsection{Continuation Of String Literals} |
| 2684 | |
| 2685 | String literals can span multiple lines by escaping newlines with |
| 2686 | backslashes, e.g. |
| 2687 | |
| 2688 | \begin{verbatim} |
| 2689 | hello = "This is a rather long string containing\n\ |
| 2690 | several lines of text just as you would do in C.\n\ |
| 2691 | Note that whitespace at the beginning of the line is\ |
| 2692 | significant.\n" |
| 2693 | print hello |
| 2694 | \end{verbatim} |
| 2695 | |
| 2696 | which would print the following: |
| 2697 | \begin{verbatim} |
| 2698 | This is a rather long string containing |
| 2699 | several lines of text just as you would do in C. |
| 2700 | Note that whitespace at the beginning of the line is significant. |
| 2701 | \end{verbatim} |
| 2702 | |
| 2703 | \subsection{Triple-quoted strings} |
| 2704 | |
| 2705 | In some cases, when you need to include really long strings (e.g. |
| 2706 | containing several paragraphs of informational text), it is annoying |
| 2707 | that you have to terminate each line with \verb@\n\@, especially if |
| 2708 | you would like to reformat the text occasionally with a powerful text |
| 2709 | editor like Emacs. For such situations, ``triple-quoted'' strings can |
| 2710 | be used, e.g. |
| 2711 | |
| 2712 | \begin{verbatim} |
| 2713 | hello = """ |
| 2714 | |
| 2715 | This string is bounded by triple double quotes (3 times "). |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 2716 | Unescaped newlines in the string are retained, though \ |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2717 | it is still possible\nto use all normal escape sequences. |
| 2718 | |
| 2719 | Whitespace at the beginning of a line is |
| 2720 | significant. If you need to include three opening quotes |
| 2721 | you have to escape at least one of them, e.g. \""". |
| 2722 | |
| 2723 | This string ends in a newline. |
| 2724 | """ |
| 2725 | \end{verbatim} |
| 2726 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 2727 | Triple-quoted strings can be surrounded by three single quotes as |
| 2728 | well, again without semantic difference. |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2729 | |
| 2730 | \subsection{String Literal Juxtaposition} |
| 2731 | |
| 2732 | One final twist: you can juxtapose multiple string literals. Two or |
| 2733 | more adjacent string literals (but not arbitrary expressions!) |
| 2734 | separated only by whitespace will be concatenated (without intervening |
| 2735 | whitespace) into a single string object at compile time. This makes |
| 2736 | it possible to continue a long string on the next line without |
| 2737 | sacrificing indentation or performance, unlike the use of the string |
| 2738 | concatenation operator \verb\+\ or the continuation of the literal |
| 2739 | itself on the next line (since leading whitespace is significant |
| 2740 | inside all types of string literals). Note that this feature, like |
| 2741 | all string features except triple-quoted strings, is borrowed from |
| 2742 | Standard C. |
| 2743 | |
| 2744 | \section{The Formatting Operator} |
| 2745 | |
| 2746 | \subsection{Basic Usage} |
| 2747 | |
| 2748 | The chapter on output formatting is really out of date: there is now |
| 2749 | an almost complete interface to C-style printf formats. This is done |
| 2750 | by overloading the modulo operator (\verb\%\) for a left operand |
| 2751 | which is a string, e.g. |
| 2752 | |
| 2753 | \begin{verbatim} |
| 2754 | >>> import math |
| 2755 | >>> print 'The value of PI is approximately %5.3f.' % math.pi |
| 2756 | The value of PI is approximately 3.142. |
| 2757 | >>> |
| 2758 | \end{verbatim} |
| 2759 | |
| 2760 | If there is more than one format in the string you pass a tuple as |
| 2761 | right operand, e.g. |
| 2762 | |
| 2763 | \begin{verbatim} |
| 2764 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
| 2765 | >>> for name, phone in table.items(): |
| 2766 | ... print '%-10s ==> %10d' % (name, phone) |
| 2767 | ... |
| 2768 | Jack ==> 4098 |
| 2769 | Dcab ==> 8637678 |
| 2770 | Sjoerd ==> 4127 |
| 2771 | >>> |
| 2772 | \end{verbatim} |
| 2773 | |
| 2774 | Most formats work exactly as in C and require that you pass the proper |
| 2775 | type (however, if you don't you get an exception, not a core dump). |
| 2776 | The \verb\%s\ format is more relaxed: if the corresponding argument is |
| 2777 | not a string object, it is converted to string using the \verb\str()\ |
| 2778 | built-in function. Using \verb\*\ to pass the width or precision in |
| 2779 | as a separate (integer) argument is supported. The C formats |
| 2780 | \verb\%n\ and \verb\%p\ are not supported. |
| 2781 | |
| 2782 | \subsection{Referencing Variables By Name} |
| 2783 | |
| 2784 | If you have a really long format string that you don't want to split |
| 2785 | up, it would be nice if you could reference the variables to be |
| 2786 | formatted by name instead of by position. This can be done by using |
| 2787 | an extension of C formats using the form \verb\%(name)format\, e.g. |
| 2788 | |
| 2789 | \begin{verbatim} |
| 2790 | >>> table = {'Sjoerd': 4127, 'Jack': 4098, 'Dcab': 8637678} |
| 2791 | >>> print 'Jack: %(Jack)d; Sjoerd: %(Sjoerd)d; Dcab: %(Dcab)d' % table |
| 2792 | Jack: 4098; Sjoerd: 4127; Dcab: 8637678 |
| 2793 | >>> |
| 2794 | \end{verbatim} |
| 2795 | |
| 2796 | This is particularly useful in combination with the new built-in |
| 2797 | \verb\vars()\ function, which returns a dictionary containing all |
| 2798 | local variables. |
| 2799 | |
| 2800 | \section{Optional Function Arguments} |
| 2801 | |
| 2802 | It is now possible to define functions with a variable number of |
| 2803 | arguments. There are two forms, which can be combined. |
| 2804 | |
| 2805 | \subsection{Default Argument Values} |
| 2806 | |
| 2807 | The most useful form is to specify a default value for one or more |
| 2808 | arguments. This creates a function that can be called with fewer |
| 2809 | arguments than it is defined, e.g. |
| 2810 | |
| 2811 | \begin{verbatim} |
| 2812 | def ask_ok(prompt, retries = 4, complaint = 'Yes or no, please!'): |
| 2813 | while 1: |
| 2814 | ok = raw_input(prompt) |
| 2815 | if ok in ('y', 'ye', 'yes'): return 1 |
| 2816 | if ok in ('n', 'no', 'nop', 'nope'): return 0 |
| 2817 | retries = retries - 1 |
| 2818 | if retries < 0: raise IOError, 'refusenik user' |
| 2819 | print complaint |
| 2820 | \end{verbatim} |
| 2821 | |
| 2822 | This function can be called either like this: |
| 2823 | \verb\ask_ok('Do you really want to quit?')\ or like this: |
| 2824 | \verb\ask_ok('OK to overwrite the file?', 2)\. |
| 2825 | |
| 2826 | The default values are evaluated at the point of function definition |
| 2827 | in the {\em defining} scope, so that e.g. |
| 2828 | |
| 2829 | \begin{verbatim} |
| 2830 | i = 5 |
| 2831 | def f(arg = i): print arg |
| 2832 | i = 6 |
| 2833 | f() |
| 2834 | \end{verbatim} |
| 2835 | |
| 2836 | will print \verb\5\. |
| 2837 | |
| 2838 | \subsection{Arbitrary Argument Lists} |
| 2839 | |
| 2840 | It is also possible to specify that a function can be called with an |
| 2841 | arbitrary number of arguments. These arguments will be wrapped up in |
| 2842 | a tuple. Before the variable number of arguments, zero or more normal |
| 2843 | arguments may occur, e.g. |
| 2844 | |
| 2845 | \begin{verbatim} |
| 2846 | def fprintf(file, format, *args): |
| 2847 | file.write(format % args) |
| 2848 | \end{verbatim} |
| 2849 | |
| 2850 | This feature may be combined with the previous, e.g. |
| 2851 | |
| 2852 | \begin{verbatim} |
| 2853 | def but_is_it_useful(required, optional = None, *remains): |
| 2854 | print "I don't know" |
| 2855 | \end{verbatim} |
| 2856 | |
| 2857 | \section{Lambda And Functional Programming Tools} |
| 2858 | |
| 2859 | \subsection{Lambda Forms} |
| 2860 | |
Guido van Rossum | 16d6e71 | 1994-08-08 12:30:22 +0000 | [diff] [blame] | 2861 | By popular demand, a few features commonly found in functional |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2862 | programming languages and Lisp have been added to Python. With the |
| 2863 | \verb\lambda\ keyword, small anonymous functions can be created. |
| 2864 | Here's a function that returns the sum of its two arguments: |
| 2865 | \verb\lambda a, b: a+b\. Lambda forms can be used wherever function |
| 2866 | objects are required. They are syntactically restricted to a single |
| 2867 | expression. Semantically, they are just syntactic sugar for a normal |
| 2868 | function definition. Like nested function definitions, lambda forms |
| 2869 | cannot reference variables from the containing scope, but this can be |
| 2870 | overcome through the judicious use of default argument values, e.g. |
| 2871 | |
| 2872 | \begin{verbatim} |
| 2873 | def make_incrementor(n): |
Guido van Rossum | c1be9d5 | 1994-08-30 12:08:58 +0000 | [diff] [blame] | 2874 | return lambda x, incr=n: x+incr |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2875 | \end{verbatim} |
| 2876 | |
| 2877 | \subsection{Map, Reduce and Filter} |
| 2878 | |
| 2879 | Three new built-in functions on sequences are good candidate to pass |
| 2880 | lambda forms. |
| 2881 | |
| 2882 | \subsubsection{Map.} |
| 2883 | |
| 2884 | \verb\map(function, sequence)\ calls \verb\function(item)\ for each of |
| 2885 | the sequence's items and returns a list of the return values. For |
| 2886 | example, to compute some cubes: |
| 2887 | |
| 2888 | \begin{verbatim} |
| 2889 | >>> map(lambda x: x*x*x, range(1, 11)) |
| 2890 | [1, 8, 27, 64, 125, 216, 343, 512, 729, 1000] |
| 2891 | >>> |
| 2892 | \end{verbatim} |
| 2893 | |
| 2894 | More than one sequence may be passed; the function must then have as |
| 2895 | many arguments as there are sequences and is called with the |
| 2896 | corresponding item from each sequence (or \verb\None\ if some sequence |
| 2897 | is shorter than another). If \verb\None\ is passed for the function, |
| 2898 | a function returning its argument(s) is substituted. |
| 2899 | |
| 2900 | Combining these two special cases, we see that |
| 2901 | \verb\map(None, list1, list2)\ is a convenient way of turning a pair |
| 2902 | of lists into a list of pairs. For example: |
| 2903 | |
| 2904 | \begin{verbatim} |
| 2905 | >>> seq = range(8) |
| 2906 | >>> map(None, seq, map(lambda x: x*x, seq)) |
| 2907 | [(0, 0), (1, 1), (2, 4), (3, 9), (4, 16), (5, 25), (6, 36), (7, 49)] |
| 2908 | >>> |
| 2909 | \end{verbatim} |
| 2910 | |
| 2911 | \subsubsection{Filter.} |
| 2912 | |
| 2913 | \verb\filter(function, sequence)\ returns a sequence (of the same |
| 2914 | type, if possible) consisting of those items from the sequence for |
| 2915 | which \verb\function(item)\ is true. For example, to compute some |
| 2916 | primes: |
| 2917 | |
| 2918 | \begin{verbatim} |
| 2919 | >>> filter(lambda x: x%2 != 0 and x%3 != 0, range(2, 25)) |
| 2920 | [5, 7, 11, 13, 17, 19, 23] |
| 2921 | >>> |
| 2922 | \end{verbatim} |
| 2923 | |
| 2924 | \subsubsection{Reduce.} |
| 2925 | |
| 2926 | \verb\reduce(function, sequence)\ returns a single value constructed |
| 2927 | by calling the (binary) function on the first two items of the |
| 2928 | sequence, then on the result and the next item, and so on. For |
| 2929 | example, to compute the sum of the numbers 1 through 10: |
| 2930 | |
| 2931 | \begin{verbatim} |
| 2932 | >>> reduce(lambda x, y: x+y, range(1, 11)) |
| 2933 | 55 |
| 2934 | >>> |
| 2935 | \end{verbatim} |
| 2936 | |
| 2937 | If there's only one item in the sequence, its value is returned; if |
| 2938 | the sequence is empty, an exception is raised. |
| 2939 | |
| 2940 | A third argument can be passed to indicate the starting value. In this |
| 2941 | case the starting value is returned for an empty sequence, and the |
| 2942 | function is first applied to the starting value and the first sequence |
| 2943 | item, then to the result and the next item, and so on. For example, |
| 2944 | |
| 2945 | \begin{verbatim} |
| 2946 | >>> def sum(seq): |
| 2947 | ... return reduce(lambda x, y: x+y, seq, 0) |
| 2948 | ... |
| 2949 | >>> sum(range(1, 11)) |
| 2950 | 55 |
| 2951 | >>> sum([]) |
| 2952 | 0 |
| 2953 | >>> |
| 2954 | \end{verbatim} |
| 2955 | |
| 2956 | \section{Continuation Lines Without Backslashes} |
| 2957 | |
| 2958 | While the general mechanism for continuation of a source line on the |
| 2959 | next physical line remains to place a backslash on the end of the |
| 2960 | line, expressions inside matched parentheses (or square brackets, or |
| 2961 | curly braces) can now also be continued without using a backslash. |
| 2962 | This is particularly useful for calls to functions with many |
| 2963 | arguments, and for initializations of large tables. |
| 2964 | |
| 2965 | For example: |
| 2966 | |
| 2967 | \begin{verbatim} |
| 2968 | month_names = ['Januari', 'Februari', 'Maart', |
| 2969 | 'April', 'Mei', 'Juni', |
| 2970 | 'Juli', 'Augustus', 'September', |
| 2971 | 'Oktober', 'November', 'December'] |
| 2972 | \end{verbatim} |
| 2973 | |
| 2974 | and |
| 2975 | |
| 2976 | \begin{verbatim} |
| 2977 | CopyInternalHyperLinks(self.context.hyperlinks, |
| 2978 | copy.context.hyperlinks, |
| 2979 | uidremap) |
| 2980 | \end{verbatim} |
| 2981 | |
| 2982 | \section{Regular Expressions} |
| 2983 | |
| 2984 | While C's printf-style output formats, transformed into Python, are |
| 2985 | adequate for most output formatting jobs, C's scanf-style input |
| 2986 | formats are not very powerful. Instead of scanf-style input, Python |
| 2987 | offers Emacs-style regular expressions as a powerful input and |
| 2988 | scanning mechanism. Read the corresponding section in the Library |
| 2989 | Reference for a full description. |
| 2990 | |
| 2991 | \section{Generalized Dictionaries} |
| 2992 | |
Guido van Rossum | 8675115 | 1995-02-28 17:14:32 +0000 | [diff] [blame] | 2993 | The keys of dictionaries are no longer restricted to strings --- they |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 2994 | can be any immutable basic type including strings, numbers, tuples, or |
| 2995 | (certain) class instances. (Lists and dictionaries are not acceptable |
| 2996 | as dictionary keys, in order to avoid problems when the object used as |
| 2997 | a key is modified.) |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 2998 | |
| 2999 | Dictionaries have two new methods: \verb\d.values()\ returns a list of |
| 3000 | the dictionary's values, and \verb\d.items()\ returns a list of the |
| 3001 | dictionary's (key, value) pairs. Like \verb\d.keys()\, these |
| 3002 | operations are slow for large dictionaries. Examples: |
| 3003 | |
| 3004 | \begin{verbatim} |
| 3005 | >>> d = {100: 'honderd', 1000: 'duizend', 10: 'tien'} |
| 3006 | >>> d.keys() |
| 3007 | [100, 10, 1000] |
| 3008 | >>> d.values() |
| 3009 | ['honderd', 'tien', 'duizend'] |
| 3010 | >>> d.items() |
| 3011 | [(100, 'honderd'), (10, 'tien'), (1000, 'duizend')] |
| 3012 | >>> |
| 3013 | \end{verbatim} |
| 3014 | |
| 3015 | \section{Miscellaneous New Built-in Functions} |
| 3016 | |
| 3017 | The function \verb\vars()\ returns a dictionary containing the current |
Guido van Rossum | 16cd7f9 | 1994-10-06 10:29:26 +0000 | [diff] [blame] | 3018 | local variables. With a module argument, it returns that module's |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3019 | global variables. The old function \verb\dir(x)\ returns |
| 3020 | \verb\vars(x).keys()\. |
| 3021 | |
| 3022 | The function \verb\round(x)\ returns a floating point number rounded |
| 3023 | to the nearest integer (but still expressed as a floating point |
| 3024 | number). E.g. \verb\round(3.4) == 3.0\ and \verb\round(3.5) == 4.0\. |
| 3025 | With a second argument it rounds to the specified number of digits, |
| 3026 | e.g. \verb\round(math.pi, 4) == 3.1416\ or even |
| 3027 | \verb\round(123.4, -2) == 100.0\. |
| 3028 | |
| 3029 | The function \verb\hash(x)\ returns a hash value for an object. |
| 3030 | All object types acceptable as dictionary keys have a hash value (and |
| 3031 | it is this hash value that the dictionary implementation uses). |
| 3032 | |
| 3033 | The function \verb\id(x)\ return a unique identifier for an object. |
| 3034 | For two objects x and y, \verb\id(x) == id(y)\ if and only if |
| 3035 | \verb\x is y\. (In fact the object's address is used.) |
| 3036 | |
| 3037 | The function \verb\hasattr(x, name)\ returns whether an object has an |
| 3038 | attribute with the given name (a string value). The function |
| 3039 | \verb\getattr(x, name)\ returns the object's attribute with the given |
| 3040 | name. The function \verb\setattr(x, name, value)\ assigns a value to |
| 3041 | an object's attribute with the given name. These three functions are |
| 3042 | useful if the attribute names are not known beforehand. Note that |
Guido van Rossum | e5f8b60 | 1995-01-04 19:12:49 +0000 | [diff] [blame] | 3043 | \verb\getattr(x, 'spam')\ is equivalent to \verb\x.spam\, and |
| 3044 | \verb\setattr(x, 'spam', y)\ is equivalent to \verb\x.spam = y\. By |
Guido van Rossum | 6938f06 | 1994-08-01 12:22:53 +0000 | [diff] [blame] | 3045 | definition, \verb\hasattr(x, name)\ returns true if and only if |
| 3046 | \verb\getattr(x, name)\ returns without raising an exception. |
| 3047 | |
| 3048 | \section{Else Clause For Try Statement} |
| 3049 | |
| 3050 | The \verb\try...except\ statement now has an optional \verb\else\ |
| 3051 | clause, which must follow all \verb\except\ clauses. It is useful to |
| 3052 | place code that must be executed if the \verb\try\ clause does not |
| 3053 | raise an exception. For example: |
| 3054 | |
| 3055 | \begin{verbatim} |
| 3056 | for arg in sys.argv: |
| 3057 | try: |
| 3058 | f = open(arg, 'r') |
| 3059 | except IOError: |
| 3060 | print 'cannot open', arg |
| 3061 | else: |
| 3062 | print arg, 'has', len(f.readlines()), 'lines' |
| 3063 | f.close() |
| 3064 | \end{verbatim} |
Guido van Rossum | 5e0759d | 1992-08-07 16:06:24 +0000 | [diff] [blame] | 3065 | |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 3066 | |
| 3067 | \section{New Class Features in Release 1.1} |
| 3068 | |
Guido van Rossum | cfb45e4 | 1994-11-10 23:04:43 +0000 | [diff] [blame] | 3069 | Some changes have been made to classes: the operator overloading |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 3070 | mechanism is more flexible, providing more support for non-numeric use |
Guido van Rossum | 29766b2 | 1994-10-06 15:33:25 +0000 | [diff] [blame] | 3071 | of operators (including calling an object as if it were a function), |
| 3072 | and it is possible to trap attribute accesses. |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 3073 | |
| 3074 | \subsection{New Operator Overloading} |
| 3075 | |
| 3076 | It is no longer necessary to coerce both sides of an operator to the |
| 3077 | same class or type. A class may still provide a \code{__coerce__} |
| 3078 | method, but this method may return objects of different types or |
| 3079 | classes if it feels like it. If no \code{__coerce__} is defined, any |
| 3080 | argument type or class is acceptable. |
| 3081 | |
| 3082 | In order to make it possible to implement binary operators where the |
| 3083 | right-hand side is a class instance but the left-hand side is not, |
| 3084 | without using coercions, right-hand versions of all binary operators |
| 3085 | may be defined. These have an `r' prepended to their name, |
| 3086 | e.g. \code{__radd__}. |
| 3087 | |
| 3088 | For example, here's a very simple class for representing times. Times |
| 3089 | are initialized from a number of seconds (like time.time()). Times |
Guido van Rossum | 1133aec | 1995-03-15 11:34:18 +0000 | [diff] [blame] | 3090 | are printed like this: \code{Wed Mar 15 12:28:48 1995}. Subtracting |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 3091 | two Times gives their difference in seconds. Adding or subtracting a |
| 3092 | Time and a number gives a new Time. You can't add two times, nor can |
| 3093 | you subtract a Time from a number. |
| 3094 | |
| 3095 | \begin{verbatim} |
| 3096 | import time |
| 3097 | |
| 3098 | class Time: |
| 3099 | def __init__(self, seconds): |
| 3100 | self.seconds = seconds |
| 3101 | def __repr__(self): |
| 3102 | return time.ctime(self.seconds) |
| 3103 | def __add__(self, x): |
| 3104 | return Time(self.seconds + x) |
| 3105 | __radd__ = __add__ # support for x+t |
| 3106 | def __sub__(self, x): |
| 3107 | if hasattr(x, 'seconds'): # test if x could be a Time |
| 3108 | return self.seconds - x.seconds |
| 3109 | else: |
| 3110 | return self.seconds - x |
| 3111 | |
| 3112 | now = Time(time.time()) |
| 3113 | tomorrow = 24*3600 + now |
| 3114 | yesterday = now - today |
| 3115 | print tomorrow - yesterday # prints 172800 |
| 3116 | \end{verbatim} |
| 3117 | |
| 3118 | \subsection{Trapping Attribute Access} |
| 3119 | |
| 3120 | You can define three new ``magic'' methods in a class now: |
| 3121 | \code{__getattr__(self, name)}, \code{__setattr__(self, name, value)} |
| 3122 | and \code{__delattr__(self, name)}. |
| 3123 | |
| 3124 | The \code{__getattr__} method is called when an attribute access fails, |
Guido van Rossum | 8675115 | 1995-02-28 17:14:32 +0000 | [diff] [blame] | 3125 | i.e. when an attribute access would otherwise raise AttributeError --- |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 3126 | this is {\em after} the instance's dictionary and its class hierarchy |
| 3127 | have been searched for the named attribute. Note that if this method |
| 3128 | attempts to access any undefined instance attribute it will be called |
| 3129 | recursively! |
| 3130 | |
| 3131 | The \code{__setattr__} and \code{__delattr__} methods are called when |
| 3132 | assignment to, respectively deletion of an attribute are attempted. |
| 3133 | They are called {\em instead} of the normal action (which is to insert |
| 3134 | or delete the attribute in the instance dictionary). If either of |
| 3135 | these methods most set or delete any attribute, they can only do so by |
Guido van Rossum | 8675115 | 1995-02-28 17:14:32 +0000 | [diff] [blame] | 3136 | using the instance dictionary directly --- \code{self.__dict__} --- else |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 3137 | they would be called recursively. |
| 3138 | |
| 3139 | For example, here's a near-universal ``Wrapper'' class that passes all |
| 3140 | its attribute accesses to another object. Note how the |
| 3141 | \code{__init__} method inserts the wrapped object in |
| 3142 | \code{self.__dict__} in order to avoid endless recursion |
| 3143 | (\code{__setattr__} would call \code{__getattr__} which would call |
| 3144 | itself recursively). |
| 3145 | |
| 3146 | \begin{verbatim} |
| 3147 | class Wrapper: |
| 3148 | def __init__(self, wrapped): |
| 3149 | self.__dict__['wrapped'] = wrapped |
| 3150 | def __getattr__(self, name): |
| 3151 | return getattr(self.wrapped, name) |
| 3152 | def __setattr__(self, name, value): |
Guido van Rossum | cfb45e4 | 1994-11-10 23:04:43 +0000 | [diff] [blame] | 3153 | setattr(self.wrapped, name, value) |
Guido van Rossum | ca3f6c8 | 1994-10-06 14:08:53 +0000 | [diff] [blame] | 3154 | def __delattr__(self, name): |
| 3155 | delattr(self.wrapped, name) |
| 3156 | |
| 3157 | import sys |
| 3158 | f = Wrapper(sys.stdout) |
| 3159 | f.write('hello world\n') # prints 'hello world' |
| 3160 | \end{verbatim} |
| 3161 | |
Guido van Rossum | 29766b2 | 1994-10-06 15:33:25 +0000 | [diff] [blame] | 3162 | A simpler example of \code{__getattr__} is an attribute that is |
| 3163 | computed each time (or the first time) it it accessed. For instance: |
| 3164 | |
| 3165 | \begin{verbatim} |
| 3166 | from math import pi |
| 3167 | |
| 3168 | class Circle: |
| 3169 | def __init__(self, radius): |
| 3170 | self.radius = radius |
| 3171 | def __getattr__(self, name): |
| 3172 | if name == 'circumference': |
| 3173 | return 2 * pi * self.radius |
| 3174 | if name == 'diameter': |
| 3175 | return 2 * self.radius |
| 3176 | if name == 'area': |
| 3177 | return pi * pow(self.radius, 2) |
| 3178 | raise AttributeError, name |
| 3179 | \end{verbatim} |
| 3180 | |
| 3181 | \subsection{Calling a Class Instance} |
| 3182 | |
| 3183 | If a class defines a method \code{__call__} it is possible to call its |
| 3184 | instances as if they were functions. For example: |
| 3185 | |
| 3186 | \begin{verbatim} |
| 3187 | class PresetSomeArguments: |
| 3188 | def __init__(self, func, *args): |
| 3189 | self.func, self.args = func, args |
| 3190 | def __call__(self, *args): |
| 3191 | return apply(self.func, self.args + args) |
| 3192 | |
| 3193 | f = PresetSomeArguments(pow, 2) # f(i) computes powers of 2 |
| 3194 | for i in range(10): print f(i), # prints 1 2 4 8 16 32 64 128 256 512 |
| 3195 | print # append newline |
| 3196 | \end{verbatim} |
| 3197 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3198 | |
| 3199 | \chapter{New in Release 1.2} |
| 3200 | |
| 3201 | |
| 3202 | This chapter describes even more recent additions to the Python |
| 3203 | language and library. |
| 3204 | |
| 3205 | |
| 3206 | \section{New Class Features} |
| 3207 | |
| 3208 | The semantics of \code{__coerce__} have been changed to be more |
| 3209 | reasonable. As an example, the new standard module \code{Complex} |
| 3210 | implements fairly complete complex numbers using this. Additional |
| 3211 | examples of classes with and without \code{__coerce__} methods can be |
| 3212 | found in the \code{Demo/classes} subdirectory, modules \code{Rat} and |
| 3213 | \code{Dates}. |
| 3214 | |
| 3215 | If a class defines no \code{__coerce__} method, this is equivalent to |
| 3216 | the following definition: |
| 3217 | |
| 3218 | \begin{verbatim} |
| 3219 | def __coerce__(self, other): return self, other |
| 3220 | \end{verbatim} |
| 3221 | |
| 3222 | If \code{__coerce__} coerces itself to an object of a different type, |
| 3223 | the operation is carried out using that type --- in release 1.1, this |
| 3224 | would cause an error. |
| 3225 | |
| 3226 | Comparisons involving class instances now invoke \code{__coerce__} |
| 3227 | exactly as if \code{cmp(x, y)} were a binary operator like \code{+} |
| 3228 | (except if \code{x} and \code{y} are the same object). |
| 3229 | |
| 3230 | \section{Unix Signal Handling} |
| 3231 | |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 3232 | On \UNIX{}, Python now supports signal handling. The module |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3233 | \code{signal} exports functions \code{signal}, \code{pause} and |
Fred Drake | 6dc2aae | 1996-12-13 21:56:03 +0000 | [diff] [blame] | 3234 | \code{alarm}, which act similar to their \UNIX{} counterparts. The |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3235 | module also exports the conventional names for the various signal |
| 3236 | classes (also usable with \code{os.kill()}) and \code{SIG_IGN} and |
| 3237 | \code{SIG_DFL}. See the section on \code{signal} in the Library |
| 3238 | Reference Manual for more information. |
| 3239 | |
| 3240 | \section{Exceptions Can Be Classes} |
| 3241 | |
| 3242 | User-defined exceptions are no longer limited to being string objects |
| 3243 | --- they can be identified by classes as well. Using this mechanism it |
| 3244 | is possible to create extensible hierarchies of exceptions. |
| 3245 | |
| 3246 | There are two new valid (semantic) forms for the raise statement: |
| 3247 | |
| 3248 | \begin{verbatim} |
| 3249 | raise Class, instance |
| 3250 | |
| 3251 | raise instance |
| 3252 | \end{verbatim} |
| 3253 | |
| 3254 | In the first form, \code{instance} must be an instance of \code{Class} |
| 3255 | or of a class derived from it. The second form is a shorthand for |
| 3256 | |
| 3257 | \begin{verbatim} |
| 3258 | raise instance.__class__, instance |
| 3259 | \end{verbatim} |
| 3260 | |
| 3261 | An except clause may list classes as well as string objects. A class |
| 3262 | in an except clause is compatible with an exception if it is the same |
| 3263 | class or a base class thereof (but not the other way around --- an |
| 3264 | except clause listing a derived class is not compatible with a base |
| 3265 | class). For example, the following code will print B, C, D in that |
| 3266 | order: |
| 3267 | |
| 3268 | \begin{verbatim} |
| 3269 | class B: |
| 3270 | pass |
| 3271 | class C(B): |
| 3272 | pass |
| 3273 | class D(C): |
| 3274 | pass |
| 3275 | |
| 3276 | for c in [B, C, D]: |
| 3277 | try: |
| 3278 | raise c() |
| 3279 | except D: |
| 3280 | print "D" |
| 3281 | except C: |
| 3282 | print "C" |
| 3283 | except B: |
| 3284 | print "B" |
| 3285 | \end{verbatim} |
| 3286 | |
| 3287 | Note that if the except clauses were reversed (with ``\code{except B}'' |
| 3288 | first), it would have printed B, B, B --- the first matching except |
| 3289 | clause is triggered. |
| 3290 | |
| 3291 | When an error message is printed for an unhandled exception which is a |
| 3292 | class, the class name is printed, then a colon and a space, and |
| 3293 | finally the instance converted to a string using the built-in function |
| 3294 | \code{str()}. |
| 3295 | |
| 3296 | In this release, the built-in exceptions are still strings. |
| 3297 | |
| 3298 | |
| 3299 | \section{Object Persistency and Object Copying} |
| 3300 | |
| 3301 | Two new modules, \code{pickle} and \code{shelve}, support storage and |
| 3302 | retrieval of (almost) arbitrary Python objects on disk, using the |
| 3303 | \code{dbm} package. A third module, \code{copy}, provides flexible |
Guido van Rossum | bcc9582 | 1995-02-16 16:28:48 +0000 | [diff] [blame] | 3304 | object copying operations. More information on these modules is |
| 3305 | provided in the Library Reference Manual. |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3306 | |
| 3307 | \subsection{Persistent Objects} |
| 3308 | |
| 3309 | The module \code{pickle} provides a general framework for objects to |
| 3310 | disassemble themselves into a stream of bytes and to reassemble such a |
| 3311 | stream back into an object. It copes with reference sharing, |
| 3312 | recursive objects and instances of user-defined classes, but not |
| 3313 | (directly) with objects that have ``magical'' links into the operating |
| 3314 | system such as open files, sockets or windows. |
| 3315 | |
| 3316 | The \code{pickle} module defines a simple protocol whereby |
| 3317 | user-defined classes can control how they are disassembled and |
| 3318 | assembled. The method \code{__getinitargs__()}, if defined, returns |
| 3319 | the argument list for the constructor to be used at assembly time (by |
| 3320 | default the constructor is called without arguments). The methods |
| 3321 | \code{__getstate__()} and \code{__setstate__()} are used to pass |
| 3322 | additional state from disassembly to assembly; by default the |
| 3323 | instance's \code{__dict__} is passed and restored. |
| 3324 | |
| 3325 | Note that \code{pickle} does not open or close any files --- it can be |
| 3326 | used equally well for moving objects around on a network or store them |
| 3327 | in a database. For ease of debugging, and the inevitable occasional |
| 3328 | manual patch-up, the constructed byte streams consist of printable |
Guido van Rossum | 47b4c0f | 1995-03-15 11:25:32 +0000 | [diff] [blame] | 3329 | \ASCII{} characters only (though it's not designed to be pretty). |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3330 | |
| 3331 | The module \code{shelve} provides a simple model for storing objects |
| 3332 | on files. The operation \code{shelve.open(filename)} returns a |
| 3333 | ``shelf'', which is a simple persistent database with a |
| 3334 | dictionary-like interface. Database keys are strings, objects stored |
| 3335 | in the database can be anything that \code{pickle} will handle. |
| 3336 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3337 | \subsection{Copying Objects} |
| 3338 | |
| 3339 | The module \code{copy} exports two functions: \code{copy()} and |
| 3340 | \code{deepcopy()}. The \code{copy()} function returns a ``shallow'' |
| 3341 | copy of an object; \code{deepcopy()} returns a ``deep'' copy. The |
| 3342 | difference between shallow and deep copying is only relevant for |
| 3343 | compound objects (objects that contain other objects, like lists or |
| 3344 | class instances): |
| 3345 | |
| 3346 | \begin{itemize} |
| 3347 | |
| 3348 | \item |
| 3349 | A shallow copy constructs a new compound object and then (to the |
| 3350 | extent possible) inserts {\em the same objects} into in that the |
| 3351 | original contains. |
| 3352 | |
| 3353 | \item |
| 3354 | A deep copy constructs a new compound object and then, recursively, |
| 3355 | inserts {\em copies} into it of the objects found in the original. |
| 3356 | |
| 3357 | \end{itemize} |
| 3358 | |
| 3359 | Both functions have the same restrictions and use the same protocols |
| 3360 | as \code{pickle} --- user-defined classes can control how they are |
| 3361 | copied by providing methods named \code{__getinitargs__()}, |
| 3362 | \code{__getstate__()} and \code{__setstate__()}. |
| 3363 | |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3364 | |
| 3365 | \section{Documentation Strings} |
| 3366 | |
| 3367 | A variety of objects now have a new attribute, \code{__doc__}, which |
| 3368 | is supposed to contain a documentation string (if no documentation is |
| 3369 | present, the attribute is \code{None}). New syntax, compatible with |
| 3370 | the old interpreter, allows for convenient initialization of the |
| 3371 | \code{__doc__} attribute of modules, classes and functions by placing |
| 3372 | a string literal by itself as the first statement in the suite. It |
| 3373 | must be a literal --- an expression yielding a string object is not |
| 3374 | accepted as a documentation string, since future tools may need to |
| 3375 | derive documentation from source by parsing. |
| 3376 | |
| 3377 | Here is a hypothetical, amply documented module called \code{Spam}: |
| 3378 | |
| 3379 | \begin{verbatim} |
| 3380 | """Spam operations. |
| 3381 | |
| 3382 | This module exports two classes, a function and an exception: |
| 3383 | |
| 3384 | class Spam: full Spam functionality --- three can sizes |
| 3385 | class SpamLight: limited Spam functionality --- only one can size |
| 3386 | |
| 3387 | def open(filename): open a file and return a corresponding Spam or |
| 3388 | SpamLight object |
| 3389 | |
| 3390 | GoneOff: exception raised for errors; should never happen |
| 3391 | |
| 3392 | Note that it is always possible to convert a SpamLight object to a |
| 3393 | Spam object by a simple method call, but that the reverse operation is |
| 3394 | generally costly and may fail for a number of reasons. |
| 3395 | """ |
| 3396 | |
| 3397 | class SpamLight: |
| 3398 | """Limited spam functionality. |
| 3399 | |
| 3400 | Supports a single can size, no flavor, and only hard disks. |
| 3401 | """ |
| 3402 | |
| 3403 | def __init__(self, size=12): |
| 3404 | """Construct a new SpamLight instance. |
| 3405 | |
| 3406 | Argument is the can size. |
| 3407 | """ |
| 3408 | # etc. |
| 3409 | |
| 3410 | # etc. |
| 3411 | |
| 3412 | class Spam(SpamLight): |
| 3413 | """Full spam functionality. |
| 3414 | |
| 3415 | Supports three can sizes, two flavor varieties, and all floppy |
| 3416 | disk formats still supported by current hardware. |
| 3417 | """ |
| 3418 | |
| 3419 | def __init__(self, size1=8, size2=12, size3=20): |
| 3420 | """Construct a new Spam instance. |
| 3421 | |
| 3422 | Arguments are up to three can sizes. |
| 3423 | """ |
| 3424 | # etc. |
| 3425 | |
| 3426 | # etc. |
| 3427 | |
| 3428 | def open(filename = "/dev/null"): |
| 3429 | """Open a can of Spam. |
| 3430 | |
| 3431 | Argument must be an existing file. |
| 3432 | """ |
| 3433 | # etc. |
| 3434 | |
| 3435 | class GoneOff: |
| 3436 | """Class used for Spam exceptions. |
| 3437 | |
| 3438 | There shouldn't be any. |
| 3439 | """ |
| 3440 | pass |
| 3441 | \end{verbatim} |
| 3442 | |
| 3443 | After executing ``\code{import Spam}'', the following expressions |
| 3444 | return the various documentation strings from the module: |
| 3445 | |
| 3446 | \begin{verbatim} |
| 3447 | Spam.__doc__ |
| 3448 | Spam.SpamLight.__doc__ |
| 3449 | Spam.SpamLight.__init__.__doc__ |
| 3450 | Spam.Spam.__doc__ |
| 3451 | Spam.Spam.__init__.__doc__ |
| 3452 | Spam.open.__doc__ |
| 3453 | Spam.GoneOff.__doc__ |
| 3454 | \end{verbatim} |
| 3455 | |
| 3456 | There are emerging conventions about the content and formatting of |
| 3457 | documentation strings. |
| 3458 | |
| 3459 | The first line should always be a short, concise summary of the |
| 3460 | object's purpose. For brevity, it should not explicitly state the |
| 3461 | object's name or type, since these are available by other means |
| 3462 | (except if the name happens to be a verb describing a function's |
| 3463 | operation). This line should begin with a capital letter and end with |
| 3464 | a period. |
| 3465 | |
| 3466 | If there are more lines in the documentation string, the second line |
| 3467 | should be blank, visually separating the summary from the rest of the |
| 3468 | description. The following lines should be one of more of paragraphs |
| 3469 | describing the objects calling conventions, its side effects, etc. |
| 3470 | |
| 3471 | Some people like to copy the Emacs convention of using UPPER CASE for |
| 3472 | function parameters --- this often saves a few words or lines. |
| 3473 | |
| 3474 | The Python parser does not strip indentation from multi-line string |
| 3475 | literals in Python, so tools that process documentation have to strip |
| 3476 | indentation. This is done using the following convention. The first |
| 3477 | non-blank line {\em after} the first line of the string determines the |
| 3478 | amount of indentation for the entire documentation string. (We can't |
| 3479 | use the first line since it is generally adjacent to the string's |
| 3480 | opening quotes so its indentation is not apparent in the string |
| 3481 | literal.) Whitespace ``equivalent'' to this indentation is then |
| 3482 | stripped from the start of all lines of the string. Lines that are |
| 3483 | indented less should not occur, but if they occur all their leading |
| 3484 | whitespace should be stripped. Equivalence of whitespace should be |
| 3485 | tested after expansion of tabs (to 8 spaces, normally). |
| 3486 | |
| 3487 | In this release, few of the built-in or standard functions and modules |
| 3488 | have documentation strings. |
| 3489 | |
| 3490 | |
| 3491 | \section{Customizing Import and Built-Ins} |
| 3492 | |
| 3493 | In preparation for a ``restricted execution mode'' which will be |
| 3494 | usable to run code received from an untrusted source (such as a WWW |
| 3495 | server or client), the mechanism by which modules are imported has |
| 3496 | been redesigned. It is now possible to provide your own function |
| 3497 | \code{__import__} which is called whenever an \code{import} statement |
| 3498 | is executed. There's a built-in function \code{__import__} which |
| 3499 | provides the default implementation, but more interesting, the various |
| 3500 | steps it takes are available separately from the new built-in module |
| 3501 | \code{imp}. (See the section on \code{imp} in the Library Reference |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3502 | Manual for more information on this module --- it also contains a |
Guido van Rossum | abfa2ca | 1995-07-07 22:57:02 +0000 | [diff] [blame] | 3503 | complete example of how to write your own \code{__import__} function.) |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3504 | |
| 3505 | When you do \code{dir()} in a fresh interactive interpreter you will |
| 3506 | see another ``secret'' object that's present in every module: |
| 3507 | \code{__builtins__}. This is either a dictionary or a module |
| 3508 | containing the set of built-in objects used by functions defined in |
| 3509 | current module. Although normally all modules are initialized with a |
| 3510 | reference to the same dictionary, it is now possible to use a |
| 3511 | different set of built-ins on a per-module basis. Together with the |
| 3512 | fact that the \code{import} statement uses the \code{__import__} |
| 3513 | function it finds in the importing modules' dictionary of built-ins, |
| 3514 | this forms the basis for a future restricted execution mode. |
| 3515 | |
| 3516 | |
| 3517 | \section{Python and the World-Wide Web} |
| 3518 | |
| 3519 | There is a growing number of modules available for writing WWW tools. |
| 3520 | The previous release already sported modules \code{gopherlib}, |
Guido van Rossum | bcc9582 | 1995-02-16 16:28:48 +0000 | [diff] [blame] | 3521 | \code{ftplib}, \code{httplib} and \code{urllib} (which unifies the |
| 3522 | other three) for accessing data through the commonest WWW protocols. |
| 3523 | This release also provides \code{cgi}, to ease the writing of |
| 3524 | server-side scripts that use the Common Gateway Interface protocol, |
| 3525 | supported by most WWW servers. The module \code{urlparse} provides |
| 3526 | precise parsing of a URL string into its components (address scheme, |
| 3527 | network location, path, parameters, query, and fragment identifier). |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3528 | |
Guido van Rossum | bcc9582 | 1995-02-16 16:28:48 +0000 | [diff] [blame] | 3529 | A rudimentary, parser for HTML files is available in the module |
| 3530 | \code{htmllib}. It currently supports a subset of HTML 1.0 (if you |
| 3531 | bring it up to date, I'd love to receive your fixes!). Unfortunately |
| 3532 | Python seems to be too slow for real-time parsing and formatting of |
Guido van Rossum | 8675115 | 1995-02-28 17:14:32 +0000 | [diff] [blame] | 3533 | HTML such as required by interactive WWW browsers --- but it's good |
| 3534 | enough to write a ``robot'' (an automated WWW browser that searches |
| 3535 | the web for information). |
Guido van Rossum | 194e57c | 1995-02-15 15:51:38 +0000 | [diff] [blame] | 3536 | |
| 3537 | |
| 3538 | \section{Miscellaneous} |
| 3539 | |
| 3540 | \begin{itemize} |
| 3541 | |
| 3542 | \item |
| 3543 | The \code{socket} module now exports all the needed constants used for |
| 3544 | socket operations, such as \code{SO_BROADCAST}. |
| 3545 | |
| 3546 | \item |
| 3547 | The functions \code{popen()} and \code{fdopen()} in the \code{os} |
| 3548 | module now follow the pattern of the built-in function \code{open()}: |
| 3549 | the default mode argument is \code{'r'} and the optional third |
| 3550 | argument specifies the buffer size, where \code{0} means unbuffered, |
| 3551 | \code{1} means line-buffered, and any larger number means the size of |
| 3552 | the buffer in bytes. |
| 3553 | |
| 3554 | \end{itemize} |
| 3555 | |
| 3556 | |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3557 | \chapter{New in Release 1.3} |
| 3558 | |
| 3559 | |
| 3560 | This chapter describes yet more recent additions to the Python |
| 3561 | language and library. |
| 3562 | |
| 3563 | |
Guido van Rossum | 9beefa2 | 1995-10-08 00:38:51 +0000 | [diff] [blame] | 3564 | \section{Keyword Arguments} |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3565 | |
| 3566 | Functions and methods written in Python can now be called using |
| 3567 | keyword arguments of the form \code{\var{keyword} = \var{value}}. For |
| 3568 | instance, the following function: |
| 3569 | |
| 3570 | \begin{verbatim} |
| 3571 | def parrot(voltage, state='a stiff', action='voom', type='Norwegian Blue'): |
| 3572 | print "-- This parrot wouldn't", action, |
| 3573 | print "if you put", voltage, "Volts through it." |
| 3574 | print "-- Lovely plumage, the", type |
| 3575 | print "-- It's", state, "!" |
| 3576 | \end{verbatim} |
| 3577 | |
| 3578 | could be called in any of the following ways: |
| 3579 | |
| 3580 | \begin{verbatim} |
| 3581 | parrot(1000) |
| 3582 | parrot(action = 'VOOOOOM', voltage = 1000000) |
| 3583 | parrot('a thousand', state = 'pushing up the daisies') |
| 3584 | parrot('a million', 'bereft of life', 'jump') |
| 3585 | \end{verbatim} |
| 3586 | |
| 3587 | but the following calls would all be invalid: |
| 3588 | |
| 3589 | \begin{verbatim} |
| 3590 | parrot() # required argument missing |
| 3591 | parrot(voltage=5.0, 'dead') # non-keyword argument following keyword |
| 3592 | parrot(110, voltage=220) # duplicate value for argument |
| 3593 | parrot(actor='John Cleese') # unknown keyword |
| 3594 | \end{verbatim} |
| 3595 | |
| 3596 | In general, an argument list must have the form: zero or more |
| 3597 | positional arguments followed by zero or more keyword arguments, where |
| 3598 | the keywords must be chosen from the formal parameter names. It's not |
| 3599 | important whether a formal parameter has a default value or not. No |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3600 | argument must receive a value more than once --- formal parameter names |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3601 | corresponding to positional arguments cannot be used as keywords in |
| 3602 | the same calls. |
| 3603 | |
| 3604 | Note that no special syntax is required to allow a function to be |
| 3605 | called with keyword arguments. The additional costs incurred by |
| 3606 | keyword arguments are only present when a call uses them. |
| 3607 | |
| 3608 | (As far as I know, these rules are exactly the same as used by |
| 3609 | Modula-3, even if they are enforced by totally different means. This |
| 3610 | is intentional.) |
| 3611 | |
| 3612 | When a final formal parameter of the form \code{**\var{name}} is |
| 3613 | present, it receives a dictionary containing all keyword arguments |
| 3614 | whose keyword doesn't correspond to a formal parameter. This may be |
| 3615 | combined with a formal parameter of the form \code{*\var{name}} which |
| 3616 | receives a tuple containing the positional arguments beyond the formal |
| 3617 | parameter list. (\code{*\var{name}} must occur before |
| 3618 | \code{**\var{name}}.) For example, if we define a function like this: |
| 3619 | |
| 3620 | \begin{verbatim} |
| 3621 | def cheeseshop(kind, *arguments, **keywords): |
| 3622 | print "-- Do you have any", kind, '?' |
| 3623 | print "-- I'm sorry, we're all out of", kind |
| 3624 | for arg in arguments: print arg |
| 3625 | print '-'*40 |
| 3626 | for kw in keywords.keys(): print kw, ':', keywords[kw] |
| 3627 | \end{verbatim} |
| 3628 | |
| 3629 | It could be called like this: |
| 3630 | |
| 3631 | \begin{verbatim} |
| 3632 | cheeseshop('Limburger', "It's very runny, sir.", |
| 3633 | "It's really very, VERY runny, sir.", |
| 3634 | client='John Cleese', |
| 3635 | shopkeeper='Michael Palin', |
| 3636 | sketch='Cheese Shop Sketch') |
| 3637 | \end{verbatim} |
| 3638 | |
| 3639 | and of course it would print: |
| 3640 | |
| 3641 | \begin{verbatim} |
| 3642 | -- Do you have any Limburger ? |
| 3643 | -- I'm sorry, we're all out of Limburger |
| 3644 | It's very runny, sir. |
| 3645 | It's really very, VERY runny, sir. |
| 3646 | ---------------------------------------- |
| 3647 | client : John Cleese |
| 3648 | shopkeeper : Michael Palin |
| 3649 | sketch : Cheese Shop Sketch |
| 3650 | \end{verbatim} |
| 3651 | |
Guido van Rossum | 691d4ec | 1995-10-08 01:14:57 +0000 | [diff] [blame] | 3652 | Consequences of this change include: |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3653 | |
| 3654 | \begin{itemize} |
| 3655 | |
| 3656 | \item |
Guido van Rossum | 691d4ec | 1995-10-08 01:14:57 +0000 | [diff] [blame] | 3657 | The built-in function \code{apply()} now has an optional third |
| 3658 | argument, which is a dictionary specifying any keyword arguments to be |
| 3659 | passed. For example, |
| 3660 | \begin{verbatim} |
| 3661 | apply(parrot, (), {'voltage': 20, 'action': 'voomm'}) |
| 3662 | \end{verbatim} |
| 3663 | is equivalent to |
| 3664 | \begin{verbatim} |
| 3665 | parrot(voltage=20, action='voomm') |
| 3666 | \end{verbatim} |
| 3667 | |
| 3668 | \item |
| 3669 | There is also a mechanism for functions and methods defined in an |
| 3670 | extension module (i.e., implemented in C or C++) to receive a |
| 3671 | dictionary of their keyword arguments. By default, such functions do |
| 3672 | not accept keyword arguments, since the argument names are not |
| 3673 | available to the interpreter. |
| 3674 | |
| 3675 | \item |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3676 | In the effort of implementing keyword arguments, function and |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3677 | especially method calls have been sped up significantly --- for a |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3678 | method with ten formal parameters, the call overhead has been cut in |
| 3679 | half; for a function with one formal parameters, the overhead has been |
| 3680 | reduced by a third. |
| 3681 | |
| 3682 | \item |
| 3683 | The format of \code{.pyc} files has changed (again). |
| 3684 | |
Guido van Rossum | 9beefa2 | 1995-10-08 00:38:51 +0000 | [diff] [blame] | 3685 | \item |
| 3686 | The \code{access} statement has been disabled. The syntax is still |
| 3687 | recognized but no code is generated for it. (There were some |
| 3688 | unpleasant interactions with changes for keyword arguments, and my |
| 3689 | plan is to get rid of \code{access} altogether in favor of a different |
| 3690 | approach.) |
| 3691 | |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3692 | \end{itemize} |
| 3693 | |
Guido van Rossum | 9beefa2 | 1995-10-08 00:38:51 +0000 | [diff] [blame] | 3694 | \section{Changes to the WWW and Internet tools} |
| 3695 | |
| 3696 | \begin{itemize} |
| 3697 | |
| 3698 | \item |
| 3699 | The \code{htmllib} module has been rewritten in an incompatible |
| 3700 | fashion. The new version is considerably more complete (HTML 2.0 |
| 3701 | except forms, but including all ISO-8859-1 entity definitions), and |
| 3702 | easy to use. Small changes to \code{sgmllib} have also been made, to |
| 3703 | better match the tokenization of HTML as recognized by other web |
| 3704 | tools. |
| 3705 | |
| 3706 | \item |
| 3707 | A new module \code{formatter} has been added, for use with the new |
| 3708 | \code{htmllib} module. |
| 3709 | |
| 3710 | \item |
| 3711 | The \code{urllib}and \code{httplib} modules have been changed somewhat |
| 3712 | to allow overriding unknown URL types and to support authentication. |
| 3713 | They now use \code{mimetools.Message} instead of \code{rfc822.Message} |
| 3714 | to parse headers. The \code{endrequest()} method has been removed |
| 3715 | from the HTTP class since it breaks the interaction with some servers. |
| 3716 | |
| 3717 | \item |
| 3718 | The \code{rfc822.Message} class has been changed to allow a flag to be |
| 3719 | passed in that says that the file is unseekable. |
| 3720 | |
| 3721 | \item |
| 3722 | The \code{ftplib} module has been fixed to be (hopefully) more robust |
| 3723 | on Linux. |
| 3724 | |
| 3725 | \item |
| 3726 | Several new operations that are optionally supported by servers have |
| 3727 | been added to \code{nntplib}: \code{xover}, \code{xgtitle}, |
| 3728 | \code{xpath} and \code{date}. % thanks to Kevan Heydon |
| 3729 | |
| 3730 | \end{itemize} |
| 3731 | |
| 3732 | \section{Other Language Changes} |
| 3733 | |
| 3734 | \begin{itemize} |
| 3735 | |
| 3736 | \item |
| 3737 | The \code{raise} statement now takes an optional argument which |
| 3738 | specifies the traceback to be used when printing the exception's stack |
| 3739 | trace. This must be a traceback object, such as found in |
| 3740 | \code{sys.exc_traceback}. When omitted or given as \code{None}, the |
| 3741 | old behavior (to generate a stack trace entry for the current stack |
| 3742 | frame) is used. |
| 3743 | |
| 3744 | \item |
| 3745 | The tokenizer is now more tolerant of alien whitespace. Control-L in |
| 3746 | the leading whitespace of a line resets the column number to zero, |
| 3747 | while Control-R just before the end of the line is ignored. |
| 3748 | |
| 3749 | \end{itemize} |
| 3750 | |
| 3751 | \section{Changes to Built-in Operations} |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3752 | |
| 3753 | \begin{itemize} |
| 3754 | |
| 3755 | \item |
| 3756 | For file objects, \code{\var{f}.read(0)} and |
| 3757 | \code{\var{f}.readline(0)} now return an empty string rather than |
| 3758 | reading an unlimited number of bytes. For the latter, omit the |
| 3759 | argument altogether or pass a negative value. |
| 3760 | |
| 3761 | \item |
| 3762 | A new system variable, \code{sys.platform}, has been added. It |
| 3763 | specifies the current platform, e.g. \code{sunos5} or \code{linux1}. |
| 3764 | |
| 3765 | \item |
| 3766 | The built-in functions \code{input()} and \code{raw_input()} now use |
| 3767 | the GNU readline library when it has been configured (formerly, only |
| 3768 | interactive input to the interpreter itself was read using GNU |
| 3769 | readline). The GNU readline library provides elaborate line editing |
| 3770 | and history. The Python debugger (\code{pdb}) is the first |
| 3771 | beneficiary of this change. |
| 3772 | |
| 3773 | \item |
| 3774 | Two new built-in functions, \code{globals()} and \code{locals()}, |
| 3775 | provide access to dictionaries containming current global and local |
| 3776 | variables, respectively. (These augment rather than replace |
| 3777 | \code{vars()}, which returns the current local variables when called |
| 3778 | without an argument, and a module's global variables when called with |
| 3779 | an argument of type module.) |
| 3780 | |
| 3781 | \item |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3782 | The built-in function \code{compile()} now takes a third possible |
| 3783 | value for the kind of code to be compiled: specifying \code{'single'} |
| 3784 | generates code for a single interactive statement, which prints the |
| 3785 | output of expression statements that evaluate to something else than |
| 3786 | \code{None}. |
| 3787 | |
Guido van Rossum | 9beefa2 | 1995-10-08 00:38:51 +0000 | [diff] [blame] | 3788 | \end{itemize} |
| 3789 | |
| 3790 | \section{Library Changes} |
| 3791 | |
| 3792 | \begin{itemize} |
| 3793 | |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3794 | \item |
Guido van Rossum | 691d4ec | 1995-10-08 01:14:57 +0000 | [diff] [blame] | 3795 | There are new module \code{ni} and \code{ihooks} that support |
| 3796 | importing modules with hierarchical names such as \code{A.B.C}. This |
| 3797 | is enabled by writing \code{import ni; ni.ni()} at the very top of the |
| 3798 | main program. These modules are amply documented in the Python |
| 3799 | source. |
| 3800 | |
| 3801 | \item |
| 3802 | The module \code{rexec} has been rewritten (incompatibly) to define a |
| 3803 | class and to use \code{ihooks}. |
| 3804 | |
| 3805 | \item |
Guido van Rossum | 9beefa2 | 1995-10-08 00:38:51 +0000 | [diff] [blame] | 3806 | The \code{string.split()} and \code{string.splitfields()} functions |
| 3807 | are now the same function (the presence or absence of the second |
| 3808 | argument determines which operation is invoked); similar for |
| 3809 | \code{string.join()} and \code{string.joinfields()}. |
| 3810 | |
| 3811 | \item |
| 3812 | The \code{Tkinter} module and its helper \code{Dialog} have been |
| 3813 | revamped to use keyword arguments. Tk 4.0 is now the standard. A new |
| 3814 | module \code{FileDialog} has been added which implements standard file |
| 3815 | selection dialogs. |
| 3816 | |
| 3817 | \item |
| 3818 | The optional built-in modules \code{dbm} and \code{gdbm} are more |
| 3819 | coordinated --- their \code{open()} functions now take the same values |
| 3820 | for their \var{flag} argument, and the \var{flag} and \var{mode} |
| 3821 | argument have default values (to open the database for reading only, |
| 3822 | and to create the database with mode \code{0666} minuse the umask, |
| 3823 | respectively). The memory leaks have finally been fixed. |
| 3824 | |
| 3825 | \item |
| 3826 | A new dbm-like module, \code{bsddb}, has been added, which uses the |
| 3827 | BSD DB package's hash method. % thanks to David Ely |
| 3828 | |
| 3829 | \item |
| 3830 | A portable (though slow) dbm-clone, implemented in Python, has been |
| 3831 | added for systems where none of the above is provided. It is aptly |
| 3832 | dubbed \code{dumbdbm}. |
| 3833 | |
| 3834 | \item |
| 3835 | The module \code{anydbm} provides a unified interface to \code{bsddb}, |
| 3836 | \code{gdbm}, \code{dbm}, and \code{dumbdbm}, choosing the first one |
| 3837 | available. |
| 3838 | |
| 3839 | \item |
| 3840 | A new extension module, \code{binascii}, provides a variety of |
| 3841 | operations for conversion of text-encoded binary data. |
| 3842 | |
| 3843 | \item |
| 3844 | There are three new or rewritten companion modules implemented in |
| 3845 | Python that can encode and decode the most common such formats: |
| 3846 | \code{uu} (uuencode), \code{base64} and \code{binhex}. |
| 3847 | |
| 3848 | \item |
| 3849 | A module to handle the MIME encoding quoted-printable has also been |
| 3850 | added: \code{quopri}. |
| 3851 | |
Guido van Rossum | aa93ca8 | 1995-10-11 17:47:45 +0000 | [diff] [blame] | 3852 | \item |
| 3853 | The parser module (which provides an interface to the Python parser's |
| 3854 | abstract syntax trees) has been rewritten (incompatibly) by Fred |
| 3855 | Drake. It now lets you change the parse tree and compile the result! |
| 3856 | |
Guido van Rossum | bf032a9 | 1995-10-11 19:28:39 +0000 | [diff] [blame] | 3857 | \item |
| 3858 | The \code{syslog} module has been upgraded and documented. |
| 3859 | % thanks to Steve Clift |
| 3860 | |
Guido van Rossum | 9beefa2 | 1995-10-08 00:38:51 +0000 | [diff] [blame] | 3861 | \end{itemize} |
| 3862 | |
| 3863 | \section{Other Changes} |
| 3864 | |
| 3865 | \begin{itemize} |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3866 | |
| 3867 | \item |
| 3868 | The dynamic module loader recognizes the fact that different filenames |
| 3869 | point to the same shared library and loads the library only once, so |
| 3870 | you can have a single shared library that defines multiple modules. |
| 3871 | (SunOS / SVR4 style shared libraries only.) |
| 3872 | |
| 3873 | \item |
| 3874 | Jim Fulton's ``abstract object interface'' has been incorporated into |
| 3875 | the run-time API. For more detailes, read the files |
| 3876 | \code{Include/abstract.h} and \code{Objects/abstract.c}. |
| 3877 | |
| 3878 | \item |
Guido van Rossum | 9beefa2 | 1995-10-08 00:38:51 +0000 | [diff] [blame] | 3879 | The Macintosh version is much more robust now. |
| 3880 | |
| 3881 | \item |
Guido van Rossum | eafe32a | 1995-08-10 14:18:10 +0000 | [diff] [blame] | 3882 | Numerous things I have forgotten or that are so obscure no-one will |
| 3883 | notice them anyway :-) |
| 3884 | |
| 3885 | \end{itemize} |
| 3886 | |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3887 | |
| 3888 | \chapter{New in Release 1.4} |
| 3889 | |
| 3890 | |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3891 | This chapter describes the major additions to the Python language and |
| 3892 | library in version 1.4. Many minor changes are not listed here; |
| 3893 | it is recommended to read the file \code{Misc/NEWS} in the Python |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3894 | source distribution for a complete listing of changes. In particular, |
| 3895 | changes that only affect C programmers or the build and installation |
| 3896 | process are not described in this chapter (the new installation |
| 3897 | lay-out is explained below under \code{sys.prefix} though). |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3898 | |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 3899 | \section{Language Changes} |
| 3900 | |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3901 | \begin{itemize} |
| 3902 | |
| 3903 | \item |
| 3904 | Power operator. \code{x**y} is equivalent to \code{pow(x, y)}. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3905 | This operator binds more tightly than \code{*}, \code{/} or \code{\%}, |
| 3906 | and binds from right to left when repeated or combined with unary |
| 3907 | operators. For example, \code{x**y**z} is equivalent to |
| 3908 | \code{x**(y**z)}, and \code{-x**y} is \code{-(x**y)}. |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3909 | |
| 3910 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3911 | Complex numbers. Imaginary literals are writen with a \code{'j'} |
| 3912 | suffix (\code{'J'} is allowed as well.) Complex numbers with a nonzero |
| 3913 | real component are written as \code{(\var{real}+\var{imag}j)}. You |
| 3914 | can also use the new built-in function \code{complex()} which takes |
| 3915 | one or two arguments: \code{complex(x)} is equivalent to \code{x + |
| 3916 | 0j}, and \code{complex(x, y)} is \code{x + y*0j}. For example, |
| 3917 | \code{1j**2} yields \code{complex(-1.0)} (which is another way of |
| 3918 | saying ``the real value 1.0 represented as a complex number.'' |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3919 | |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3920 | Complex numbers are always represented as two floating point numbers, |
| 3921 | the real and imaginary part. |
| 3922 | To extract these parts from a complex number \code{z}, |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3923 | use \code{z.real} and \code{z.imag}. The conversion functions to |
| 3924 | floating point and integer (\code{float()}, \code{int()} and |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3925 | \code{long()}) don't work for complex numbers --- there is no one |
| 3926 | correct way to convert a complex number to a real number. Use |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3927 | \code{abs(z)} to get its magnitude (as a float) or \code{z.real} to |
| 3928 | get its real part. |
| 3929 | |
| 3930 | Module \code{cmath} provides versions of all math functions that take |
| 3931 | complex arguments and return complex results. (Module \code{math} |
| 3932 | only supports real numbers, so that \code{math.sqrt(-1)} still raises |
| 3933 | a \code{ValueError} exception. Numerical experts agree that this is |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3934 | the way it should be.) |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3935 | |
| 3936 | \item |
| 3937 | New indexing syntax. It is now possible to use a tuple as an indexing |
| 3938 | expression for a mapping object without parenthesizing it, |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3939 | e.g. \code{x[1, 2, 3]} is equivalent to \code{x[(1, 2, 3)]}. |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3940 | |
| 3941 | \item |
| 3942 | New slicing syntax. In support of the Numerical Python extension |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3943 | (distributed independently), slice indices of the form |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3944 | \code{x[lo:hi:stride]} are possible, multiple slice indices separated by |
Guido van Rossum | 76e47f3 | 1996-11-02 17:05:21 +0000 | [diff] [blame] | 3945 | commas are allowed, and an index position may be replaced by an ellipsis, |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3946 | as follows: \code{x[a, ..., z]}. There's also a new built-in function |
| 3947 | \code{slice(lo, hi, stride)} and a new built-in object |
Guido van Rossum | 76e47f3 | 1996-11-02 17:05:21 +0000 | [diff] [blame] | 3948 | \code{Ellipsis}, which yield the same effect without using special |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3949 | syntax. None of the standard sequence types support indexing with |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3950 | slice objects or ellipses yet. |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3951 | |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3952 | Note that when this new slicing syntax is used, the mapping interface |
| 3953 | will be used, not the sequence interface. In particular, when a |
| 3954 | user-defined class instance is sliced using this new slicing syntax, |
| 3955 | its \code{__getitem__} method is invoked --- the |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3956 | \code{__getslice__} method is only invoked when a single old-style |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3957 | slice is used, i.e. \code{x[lo:hi]}, with possible omission of |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3958 | \code{lo} and/or \code{hi}. Some examples: |
| 3959 | |
| 3960 | \begin{verbatim} |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3961 | x[0:10:2] -> slice(0, 10, 2) |
| 3962 | x[:2:] -> slice(None, 2, None) |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 3963 | x[::-1] -> slice(None, None, -1) |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3964 | x[::] -> slice(None, None, None) |
| 3965 | x[1, 2:3] -> (1, slice(2, 3, None)) |
| 3966 | x[1:2, 3:4] -> (slice(1, 2, None), slice(3, 4, None)) |
Guido van Rossum | 76e47f3 | 1996-11-02 17:05:21 +0000 | [diff] [blame] | 3967 | x[1:2, ..., 3:4] -> (slice(1, 2, None), Ellipsis, |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3968 | slice(3, 4, None)) |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3969 | \end{verbatim} |
| 3970 | |
| 3971 | For more help with this you are referred to the matrix-sig. |
| 3972 | |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 3973 | \item |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3974 | The \code{access} statement is now truly gone; \code{access} is no |
| 3975 | longer a reserved word. This saves a few cycles here and there. |
| 3976 | |
| 3977 | \item |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 3978 | Private variables through name mangling. |
| 3979 | There is now limited support for class-private |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3980 | identifiers. Any identifier of the form \code{__spam} (at least two |
| 3981 | leading underscores, at most one trailing underscore) is now textually |
| 3982 | replaced with \code{_classname__spam}, where \code{classname} is the |
| 3983 | current class name with leading underscore(s) stripped. This mangling |
| 3984 | is done without regard of the syntactic position of the identifier, so |
| 3985 | it can be used to define class-private instance and class variables, |
| 3986 | methods, as well as globals, and even to store instance variables |
| 3987 | private to this class on instances of {\em other} classes. Truncation |
| 3988 | may occur when the mangled name would be longer than 255 characters. |
| 3989 | Outside classes, or when the class name consists of only underscores, |
| 3990 | no mangling occurs. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 3991 | |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 3992 | Name mangling is intended to give classes an easy way to define |
| 3993 | ``private'' instance variables and methods, without having to worry |
| 3994 | about instance variables defined by derived classes, or mucking with |
| 3995 | instance variables by code outside the class. Note that the mangling |
| 3996 | rules are designed mostly to avoid accidents; it still is possible for |
| 3997 | a determined soul to access or modify a variable that is considered |
| 3998 | private. This can even be useful, e.g. for the debugger, and that's |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 3999 | one reason why this loophole is not closed. (Buglet: derivation of a |
| 4000 | class with the same name as the base class makes use of private |
| 4001 | variables of the base class possible.) |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4002 | |
| 4003 | Notice that code passed to \code{exec}, \code{eval()} or |
| 4004 | \code{evalfile()} does not consider the classname of the invoking |
| 4005 | class to be the current class; this is similar to the effect of the |
| 4006 | \code{global} statement, the effect of which is likewise restricted to |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4007 | code that is byte-compiled together. The same restriction applies to |
| 4008 | \code{getattr()}, \code{setattr()} and \code{delattr()}, as well as |
| 4009 | when referencing \code{__dict__} directly. |
| 4010 | |
| 4011 | Here's an example of a class that implements its own |
| 4012 | \code{__getattr__} and \code{__setattr__} methods and stores all |
| 4013 | attributes in a private variable, in a way that works in Python 1.4 as |
| 4014 | well as in previous versions: |
| 4015 | |
| 4016 | \begin{verbatim} |
| 4017 | class VirtualAttributes: |
| 4018 | __vdict = None |
| 4019 | __vdict_name = locals().keys()[0] |
| 4020 | |
| 4021 | def __init__(self): |
| 4022 | self.__dict__[self.__vdict_name] = {} |
| 4023 | |
| 4024 | def __getattr__(self, name): |
| 4025 | return self.__vdict[name] |
| 4026 | |
| 4027 | def __setattr__(self, name, value): |
| 4028 | self.__vdict[name] = value |
| 4029 | \end{verbatim} |
| 4030 | |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4031 | {\em Warning: this is an experimental feature.} To avoid all |
| 4032 | potential problems, refrain from using identifiers starting with |
| 4033 | double underscore except for predefined uses like \code{__init__}. To |
| 4034 | use private names while maintaining future compatibility: refrain from |
| 4035 | using the same private name in classes related via subclassing; avoid |
| 4036 | explicit (manual) mangling/unmangling; and assume that at some point |
| 4037 | in the future, leading double underscore will revert to being just a |
| 4038 | naming convention. Discussion on extensive compile-time declarations |
| 4039 | are currently underway, and it is impossible to predict what solution |
| 4040 | will eventually be chosen for private names. Double leading |
| 4041 | underscore is still a candidate, of course --- just not the only one. |
| 4042 | It is placed in the distribution in the belief that it is useful, and |
| 4043 | so that widespread experience with its use can be gained. It will not |
| 4044 | be removed without providing a better solution and a migration path. |
| 4045 | |
| 4046 | \end{itemize} |
| 4047 | |
| 4048 | \section{Run-time Changes} |
| 4049 | |
| 4050 | \begin{itemize} |
| 4051 | |
| 4052 | \item |
| 4053 | New built-in function \code{list()} converts any sequence to a new list. |
| 4054 | Note that when the argument is a list, the return value is a fresh |
| 4055 | copy, similar to what would be returned by \code{a[:]}. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4056 | |
| 4057 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4058 | Improved syntax error message. Syntax errors detected by the code |
| 4059 | generation phase of the Python bytecode compiler now include a line |
| 4060 | number. The line number is appended in parentheses. It is suppressed |
| 4061 | if the error occurs in line 1 (this usually happens in interactive |
| 4062 | use). |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4063 | |
| 4064 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4065 | Different exception raised. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4066 | Unrecognized keyword arguments now raise a \code{TypeError} exception |
| 4067 | rather than \code{KeyError}. |
| 4068 | |
| 4069 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4070 | Exceptions in \code{__del__} methods. When a \code{__del__} method |
| 4071 | raises an exception, a warning is written to \code{sys.stderr} and the |
| 4072 | exception is ignored. Formerly, such exceptions were ignored without |
| 4073 | warning. (Propagating the exception is not an option since it it is |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4074 | invoked from an object finalizer, which cannot return any kind of |
| 4075 | status or error.) (Buglet: The new behavior, while needed in order to |
| 4076 | debug failing \code{__del__} methods, is occasionally annoying, |
| 4077 | because if affects the program's standard error stream. It honors |
| 4078 | assignments to \code{sys.stderr}, so it can be redirected from within |
| 4079 | a program if desired.) |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4080 | |
| 4081 | \item |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4082 | You can now discover from which file (if any) a module was loaded by |
| 4083 | inspecting its \code{__file__} attribute. This attribute is not |
| 4084 | present for built-in or frozen modules. It points to the shared |
| 4085 | library file for dynamically loaded modules. (Buglet: this may be a |
| 4086 | relative path and is stored in the \code{.pyc} file on compilation. |
| 4087 | If you manipulate the current directory with \code{os.chdir()} or move |
| 4088 | \code{.pyc} files around, the value may be incorrect.) |
| 4089 | |
| 4090 | \end{itemize} |
| 4091 | |
| 4092 | \section{New or Updated Modules} |
| 4093 | |
| 4094 | \begin{itemize} |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4095 | |
| 4096 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4097 | New built-in module \code{operator}. While undocumented, the concept |
| 4098 | is real simply: \code{operator.__add__(x, y)} does exactly the same |
| 4099 | thing as \code{x+y} (for all types --- built-in, user-defined, |
| 4100 | extension-defined). As a convenience, \code{operator.add} does the |
| 4101 | same thing, but beware --- you can't use \code{operator.and} and a few |
| 4102 | others where the ``natural'' name for an operator is a reserved |
| 4103 | keyword. You can add a single trailing underscore in such cases. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4104 | |
| 4105 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4106 | New built-in module \code{errno}. See the Library Reference Manual. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4107 | |
| 4108 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4109 | Rewritten \code{cgi} module. See the Library Reference Manual. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4110 | |
| 4111 | \item |
| 4112 | Improved restricted execution module (\code{rexec}). New module |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4113 | \code{Bastion}. Both are now documented in a new chapter on |
| 4114 | restricted execution in the Library Reference Manual. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4115 | |
| 4116 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4117 | New string operations (all described in the Library Reference Manual): |
| 4118 | \code{lstrip()}, \code{rstrip()} (strip only the left/right |
| 4119 | whitespace), \code{capitalize()} (uppercase the first character, |
| 4120 | lowercase the rest), \code{capwords()} (capitalize each word, |
| 4121 | delimited a la \code{string.split()}), \code{translate()} (string |
| 4122 | transliteration -- this existed before but can now also delete |
| 4123 | characters by specifying a third argument), \code{maketrans()} (a |
| 4124 | convenience function for creating translation tables for |
| 4125 | \code{translate()} and \code{regex.compile()}). The string function |
| 4126 | \code{split()} has an optional third argument which specifies the |
| 4127 | maximum number of separators to split; |
| 4128 | e.g. \code{string.split('a=b=c', '=', 1)} yields \code{['a', 'b=c']}. |
| 4129 | (Note that for a long time, \code{split()} and \code{splitfields()} |
| 4130 | are synonyms. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4131 | |
| 4132 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4133 | New regsub operations (see the Library Reference Manual): |
| 4134 | \code{regsub.capwords()} (like \code{string.capwords()} but allows you to |
| 4135 | specify the word delimiter as a regular expression), |
| 4136 | \code{regsub.splitx()} (like \code{regsub.split()} but returns the |
| 4137 | delimiters as well as the words in the resulting list). The optional |
| 4138 | \code{maxsep} argument is also supported by \code{regsub.split()}. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4139 | |
| 4140 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4141 | Module files \code{pdb.py} and \code{profile.py} can now be invoked as |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4142 | scripts to debug c.q. profile other scripts easily. For example: |
| 4143 | \code{python /usr/local/lib/python1.4/profile.py myscript.py} |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4144 | |
| 4145 | \item |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4146 | The \code{os} module now supports the \code{putenv()} function on |
| 4147 | systems where it is provided in the C library (Windows NT and most |
| 4148 | Unix versions). For example, \code{os.putenv('PATH', |
| 4149 | '/bin:/usr/bin')} sets the environment variable \code{PATH} to the |
| 4150 | string \code{'/bin:/usr/bin'}. Such changes to the environment affect |
| 4151 | subprocesses started with \code{os.system()}, \code{os.popen()} or |
| 4152 | \code{os.fork()} and \code{os.execv()}. When \code{putenv()} is |
| 4153 | supported, assignments to items in \code{os.environ} are automatically |
| 4154 | translated into corresponding calls to \code{os.putenv()}; however, |
| 4155 | calls to \code{os.putenv()} don't update \code{os.environ}, so it is |
| 4156 | actually preferable to assign to items of \code{os.environ}. For this |
| 4157 | purpose, the type of \code{os.environ} is changed to a subclass of |
| 4158 | \code{UserDict.UserDict} when \code{os.putenv()} is supported. |
| 4159 | (Buglet: \code{os.execve()} still requires a real dictionary, so it |
| 4160 | won't accept \code{os.environ} as its third argument. However, you |
| 4161 | can now use \code{os.execv()} and it will use your changes to |
| 4162 | \code{os.environ}!.) |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4163 | |
| 4164 | \item |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4165 | More new functions in the \code{os} module: \code{mkfifo}, |
| 4166 | \code{plock}, \code{remove} (== \code{unlink}), and \code{ftruncate}. |
| 4167 | See the Unix manual (section 2, system calls) for these function. |
| 4168 | More functions are also available under NT. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4169 | |
| 4170 | \item |
Guido van Rossum | 6a05f95 | 1996-10-22 19:27:46 +0000 | [diff] [blame] | 4171 | New functions in the fcntl module: \code{lockf()} and \code{flock()} |
| 4172 | (don't ask \code{:-)}). See the Library Reference Manual. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4173 | |
| 4174 | \item |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4175 | The first item of the module search path, \code{sys.path[0]}, is the |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4176 | directory containing the script that was used to invoke the Python |
| 4177 | interpreter. If the script directory is not available (e.g. if the |
| 4178 | interpreter is invoked interactively or if the script is read from |
| 4179 | standard input), \code{sys.path[0]} is the empty string, which directs |
| 4180 | Python to search modules in the current directory first. Notice that |
| 4181 | the script directory is inserted {\em before} the entries inserted as |
| 4182 | a result of \code{\$PYTHONPATH}. There is no longer an entry for the |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4183 | current directory later in the path (unless explicitly set in |
| 4184 | \code{\$PYTHONPATH} or overridden at build time). |
| 4185 | |
| 4186 | \end{itemize} |
| 4187 | |
| 4188 | \section{Configuration and Installation} |
| 4189 | |
| 4190 | \begin{itemize} |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4191 | |
| 4192 | \item |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4193 | More configuration information is now available to Python programs. |
| 4194 | The variable \code{sys.prefix} gives the site-specific directory |
| 4195 | prefix where the platform independent Python files are installed; by |
| 4196 | default, this is the string \code{"/usr/local"}. This can be set at |
| 4197 | build time with the \code{--prefix} argument to the \code{configure} |
| 4198 | script. The main collection of Python library modules is installed in |
| 4199 | the directory \code{sys.prefix+"/lib/python1.4"} while the platform |
| 4200 | independent header files (all except \code{config.h}) are stored in |
| 4201 | \code{sys.prefix+"/include/python1.4"}. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4202 | |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4203 | Similarly, the variable \code{sys.exec_prefix} gives the site-specific |
| 4204 | directory prefix where the platform {\em de}pendent Python files are |
| 4205 | installed; by default, this is also \code{"/usr/local"}. This can be |
| 4206 | set at build time with the \code{--exec-prefix} argument to the |
| 4207 | \code{configure} script. Specifically, all configuration files |
| 4208 | (e.g. the \code{config.h} header file) are installed in the directory |
| 4209 | \code{sys.exec_prefix+"/lib/python1.4/config"}, and shared library |
| 4210 | modules are installed in |
| 4211 | \code{sys.exec_prefix+"/lib/python1.4/sharedmodules"}. |
| 4212 | |
| 4213 | Include files are at \code{sys.prefix+"/include/python1.4"}. |
| 4214 | |
| 4215 | It is not yet decided what the most portable way is to come up with |
| 4216 | the version number used in these pathnames. For compatibility with |
| 4217 | the 1.4beta releases, sys.version[:3] can be used. |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4218 | |
| 4219 | On non-Unix systems, these variables are meaningless. |
| 4220 | |
| 4221 | \item |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4222 | While sites are strongly discouraged from modifying the standard |
| 4223 | Python library (like adding site-specific modules or functions), there |
| 4224 | is now a standard way to invoke site-specific features. The standard |
| 4225 | module \code{site}, when imported, appends two site-specific |
| 4226 | directories to the end of \code{sys.path}: |
| 4227 | \code{\$prefix/lib/site-python} and |
| 4228 | \code{\$exec_prefix/lib/site-python}, where \code{\$prefix} and |
| 4229 | \code{\$exec_prefix} are the directories \code{sys.prefix} and |
Guido van Rossum | 5812488 | 1996-10-08 17:29:56 +0000 | [diff] [blame] | 4230 | \code{sys.exec_prefix} mentioned above. |
| 4231 | |
Guido van Rossum | 3a26dd8 | 1996-10-24 22:12:48 +0000 | [diff] [blame] | 4232 | After this path manipulation has been performed, an attempt is made to |
| 4233 | import the module \code{sitecustomize}. Any \code{ImportError} |
| 4234 | exception raised by this attempt is silently ignored. |
Guido van Rossum | 97662c8 | 1996-08-23 15:35:47 +0000 | [diff] [blame] | 4235 | |
| 4236 | \end{itemize} |
| 4237 | |
Guido van Rossum | d9bf55d | 1991-01-11 16:35:08 +0000 | [diff] [blame] | 4238 | \end{document} |